本文整理汇总了Java中org.apache.camel.Message.getMandatoryBody方法的典型用法代码示例。如果您正苦于以下问题:Java Message.getMandatoryBody方法的具体用法?Java Message.getMandatoryBody怎么用?Java Message.getMandatoryBody使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.camel.Message
的用法示例。
在下文中一共展示了Message.getMandatoryBody方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: process
import org.apache.camel.Message; //导入方法依赖的package包/类
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
Object message = in.getMandatoryBody();
if (!(message == null || message instanceof String || message instanceof byte[])) {
message = in.getMandatoryBody(String.class);
}
if (isSendToAllSet(in)) {
sendToAll(store, message, exchange);
} else {
// look for connection key and get Websocket
String connectionKey = in.getHeader(WebsocketConstants.CONNECTION_KEY, String.class);
if (connectionKey != null) {
DefaultWebsocket websocket = store.get(connectionKey);
log.debug("Sending to connection key {} -> {}", connectionKey, message);
sendMessage(websocket, message);
} else {
throw new IllegalArgumentException("Failed to send message to single connection; connetion key not set.");
}
}
}
示例2: createUser
import org.apache.camel.Message; //导入方法依赖的package包/类
/**
* Get result from AlmaUserService.createUser() and store in exchange.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void createUser(final Exchange exchange) throws Exception {
final Message in = exchange.getIn();
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
User user = in.getMandatoryBody(User.class);
try {
log.debug("Creating user with id {} in ALMA", user.getPrimaryId());
in.setBody(userService.createUser(user));
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Ok);
} catch (BadRequestException e) {
if (e.getResponse().getStatus() != 400) {
log.error("Failed to create user", e);
} else {
WebServiceResult res = e.getResponse().readEntity(WebServiceResult.class);
String code = res.getErrorList().getError().get(0).getErrorCode();
String message = res.getErrorList().getError().get(0).getErrorMessage();
log.error("Code: " + code + ", message: " + message, e);
e.getResponse().close();
}
throw e;
}
}
示例3: getMessageBodyNode
import org.apache.camel.Message; //导入方法依赖的package包/类
protected Node getMessageBodyNode(Message message) throws Exception { //NOPMD
InputStream is = message.getMandatoryBody(InputStream.class);
Boolean isPlainText = isPlainText(message);
Node node;
if (isPlainText != null && isPlainText) {
node = getTextNode(message, is);
} else {
ValidatorErrorHandler errorHandler = new DefaultValidationErrorHandler();
Schema schema = getSchemaForSigner(message, errorHandler);
Document doc = parseInput(is, getConfiguration().getDisallowDoctypeDecl(), schema, errorHandler);
errorHandler.handleErrors(message.getExchange(), schema, null); // throws ValidationException
node = doc.getDocumentElement();
LOG.debug("Root element of document to be signed: {}", node);
}
return node;
}
示例4: doWriteGZIPResponse
import org.apache.camel.Message; //导入方法依赖的package包/类
protected void doWriteGZIPResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
byte[] bytes;
try {
bytes = message.getMandatoryBody(byte[].class);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
byte[] data = GZIPHelper.compressGZIP(bytes);
ServletOutputStream os = response.getOutputStream();
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response as GZIP in non-chunked mode with content-length {} and buffer size: {}", data.length, response.getBufferSize());
}
response.setContentLength(data.length);
os.write(data);
os.flush();
} finally {
IOHelper.close(os);
}
}
示例5: process
import org.apache.camel.Message; //导入方法依赖的package包/类
@Override
public void process(Exchange exchange) throws Exception {
Message message = null;
if (exchange.hasOut()) {
message = exchange.getOut();
} else {
message = exchange.getIn();
}
byte[] hl7Bytes = message.getMandatoryBody(byte[].class);
byte[] acknowledgementBytes = null;
if (null == exchange.getException()) {
acknowledgementBytes = generateApplicationAcceptAcknowledgementMessage(hl7Bytes);
message.setHeader(MLLP_ACKNOWLEDGEMENT_TYPE, "AA");
} else {
acknowledgementBytes = generateApplicationErrorAcknowledgementMessage(hl7Bytes);
message.setHeader(MLLP_ACKNOWLEDGEMENT_TYPE, "AE");
}
message.setHeader(MLLP_ACKNOWLEDGEMENT, acknowledgementBytes);
}
示例6: evaluate
import org.apache.camel.Message; //导入方法依赖的package包/类
public Object evaluate(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
Object body = msg.getBody();
if (factory == null) {
factory = createStreamFactory(exchange.getContext());
}
BeanReader beanReader = null;
if (body instanceof WrappedFile) {
body = ((WrappedFile) body).getFile();
}
if (body instanceof File) {
File file = (File) body;
beanReader = factory.createReader(getStreamName(), file);
}
if (beanReader == null) {
Reader reader = msg.getMandatoryBody(Reader.class);
beanReader = factory.createReader(getStreamName(), reader);
}
beanReader.setErrorHandler(new BeanIOErrorHandler(configuration));
return new BeanIOIterator(beanReader);
}
示例7: process
import org.apache.camel.Message; //导入方法依赖的package包/类
@Override
public void process(Exchange exchange) throws Exception {
final Message in = exchange.getIn();
String command = in.getMandatoryBody(String.class);
try {
SshResult result = SshHelper.sendExecCommand(command, endpoint, client);
exchange.getOut().setBody(result.getStdout());
exchange.getOut().setHeader(SshResult.EXIT_VALUE, result.getExitValue());
exchange.getOut().setHeader(SshResult.STDERR, result.getStderr());
} catch (Exception e) {
throw new CamelExchangeException("Cannot execute command: " + command, exchange, e);
}
// propagate headers and attachments
exchange.getOut().getHeaders().putAll(in.getHeaders());
exchange.getOut().setAttachments(in.getAttachments());
}
示例8: testGetMandatoryBody
import org.apache.camel.Message; //导入方法依赖的package包/类
public void testGetMandatoryBody() throws Exception {
Exchange exchange = new DefaultExchange(context);
Message in = exchange.getIn();
try {
in.getMandatoryBody();
fail("Should have thrown an exception");
} catch (InvalidPayloadException e) {
// expected
}
in.setBody("Hello World");
assertEquals("Hello World", in.getMandatoryBody());
}
示例9: process
import org.apache.camel.Message; //导入方法依赖的package包/类
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
boolean out = exchange.hasOut();
Message old = out ? exchange.getOut() : exchange.getIn();
if (old.getBody() == null) {
// only convert if the is a body
callback.done(true);
return true;
}
if (charset != null) {
// override existing charset with configured charset as that is what the user
// have explicit configured and expects to be used
exchange.setProperty(Exchange.CHARSET_NAME, charset);
}
// use mandatory conversion
Object value;
try {
value = old.getMandatoryBody(type);
} catch (Throwable e) {
exchange.setException(e);
callback.done(true);
return true;
}
// create a new message container so we do not drag specialized message objects along
// but that is only needed if the old message is a specialized message
boolean copyNeeded = !(old.getClass().equals(DefaultMessage.class));
if (copyNeeded) {
Message msg = new DefaultMessage();
msg.copyFrom(old);
msg.setBody(value);
// replace message on exchange
ExchangeHelper.replaceMessage(exchange, msg, false);
} else {
// no copy needed so set replace value directly
old.setBody(value);
}
// remove charset when we are done as we should not propagate that,
// as that can lead to double converting later on
if (charset != null) {
exchange.removeProperty(Exchange.CHARSET_NAME);
}
callback.done(true);
return true;
}
示例10: doWriteDirectResponse
import org.apache.camel.Message; //导入方法依赖的package包/类
protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
// if content type is serialized Java object, then serialize and write it to the response
String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (allowJavaSerializedObject || isTransferException()) {
try {
Object object = message.getMandatoryBody(Serializable.class);
HttpHelper.writeObjectToServletResponse(response, object);
// object is written so return
return;
} catch (InvalidPayloadException e) {
throw new IOException(e);
}
} else {
throw new RuntimeCamelException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
}
}
// prefer streaming
InputStream is = null;
if (checkChunked(message, exchange)) {
is = message.getBody(InputStream.class);
} else {
// try to use input stream first, so we can copy directly
if (!isText(contentType)) {
is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody());
}
}
if (is != null) {
ServletOutputStream os = response.getOutputStream();
if (!checkChunked(message, exchange)) {
CachedOutputStream stream = new CachedOutputStream(exchange);
try {
// copy directly from input stream to the cached output stream to get the content length
int len = copyStream(is, stream, response.getBufferSize());
// we need to setup the length if message is not chucked
response.setContentLength(len);
OutputStream current = stream.getCurrentStream();
if (current instanceof ByteArrayOutputStream) {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming (direct) response in non-chunked mode with content-length {}");
}
ByteArrayOutputStream bos = (ByteArrayOutputStream) current;
bos.writeTo(os);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len, len);
}
copyStream(stream.getInputStream(), os, len);
}
} finally {
IOHelper.close(is, os);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in chunked mode with buffer size {}", response.getBufferSize());
}
copyStream(is, os, response.getBufferSize());
}
} else {
// not convertable as a stream so fallback as a String
String data = message.getBody(String.class);
if (data != null) {
// set content length and encoding before we write data
String charset = IOHelper.getCharsetName(exchange, true);
final int dataByteLength = data.getBytes(charset).length;
response.setCharacterEncoding(charset);
response.setContentLength(dataByteLength);
if (LOG.isDebugEnabled()) {
LOG.debug("Writing response in non-chunked mode as plain text with content-length {} and buffer size: {}", dataByteLength, response.getBufferSize());
}
try {
response.getWriter().print(data);
} finally {
response.getWriter().flush();
}
}
}
}
示例11: testSubscribeAndReceive
import org.apache.camel.Message; //导入方法依赖的package包/类
@Test
public void testSubscribeAndReceive() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:CamelTestTopic");
mock.expectedMessageCount(1);
// assert expected static headers
mock.expectedHeaderReceived("CamelSalesforceTopicName", "CamelTestTopic");
mock.expectedHeaderReceived("CamelSalesforceChannel", "/topic/CamelTestTopic");
Merchandise__c merchandise = new Merchandise__c();
merchandise.setName("TestNotification");
merchandise.setDescription__c("Merchandise for testing Streaming API updated on " + new DateTime().toString());
merchandise.setPrice__c(9.99);
merchandise.setTotal_Inventory__c(1000.0);
CreateSObjectResult result = template().requestBody(
"direct:upsertSObject", merchandise, CreateSObjectResult.class);
assertTrue("Merchandise test record not created", result == null || result.getSuccess());
try {
// wait for Salesforce notification
mock.assertIsSatisfied();
final Message in = mock.getExchanges().get(0).getIn();
merchandise = in.getMandatoryBody(Merchandise__c.class);
assertNotNull("Missing event body", merchandise);
log.info("Merchandise notification: {}", merchandise.toString());
assertNotNull("Missing field Id", merchandise.getId());
assertNotNull("Missing field Name", merchandise.getName());
// validate dynamic message headers
assertNotNull("Missing header CamelSalesforceClientId", in.getHeader("CamelSalesforceClientId"));
assertNotNull("Missing header CamelSalesforceEventType", in.getHeader("CamelSalesforceEventType"));
assertNotNull("Missing header CamelSalesforceCreatedDate", in.getHeader("CamelSalesforceCreatedDate"));
} finally {
// remove the test record
assertNull(template().requestBody("direct:deleteSObjectWithId", merchandise));
// remove the test topic
// find it using SOQL first
QueryRecordsPushTopic records = template().requestBody("direct:query", null,
QueryRecordsPushTopic.class);
assertEquals("Test topic not found", 1, records.getTotalSize());
assertNull(template().requestBody("direct:deleteSObject",
records.getRecords().get(0)));
}
}