Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:org.apache.synapse.transport.fix.message.FIXMessageBuilder.java

public OMElement processDocument(InputStream inputStream, String contentType, MessageContext messageContext)
        throws AxisFault {
    Reader reader = null;// ww w . j  a  va2  s .c  o m
    StringBuilder messageString = new StringBuilder();
    quickfix.Message message = null;
    try {
        String charSetEncoding = (String) messageContext
                .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
        if (charSetEncoding == null) {
            charSetEncoding = MessageContext.DEFAULT_CHAR_SET_ENCODING;
        }
        reader = new InputStreamReader(inputStream, charSetEncoding);
        try {
            int data = reader.read();
            while (data != -1) {
                char dataChar = (char) data;
                data = reader.read();
                messageString.append(dataChar);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("Error In creating FIX SOAP envelope ...", e);
            throw new AxisFault(e.getMessage());
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Error In creating FIX SOAP envelope ...", e);
        throw new AxisFault(e.getMessage());
    }

    try {
        DefaultDataDictionaryProvider dataDictionary = new DefaultDataDictionaryProvider();
        String beginString = MessageUtils.getStringField(messageString.toString(), BeginString.FIELD);
        DataDictionary dataDic = dataDictionary.getSessionDataDictionary(beginString);
        message = new quickfix.Message(messageString.toString(), null, false);
    } catch (InvalidMessage e) {
        // TODO Auto-generated catch block
        log.error("Error In creating FIX SOAP envelope ...", e);
        throw new AxisFault(e.getMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug("Creating SOAP envelope for FIX message...");
    }

    SOAPFactory soapFactory = new SOAP11Factory();
    OMElement msg = soapFactory.createOMElement(FIXConstants.FIX_MESSAGE, null);
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_INCOMING_SESSION, null, ""));
    msg.addAttribute(
            soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_COUNTER, null, String.valueOf("-1")));

    OMElement header = soapFactory.createOMElement(FIXConstants.FIX_HEADER, null);
    OMElement body = soapFactory.createOMElement(FIXConstants.FIX_BODY, null);
    OMElement trailer = soapFactory.createOMElement(FIXConstants.FIX_TRAILER, null);

    // process FIX header
    Iterator<quickfix.Field<?>> iter = message.getHeader().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            quickfix.Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null,
                    String.valueOf(field.getTag())));
            Object value = field.getObject();

            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = messageContext.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                soapFactory.createOMText(msgField, value.toString(), OMElement.CDATA_SECTION_NODE);
            }
            header.addChild(msgField);
        }
    }
    // process FIX body
    convertFIXBodyToXML(message, body, soapFactory, messageContext);

    // process FIX trailer
    iter = message.getTrailer().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            quickfix.Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null,
                    String.valueOf(field.getTag())));
            Object value = field.getObject();

            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = messageContext.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                soapFactory.createOMText(msgField, value.toString(), OMElement.CDATA_SECTION_NODE);
            }
            trailer.addChild(msgField);
        }
    }

    msg.addChild(header);
    msg.addChild(body);
    msg.addChild(trailer);
    SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(msg);
    messageContext.setEnvelope(envelope);

    return msg;
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }//from  www.ja  va2s. co m
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();/*from   ww  w.  ja v a2  s  .c  o  m*/

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.apache.axis2.datasource.jaxb.JAXBAttachmentMarshaller.java

public String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String namespace,
        String localPart) {//from   ww w. ja  va 2 s  . co m

    if (offset != 0 || length != data.length) {
        int len = length - offset;
        byte[] newData = new byte[len];
        System.arraycopy(data, offset, newData, 0, len);
        data = newData;
    }

    if (mimeType == null || mimeType.length() == 0) {
        mimeType = APPLICATION_OCTET;
    }

    if (log.isDebugEnabled()) {
        log.debug("Adding MTOM/XOP byte array attachment for element: " + "{" + namespace + "}" + localPart);
    }

    String cid = null;

    try {
        // Create MIME Body Part
        final InternetHeaders ih = new InternetHeaders();
        final byte[] dataArray = data;
        ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeType);
        final MimeBodyPart mbp = (MimeBodyPart) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return new MimeBodyPart(ih, dataArray);
                } catch (MessagingException e) {
                    throw new OMException(e);
                }
            }
        });

        //Create a data source for the MIME Body Part
        MimePartDataSource mpds = (MimePartDataSource) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new MimePartDataSource(mbp);
            }
        });
        long dataLength = data.length;
        Integer value = null;
        if (msgContext != null) {
            value = (Integer) msgContext.getProperty(Constants.Configuration.MTOM_THRESHOLD);
        } else if (log.isDebugEnabled()) {
            log.debug(
                    "The msgContext is null so the MTOM threshold value can not be determined; it will default to 0.");
        }

        int optimizedThreshold = (value != null) ? value.intValue() : 0;

        if (optimizedThreshold == 0 || dataLength > optimizedThreshold) {
            DataHandler dataHandler = new DataHandler(mpds);
            cid = addDataHandler(dataHandler, false);
        }

        // Add the content id to the mime body part
        mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
    } catch (MessagingException e) {
        throw new OMException(e);
    }

    return cid == null ? null : "cid:" + cid;
}

