Search in sources :

Example 91 with DataHandler

use of javax.activation.DataHandler in project camel by apache.

the class SqlProducerOutputAttachment method testHeaderAndAttachmentAreAvailableAfterProducer.

@Test
public void testHeaderAndAttachmentAreAvailableAfterProducer() throws InterruptedException, MalformedURLException {
    MockEndpoint mock = getMockEndpoint("mock:query");
    DataHandler content = new DataHandler(new URL("http://www.nu.nl"));
    mock.expectedMessageCount(1);
    mock.expectedHeaderReceived(SqlConstants.SQL_ROW_COUNT, 1);
    mock.expectedHeaderReceived("TheProjectID", 1);
    mock.expectedHeaderReceived("maintain", "this");
    mock.expects(() -> {
        assertThat(mock.getReceivedExchanges().get(0).getIn().getAttachments().size(), is(1));
        assertThat(mock.getReceivedExchanges().get(0).getIn().getAttachment("att1"), notNullValue());
        assertThat(mock.getReceivedExchanges().get(0).getIn().getAttachment("att1"), is(content));
    });
    mock.message(0).body().isEqualTo("Hi there!");
    Exchange exchange = context.getEndpoint("direct:query").createExchange();
    exchange.getIn().setBody("Hi there!");
    exchange.getIn().setHeader("myProject", "Camel");
    exchange.getIn().setHeader("maintain", "this");
    exchange.getIn().addAttachment("att1", content);
    template.send("direct:query", exchange);
    assertMockEndpointsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) DataHandler(javax.activation.DataHandler) URL(java.net.URL) Test(org.junit.Test)

Example 92 with DataHandler

use of javax.activation.DataHandler in project gitblit by gitblit.

the class MailService method createMessage.

/**
	 * Create a message.
	 *
	 * @param mailing
	 * @return a message
	 */
public Message createMessage(Mailing mailing) {
    if (mailing.subject == null) {
        mailing.subject = "";
    }
    if (mailing.content == null) {
        mailing.content = "";
    }
    Message message = new MailMessageImpl(session, mailing.id);
    try {
        String fromAddress = settings.getString(Keys.mail.fromAddress, null);
        if (StringUtils.isEmpty(fromAddress)) {
            fromAddress = "gitblit@gitblit.com";
        }
        InternetAddress from = new InternetAddress(fromAddress, mailing.from == null ? "Gitblit" : mailing.from);
        message.setFrom(from);
        Pattern validEmail = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        // validate & add TO recipients
        List<InternetAddress> to = new ArrayList<InternetAddress>();
        for (String address : mailing.toAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    to.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        // validate & add CC recipients
        List<InternetAddress> cc = new ArrayList<InternetAddress>();
        for (String address : mailing.ccAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    cc.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        if (settings.getBoolean(Keys.web.showEmailAddresses, true)) {
            // full disclosure of recipients
            if (to.size() > 0) {
                message.setRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));
            }
            if (cc.size() > 0) {
                message.setRecipients(Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()]));
            }
        } else {
            // everyone is bcc'd
            List<InternetAddress> bcc = new ArrayList<InternetAddress>();
            bcc.addAll(to);
            bcc.addAll(cc);
            message.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
        }
        message.setSentDate(new Date());
        // UTF-8 encode
        message.setSubject(MimeUtility.encodeText(mailing.subject, "utf-8", "B"));
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText(mailing.content, "utf-8");
        if (Mailing.Type.html == mailing.type) {
            messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
        } else {
            messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        }
        MimeMultipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messagePart);
        // handle attachments
        if (mailing.hasAttachments()) {
            for (File file : mailing.attachments) {
                if (file.exists()) {
                    MimeBodyPart filePart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    filePart.setDataHandler(new DataHandler(fds));
                    filePart.setFileName(fds.getName());
                    multiPart.addBodyPart(filePart);
                }
            }
        }
        message.setContent(multiPart);
    } catch (Exception e) {
        logger.error("Failed to properly create message", e);
    }
    return message;
}
Also used : Pattern(java.util.regex.Pattern) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) Date(java.util.Date) MessagingException(javax.mail.MessagingException) SendFailedException(javax.mail.SendFailedException) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 93 with DataHandler

use of javax.activation.DataHandler in project quickstarts by jboss-switchyard.

the class CustomProcessor method process.

@Override
public void process(Exchange exchange) throws Exception {
    String newFileName = "external-switchyard.png";
    DataHandler image = exchange.getIn().getAttachment(exchange.getIn().getBody(String.class));
    exchange.getOut().addAttachment(newFileName, image);
    exchange.getOut().setBody(newFileName);
}
Also used : DataHandler(javax.activation.DataHandler)

