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();
}
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;
}
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);
}
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));
}
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;
}
Aggregations