From source file:de.extra.client.plugins.outputplugin.mtomws.WsCxfIT.java

/**
 * Fhrt zu dem RequestTransport InputFile
 * /*from  ww  w . j ava2s  .co  m*/
 * @param requestTransport
 * @param inputFile
 * @return
 */
private RequestTransport fillInputFile(final RequestTransport requestTransport, final File inputFile) {
    final Base64CharSequenceType base64CharSequence = requestTransport.getTransportBody().getData()
            .getBase64CharSequence();
    final DataSource source = new FileDataSource(inputFile);
    base64CharSequence.setValue(new DataHandler(source));

    return requestTransport;

}

From source file:org.wso2.appserver.integration.resources.resource.test.RegistryResourceTestCase.java

@Test(groups = { "wso2.as" }, dependsOnMethods = "testCreateCollection")
public void testAddResourceFromURL() throws MalformedURLException, ResourceAdminServiceExceptionException,
        RemoteException, RegistryExceptionException {
    boolean isFound = false;
    String JAR_URL = "http://dist.wso2.org/maven2/org/wso2/carbon/org.wso2.carbon."
            + "registry.profiles.ui/3.0.0/org.wso2.carbon.registry.profiles." + "ui-3.0.0.jar";
    String JAR_NAME = "org.wso2.carbon.registry.profiles.ui-3.0.0.jar";
    resourceAdminServiceClient.addResource(PARENT_PATH + "/" + WSO2_COLL + "/" + JAR_NAME,
            "application/java-archive", "resource added from external URL", new DataHandler(new URL(JAR_URL)));
    ResourceTreeEntryBean resourceTreeEntryBean = resourceAdminServiceClient
            .getResourceTreeEntryBean(PARENT_PATH + "/" + WSO2_COLL);
    String[] resourceChild = resourceTreeEntryBean.getChildren();
    for (int childCount = 0; childCount <= resourceChild.length; childCount++) {
        if (resourceChild[childCount].equalsIgnoreCase(PARENT_PATH + "/" + WSO2_COLL + "/" + JAR_NAME)) {
            isFound = true;/*  www  .  j a v  a 2s .c om*/
            break;
        }
    }

    assertTrue(isFound, "uploaded resource not found in " + PARENT_PATH + "/" + WSO2_COLL);
}

From source file:be.medx.mcn.SendRequestMapper.java

public static be.cin.types.v1.Blob mapBlobToCinBlob(final Blob blob) {
    final be.cin.types.v1.Blob result = new be.cin.types.v1.Blob();
    final ByteArrayDatasource rawData = new ByteArrayDatasource(blob.getContent());
    final DataHandler dh = new DataHandler(rawData);
    result.setValue(dh);/* w ww  .  ja va  2s  .c o  m*/
    result.setMessageName(blob.getMessageName());
    result.setId(blob.getId());
    result.setContentEncoding(blob.getContentEncoding());
    result.setHashValue(blob.getHashValue());
    result.setContentType(blob.getContentType());
    return result;
}

From source file:org.wso2.bam.integration.tests.toolbox.CustomToolBoxTestCase.java

private Object[] getToolBox() throws Exception {
    BAMToolboxDepolyerServiceStub.BasicToolBox[] toolBoxes = toolboxStub.getBasicToolBoxes();
    if (null == toolBoxes || toolBoxes.length == 0) {
        throw new Exception("No default toolboxes available..");
    }/*from  w ww .  j av a 2  s  .  co m*/
    String toolBoxLocation = toolBoxes[0].getLocation();

    File toolBox = new File(toolBoxLocation);
    FileDataSource dataSource = new FileDataSource(toolBox);
    Object[] result = new Object[2];

    result[0] = new DataHandler(dataSource);
    result[1] = toolBoxes[0].getTBoxFileName();
    return result;
}

From source file:org.wf.dp.dniprorada.util.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {/* w ww  .ja va  2  s.  c o m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        log.info("[_Attach:oURL]:sName=" + sName);
    } catch (Exception oException) {
        log.error("[_Attach:oURL]:sName=" + sName, oException);
    }
    return this;
}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }//from  w  w w . jav  a2s.com
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}