Example 94 with DataHandler

use of javax.activation.DataHandler in project quickstarts by jboss-switchyard.

the class SoapAttachmentClient method sendMessage.

public static SOAPMessage sendMessage(String switchyard_web_service) throws Exception {
    SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection connection = conFactory.createConnection();
    MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage msg = msgFactory.createMessage();
    SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(new QName("urn:switchyard-quickstart:soap-attachment:1.0", "echoImage"));
    bodyElement.addTextNode("cid:switchyard.png");
    AttachmentPart ap = msg.createAttachmentPart();
    URL imageUrl = Classes.getResource("switchyard.png");
    ap.setDataHandler(new DataHandler(new URLDataSource(imageUrl)));
    ap.setContentId("switchyard.png");
    msg.addAttachmentPart(ap);
    return connection.call(msg, new URL(switchyard_web_service));
}
Also used : SOAPConnectionFactory(javax.xml.soap.SOAPConnectionFactory) URLDataSource(javax.activation.URLDataSource) MessageFactory(javax.xml.soap.MessageFactory) QName(javax.xml.namespace.QName) SOAPConnection(javax.xml.soap.SOAPConnection) AttachmentPart(javax.xml.soap.AttachmentPart) DataHandler(javax.activation.DataHandler) SOAPMessage(javax.xml.soap.SOAPMessage) URL(java.net.URL) SOAPBodyElement(javax.xml.soap.SOAPBodyElement)

Example 95 with DataHandler

use of javax.activation.DataHandler in project quickstarts by jboss-switchyard.

the class CreateFlightTripMessageComposer method compose.

