use of org.apache.camel.TypeConverter in project camel by apache.
the class DefaultNettyHttpBinding method toNettyRequest.
@Override
public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration) throws Exception {
LOG.trace("toNettyRequest: {}", message);
// the message body may already be a Netty HTTP response
if (message.getBody() instanceof HttpRequest) {
return (HttpRequest) message.getBody();
}
String uriForRequest = uri;
if (configuration.isUseRelativePath()) {
int indexOfPath = uri.indexOf((new URI(uri)).getPath());
if (indexOfPath > 0) {
uriForRequest = uri.substring(indexOfPath);
}
}
// just assume GET for now, we will later change that to the actual method to use
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriForRequest);
TypeConverter tc = message.getExchange().getContext().getTypeConverter();
// if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
// duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
Map<String, Object> skipRequestHeaders = null;
if (configuration.isBridgeEndpoint()) {
String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
if (queryString != null) {
skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
}
// Need to remove the Host key as it should be not used
message.getHeaders().remove("host");
}
// must use entrySet to ensure case of keys is preserved
for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
continue;
}
// use an iterator as there can be multiple values. (must not use a delimiter)
final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
while (it.hasNext()) {
String headerValue = tc.convertTo(String.class, it.next());
if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
LOG.trace("HTTP-Header: {}={}", key, headerValue);
request.headers().add(key, headerValue);
}
}
}
Object body = message.getBody();
if (body != null) {
// support bodies as native Netty
ChannelBuffer buffer;
if (body instanceof ChannelBuffer) {
buffer = (ChannelBuffer) body;
} else {
// try to convert to buffer first
buffer = message.getBody(ChannelBuffer.class);
if (buffer == null) {
// fallback to byte array as last resort
byte[] data = message.getMandatoryBody(byte[].class);
buffer = ChannelBuffers.copiedBuffer(data);
}
}
if (buffer != null) {
request.setContent(buffer);
int len = buffer.readableBytes();
// set content-length
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
LOG.trace("Content-Length: {}", len);
} else {
// we do not support this kind of body
throw new NoTypeConversionAvailableException(body, ChannelBuffer.class);
}
}
// update HTTP method accordingly as we know if we have a body or not
HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
request.setMethod(method);
// set the content type in the response.
String contentType = MessageHelper.getContentType(message);
if (contentType != null) {
// set content-type
request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
LOG.trace("Content-Type: {}", contentType);
}
// must include HOST header as required by HTTP 1.1
// use URI as its faster than URL (no DNS lookup)
URI u = new URI(uri);
String hostHeader = u.getHost() + (u.getPort() == 80 ? "" : ":" + u.getPort());
request.headers().set(HttpHeaders.Names.HOST, hostHeader);
LOG.trace("Host: {}", hostHeader);
// configure connection to accordingly to keep alive configuration
// favor using the header from the message
String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
if (connection == null) {
// fallback and use the keep alive from the configuration
if (configuration.isKeepAlive()) {
connection = HttpHeaders.Values.KEEP_ALIVE;
} else {
connection = HttpHeaders.Values.CLOSE;
}
}
request.headers().set(HttpHeaders.Names.CONNECTION, connection);
LOG.trace("Connection: {}", connection);
return request;
}
use of org.apache.camel.TypeConverter in project camel by apache.
the class DefaultSparkBinding method toSparkResponse.
@Override
public void toSparkResponse(Message message, Response response, SparkConfiguration configuration) throws Exception {
LOG.trace("toSparkResponse: {}", message);
// the response code is 200 for OK and 500 for failed
boolean failed = message.getExchange().isFailed();
int defaultCode = failed ? 500 : 200;
int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
response.status(code);
LOG.trace("HTTP Status Code: {}", code);
TypeConverter tc = message.getExchange().getContext().getTypeConverter();
// must use entrySet to ensure case of keys is preserved
for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (Exchange.CONTENT_TYPE.equalsIgnoreCase(key)) {
// we set content-type later
continue;
}
// use an iterator as there can be multiple values. (must not use a delimiter)
final Iterator<?> it = ObjectHelper.createIterator(value, null);
while (it.hasNext()) {
String headerValue = tc.convertTo(String.class, it.next());
if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
LOG.trace("HTTP-Header: {}={}", key, headerValue);
response.header(key, headerValue);
}
}
}
// set the content type in the response.
String contentType = MessageHelper.getContentType(message);
if (contentType != null) {
// set content-type
response.header(Exchange.CONTENT_TYPE, contentType);
LOG.trace("Content-Type: {}", contentType);
}
Object body = message.getBody();
Exception cause = message.getExchange().getException();
// if there was an exception then use that as body
if (cause != null) {
if (configuration.isTransferException()) {
// we failed due an exception, and transfer it as java serialized object
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(cause);
oos.flush();
IOHelper.close(oos, bos);
body = bos.toByteArray();
// force content type to be serialized java object
message.setHeader(Exchange.CONTENT_TYPE, SparkConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
} else {
// we failed due an exception so print it as plain text
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cause.printStackTrace(pw);
// the body should then be the stacktrace
body = sw.toString().getBytes();
// force content type to be text/plain as that is what the stacktrace is
message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
}
// and mark the exception as failure handled, as we handled it by returning it as the response
ExchangeHelper.setFailureHandled(message.getExchange());
}
if (body != null) {
String str = tc.mandatoryConvertTo(String.class, message.getExchange(), body);
response.body(str);
// and must set body to the response body as Spark otherwise may output something else
message.setBody(str);
}
}
use of org.apache.camel.TypeConverter in project camel by apache.
the class IgniteComputeProducer method doRun.
private void doRun(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception {
Object job = exchange.getIn().getBody();
if (Collection.class.isAssignableFrom(job.getClass())) {
Collection<?> col = (Collection<?>) job;
TypeConverter tc = exchange.getContext().getTypeConverter();
Collection<IgniteRunnable> runnables = new ArrayList<>(col.size());
for (Object o : col) {
runnables.add(tc.mandatoryConvertTo(IgniteRunnable.class, o));
}
compute.run(runnables);
} else if (IgniteRunnable.class.isAssignableFrom(job.getClass())) {
compute.run((IgniteRunnable) job);
} else {
throw new RuntimeCamelException(String.format("Ignite Compute endpoint with RUN executionType is only " + "supported for IgniteRunnable payloads, or collections of them. The payload type was: %s.", job.getClass().getName()));
}
}
use of org.apache.camel.TypeConverter in project camel by apache.
the class JcloudsPayloadConverter method convertTo.
@FallbackConverter
@SuppressWarnings("unchecked")
public static <T extends Payload> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) throws IOException {
Class<?> sourceType = value.getClass();
if (GenericFile.class.isAssignableFrom(sourceType)) {
GenericFile<?> genericFile = (GenericFile<?>) value;
if (genericFile.getFile() != null) {
Class<?> genericFileType = genericFile.getFile().getClass();
TypeConverter converter = registry.lookup(Payload.class, genericFileType);
if (converter != null) {
return (T) converter.convertTo(Payload.class, genericFile.getFile());
}
}
}
return null;
}
use of org.apache.camel.TypeConverter in project camel by apache.
the class CamelJaxbFallbackConverterTest method testFilteringConverter.
@Test
public void testFilteringConverter() throws Exception {
byte[] buffers = "<Person><firstName>FOO</firstName><lastName>BAR</lastName></Person>".getBytes("UTF-8");
InputStream is = new ByteArrayInputStream(buffers);
Exchange exchange = new DefaultExchange(context);
exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");
exchange.setProperty(Exchange.FILTER_NON_XML_CHARS, true);
TypeConverter converter = context.getTypeConverter();
PersonType person = converter.convertTo(PersonType.class, exchange, is);
assertNotNull("Person should not be null ", person);
assertEquals("Get the wrong first name ", "FOO", person.getFirstName());
assertEquals("Get the wrong second name ", "BAR ", person.getLastName());
person.setLastName("BAR�");
String value = converter.convertTo(String.class, exchange, person);
assertTrue("Didn't filter the non-xml chars", value.indexOf("<lastName>BAR </lastName>") > 0);
exchange.setProperty(Exchange.FILTER_NON_XML_CHARS, false);
value = converter.convertTo(String.class, exchange, person);
assertTrue("Should not filter the non-xml chars", value.indexOf("<lastName>BAR�</lastName>") > 0);
}
Aggregations