@Override
public Message compose(CamelBindingData source, Exchange exchange) throws Exception {
    Message response = exchange.createMessage();
    // map context properties
    getContextMapper().mapFrom(source, exchange.getContext(response));
    Set<String> attachements = source.getMessage().getAttachmentNames();
    if (!attachements.isEmpty()) {
        for (Entry<String, DataHandler> entry : source.getMessage().getAttachments().entrySet()) {
            response.addAttachment(entry.getKey(), entry.getValue().getDataSource());
        }
    }
    // Retrieve flight connection and passenger info from exchange context property.
    FlightTripRequestInfo flightTripRequestInfo = (FlightTripRequestInfo) exchange.getContext().getProperty(FLIGHT_TRIP_REQUEST_INFO).getValue();
    FlightConnectionInfo flightConnectionInfo = flightTripRequestInfo.getFlightConnectionInfo();
    PassengerInfo passengerInfo = flightTripRequestInfo.getPassengerInfo();
    // Retrieve SAP response object from body of exchange message.
    Structure flightTripCreateResponse = source.getMessage().getBody(Structure.class);
    if (flightTripCreateResponse == null) {
        throw new Exception("No Flight Trip Create Response");
    }
    // Check BAPI return parameter for errors 
    @SuppressWarnings("unchecked") Table<Structure> bapiReturn = flightTripCreateResponse.get("RETURN", Table.class);
    Structure bapiReturnEntry = bapiReturn.get(0);
    if (!bapiReturnEntry.get("TYPE", String.class).equals("S")) {
        String message = bapiReturnEntry.get("MESSAGE", String.class);
        throw new Exception("BAPI call failed: " + message);
    }
    // Create bean to hold Flight Booking data.
    BookFlightResponse bookFlightResponse = new BookFlightResponse();
    // Trip Number
    String tripNumber = flightTripCreateResponse.get("TRIPNUMBER", String.class);
    if (tripNumber != null) {
        bookFlightResponse.setTripNumber(tripNumber);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added TRIPNUMBER = '{}' to request", tripNumber);
        }
    } else {
        throw new Exception("No Flight Booking Trip Number");
    }
    // Pricing Info
    Structure ticketPrice = flightTripCreateResponse.get("TICKET_PRICE", Structure.class);
    if (ticketPrice != null) {
        // Ticket Price
        BigDecimal tripPrice = ticketPrice.get("TRIPPRICE", BigDecimal.class);
        bookFlightResponse.setTicketPrice(tripPrice);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added TICKET_PRICE = '{}' to request", tripPrice);
        }
        // Ticket Tax
        BigDecimal tripTax = ticketPrice.get("TRIPTAX", BigDecimal.class);
        bookFlightResponse.setTicketTax(tripTax);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added TICKET_TAX = '{}' to request", tripTax);
        }
        // Currency
        String currency = ticketPrice.get("CURR", String.class);
        bookFlightResponse.setCurrency(currency);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added CURRENCY = '{}' to request", currency);
        }
    } else {
        throw new Exception("No Flight Booking Ticket Price");
    }
    // Passenger Info
    //  Form
    bookFlightResponse.setPassengerFormOfAddress(passengerInfo.getFormOfAddress());
    //  Name
    bookFlightResponse.setPassengerName(passengerInfo.getName());
    //  DOB
    bookFlightResponse.setPassengerDateOfBirth(passengerInfo.getDateOfBirth());
    // Flight Info
    FlightInfo flightInfo = new FlightInfo();
    //  Flight Time
    flightInfo.setFlightTime(flightConnectionInfo.getFlightTime());
    //  Departure City
    flightInfo.setCityFrom(flightConnectionInfo.getDepartureCity());
    //  Departure Date
    flightInfo.setDepartureDate(flightConnectionInfo.getDepartureDate());
    //  Departure Time
    flightInfo.setDepartureTime(flightConnectionInfo.getDepartureTime());
    //  Arrival City
    flightInfo.setCityTo(flightConnectionInfo.getArrivalCity());
    //  Arrival Date
    flightInfo.setArrivalDate(flightConnectionInfo.getArrivalDate());
    //  Arrival Time
    flightInfo.setArrivalTime(flightConnectionInfo.getArrivalTime());
    bookFlightResponse.setFlightInfo(flightInfo);
    ConnectionInfoTable connectionInfoTable = new ConnectionInfoTable();
    List<ConnectionInfo> rows = new ArrayList<ConnectionInfo>();
    for (FlightHop flightHop : flightConnectionInfo.getFlightHopList()) {
        // Connection Info
        ConnectionInfo connection = new ConnectionInfo();
        //  Connection ID
        connection.setConnectionId(flightHop.getHopNumber());
        //  Airline
        connection.setAirline(flightHop.getAirlineName());
        //  Plane Type
        connection.setPlaneType(flightHop.getAircraftType());
        //  Departure City
        connection.setCityFrom(flightHop.getDepatureCity());
        //  Departure Date
        connection.setDepartureDate(flightHop.getDepatureDate());
        //  Departure Time
        connection.setDepartureTime(flightHop.getDepatureTime());
        //  Arrival City
        connection.setCityTo(flightHop.getArrivalCity());
        //  Arrival Date
        connection.setArrivalDate(flightHop.getArrivalDate());
        //  Arrival Time
        connection.setArrivalTime(flightHop.getArrivalTime());
        rows.add(connection);
    }
    connectionInfoTable.setRows(rows);
    bookFlightResponse.setConnectionInfo(connectionInfoTable);
    response.setContent(bookFlightResponse);
    return response;
}
Also used : Message(org.switchyard.Message) ConnectionInfoTable(org.switchyard.quickstarts.camel.sap.binding.jaxb.ConnectionInfoTable) ArrayList(java.util.ArrayList) FlightConnectionInfo(org.switchyard.quickstarts.camel.sap.binding.bean.FlightConnectionInfo) PassengerInfo(org.switchyard.quickstarts.camel.sap.binding.bean.PassengerInfo) DataHandler(javax.activation.DataHandler) BigDecimal(java.math.BigDecimal) FlightHop(org.switchyard.quickstarts.camel.sap.binding.bean.FlightHop) FlightInfo(org.switchyard.quickstarts.camel.sap.binding.jaxb.FlightInfo) BookFlightResponse(org.switchyard.quickstarts.camel.sap.binding.jaxb.BookFlightResponse) FlightTripRequestInfo(org.switchyard.quickstarts.camel.sap.binding.bean.FlightTripRequestInfo) ConnectionInfo(org.switchyard.quickstarts.camel.sap.binding.jaxb.ConnectionInfo) FlightConnectionInfo(org.switchyard.quickstarts.camel.sap.binding.bean.FlightConnectionInfo) Structure(org.fusesource.camel.component.sap.model.rfc.Structure)

Aggregations

DataHandler (javax.activation.DataHandler)180 Exchange (org.apache.camel.Exchange)39 MimeBodyPart (javax.mail.internet.MimeBodyPart)38 FileDataSource (javax.activation.FileDataSource)33 Test (org.junit.Test)33 DataSource (javax.activation.DataSource)32 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)29 IOException (java.io.IOException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)25 InputStream (java.io.InputStream)25 MessagingException (javax.mail.MessagingException)25 MimeMultipart (javax.mail.internet.MimeMultipart)25 MimeMessage (javax.mail.internet.MimeMessage)23 ByteArrayInputStream (java.io.ByteArrayInputStream)22 Message (org.apache.camel.Message)21 OMElement (org.apache.axiom.om.OMElement)17 Processor (org.apache.camel.Processor)15 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)14 File (java.io.File)13 PipedInputStream (java.io.PipedInputStream)13