use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class JmsSender method sendMessage.
public Message sendMessage(Message message, PipeLineSession session, String soapHeader) throws SenderException, TimeoutException {
Session s = null;
MessageProducer mp = null;
String correlationID = session == null ? null : session.getMessageId();
ParameterValueList pvl = null;
if (paramList != null) {
try {
pvl = paramList.getValues(message, session);
} catch (ParameterException e) {
throw new SenderException(getLogPrefix() + "cannot extract parameters", e);
}
}
try {
if (isSoap()) {
if (soapHeader == null) {
if (pvl != null && StringUtils.isNotEmpty(getSoapHeaderParam())) {
ParameterValue soapHeaderParamValue = pvl.getParameterValue(getSoapHeaderParam());
if (soapHeaderParamValue == null) {
log.warn("no SoapHeader found using parameter [" + getSoapHeaderParam() + "]");
} else {
soapHeader = soapHeaderParamValue.asStringValue("");
}
}
}
message = soapWrapper.putInEnvelope(message, getEncodingStyleURI(), getServiceNamespaceURI(), soapHeader);
if (log.isDebugEnabled())
log.debug(getLogPrefix() + "correlationId [" + correlationID + "] soap message [" + message + "]");
}
s = createSession();
mp = getMessageProducer(s, getDestination(session, pvl));
Destination replyQueue = null;
// create message
javax.jms.Message msg = createMessage(s, correlationID, message);
if (getMessageType() != null) {
msg.setJMSType(getMessageType());
}
if (getDeliveryMode() != DeliveryMode.NOT_SET) {
msg.setJMSDeliveryMode(getDeliveryMode().getDeliveryMode());
mp.setDeliveryMode(getDeliveryMode().getDeliveryMode());
}
if (getPriority() >= 0) {
msg.setJMSPriority(getPriority());
mp.setPriority(getPriority());
}
// set properties
if (pvl != null) {
setProperties(msg, pvl);
}
if (getReplyToName() != null) {
replyQueue = getDestination(getReplyToName());
} else {
if (isSynchronous()) {
replyQueue = getMessagingSource().getDynamicReplyQueue(s);
}
}
if (replyQueue != null) {
msg.setJMSReplyTo(replyQueue);
if (log.isDebugEnabled())
log.debug("replyTo set to queue [" + replyQueue.toString() + "]");
}
// send message
send(mp, msg);
if (log.isDebugEnabled()) {
log.debug("[" + getName() + "] " + "sent message [" + message + "] " + "to [" + mp.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "using deliveryMode [" + getDeliveryMode() + "] " + ((getReplyToName() != null) ? "replyTo [" + getReplyToName() + "]" : ""));
} else {
if (log.isInfoEnabled()) {
log.info("[" + getName() + "] " + "sent message to [" + mp.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "using deliveryMode [" + getDeliveryMode() + "] " + ((getReplyToName() != null) ? "replyTo [" + getReplyToName() + "]" : ""));
}
}
if (isSynchronous()) {
String replyCorrelationId = null;
if (getReplyToName() != null) {
switch(getLinkMethod()) {
case MESSAGEID:
replyCorrelationId = msg.getJMSMessageID();
break;
case CORRELATIONID:
replyCorrelationId = correlationID;
break;
case CORRELATIONID_FROM_MESSAGE:
replyCorrelationId = msg.getJMSCorrelationID();
break;
default:
throw new IllegalStateException("unknown linkMethod [" + getLinkMethod() + "]");
}
}
if (log.isDebugEnabled())
log.debug("[" + getName() + "] start waiting for reply on [" + replyQueue + "] requestMsgId [" + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId + "] for [" + getReplyTimeout() + "] ms");
MessageConsumer mc = getMessageConsumerForCorrelationId(s, replyQueue, replyCorrelationId);
try {
javax.jms.Message rawReplyMsg = mc.receive(getReplyTimeout());
if (rawReplyMsg == null) {
throw new TimeoutException("did not receive reply on [" + replyQueue + "] requestMsgId [" + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId + "] within [" + getReplyTimeout() + "] ms");
}
if (getResponseHeadersList().size() > 0) {
Enumeration<?> propertyNames = rawReplyMsg.getPropertyNames();
while (propertyNames.hasMoreElements()) {
String jmsProperty = (String) propertyNames.nextElement();
if (getResponseHeadersList().contains(jmsProperty)) {
session.put(jmsProperty, rawReplyMsg.getObjectProperty(jmsProperty));
}
}
}
return extractMessage(rawReplyMsg, session, isSoap(), getReplySoapHeaderSessionKey(), soapWrapper);
} finally {
if (mc != null) {
try {
mc.close();
} catch (JMSException e) {
log.warn("JmsSender [" + getName() + "] got exception closing message consumer for reply", e);
}
}
}
}
return new Message(msg.getJMSMessageID());
} catch (JMSException e) {
throw new SenderException(e);
} catch (IOException e) {
throw new SenderException(e);
} catch (NamingException e) {
throw new SenderException(e);
} catch (SAXException e) {
throw new SenderException(e);
} catch (TransformerException e) {
throw new SenderException(e);
} catch (JmsException e) {
throw new SenderException(e);
} finally {
if (mp != null) {
try {
mp.close();
} catch (JMSException e) {
log.warn("JmsSender [" + getName() + "] got exception closing message producer", e);
}
}
closeSession(s);
}
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class JdbcQuerySenderBase method executePackageQuery.
protected Message executePackageQuery(QueryExecutionContext queryExecutionContext) throws SenderException, JdbcException, IOException, JMSException {
Connection connection = queryExecutionContext.getConnection();
String query = queryExecutionContext.getQuery();
Object[] paramArray = new Object[10];
String callMessage = fillParamArray(paramArray, query);
try (CallableStatement pstmt = connection.prepareCall(callMessage)) {
if (getMaxRows() > 0) {
pstmt.setMaxRows(getMaxRows() + (getStartRow() > 1 ? getStartRow() - 1 : 0));
}
int var = 1;
for (int i = 0; i < paramArray.length; i++) {
if (paramArray[i] instanceof Timestamp) {
pstmt.setTimestamp(var, (Timestamp) paramArray[i]);
var++;
}
if (paramArray[i] instanceof java.sql.Date) {
pstmt.setDate(var, (java.sql.Date) paramArray[i]);
var++;
}
if (paramArray[i] instanceof String) {
pstmt.setString(var, (String) paramArray[i]);
var++;
}
if (paramArray[i] instanceof Integer) {
int x = Integer.parseInt(paramArray[i].toString());
pstmt.setInt(var, x);
var++;
}
if (paramArray[i] instanceof Float) {
float x = Float.parseFloat(paramArray[i].toString());
pstmt.setFloat(var, x);
var++;
}
}
if (query.indexOf('?') != -1) {
// make sure enough space is available for result...
pstmt.registerOutParameter(var, Types.CLOB);
}
if ("xml".equalsIgnoreCase(getPackageContent())) {
log.debug(getLogPrefix() + "executing a package SQL command");
pstmt.executeUpdate();
String pUitvoer = pstmt.getString(var);
return new Message(pUitvoer);
}
log.debug(getLogPrefix() + "executing a package SQL command");
int numRowsAffected = pstmt.executeUpdate();
if (convertedResultQuery != null) {
PreparedStatement resStmt = queryExecutionContext.getResultQueryStatement();
if (log.isDebugEnabled())
log.debug("obtaining result from [" + convertedResultQuery + "]");
ResultSet rs = resStmt.executeQuery();
return getResult(rs);
}
if (getColumnsReturnedList() != null) {
return getResult(getReturnedColumns(getColumnsReturnedList(), queryExecutionContext.getStatement()));
}
if (isScalar()) {
return new Message(Integer.toString(numRowsAffected));
}
return new Message("<result><rowsupdated>" + numRowsAffected + "</rowsupdated></result>");
} catch (SQLException sqle) {
throw new SenderException(getLogPrefix() + "got exception executing a package SQL command", sqle);
}
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class MessageSendingPipe method doPipe.
@Override
public PipeRunResult doPipe(Message input, PipeLineSession session) throws PipeRunException {
String correlationID = session == null ? null : session.getMessageId();
Message originalMessage = null;
Message result = null;
PipeForward forward = getSuccessForward();
if (messageLog != null) {
preserve(input, session);
originalMessage = input;
}
if (getInputWrapper() != null) {
log.debug(getLogPrefix(session) + "wrapping input");
PipeRunResult wrapResult = pipeProcessor.processPipe(getPipeLine(), inputWrapper, input, session);
if (wrapResult == null) {
throw new PipeRunException(inputWrapper, "retrieved null result from inputWrapper");
}
if (!wrapResult.isSuccessful()) {
return wrapResult;
}
input = wrapResult.getResult();
if (messageLog != null) {
preserve(input, session);
}
log.debug(getLogPrefix(session) + "input after wrapping (" + ClassUtils.nameOf(input) + ") [" + input.toString() + "]");
}
if (getInputValidator() != null) {
preserve(input, session);
log.debug(getLogPrefix(session) + "validating input");
PipeRunResult validationResult = pipeProcessor.processPipe(getPipeLine(), inputValidator, input, session);
if (validationResult != null && !validationResult.isSuccessful()) {
return validationResult;
}
input = validationResult.getResult();
}
if (StringUtils.isNotEmpty(getStubFilename())) {
ParameterList pl = getParameterList();
result = new Message(returnString);
if (pl != null) {
Map<String, Object> params;
try {
params = pl.getValues(input, session).getValueMap();
} catch (ParameterException e1) {
throw new PipeRunException(this, getLogPrefix(session) + "got exception evaluating parameters", e1);
}
String sfn = null;
if (params != null && params.size() > 0) {
sfn = (String) params.get(STUBFILENAME);
}
if (sfn != null) {
try {
result = new Message(Misc.resourceToString(ClassUtils.getResourceURL(this, sfn), Misc.LINE_SEPARATOR));
log.info(getLogPrefix(session) + "returning result from dynamic stub [" + sfn + "]");
} catch (Throwable e) {
throw new PipeRunException(this, getLogPrefix(session) + "got exception loading result from stub [" + sfn + "]", e);
}
} else {
log.info(getLogPrefix(session) + "returning result from static stub [" + getStubFilename() + "]");
}
} else {
log.info(getLogPrefix(session) + "returning result from static stub [" + getStubFilename() + "]");
}
} else {
Map<String, Object> threadContext = new LinkedHashMap<String, Object>();
try {
String messageID = null;
// sendResult has a messageID for async senders, the result for sync senders
int retryInterval = getRetryMinInterval();
PipeRunResult sendResult = null;
boolean replyIsValid = false;
int retriesLeft = 0;
if (getMaxRetries() > 0) {
retriesLeft = getMaxRetries() + 1;
} else {
retriesLeft = 1;
}
while (retriesLeft-- >= 1 && !replyIsValid) {
try {
sendResult = sendMessage(input, session, getSender(), threadContext);
if (retryTp != null) {
String retry = retryTp.transform(sendResult.getResult().asString(), null);
if (retry.equalsIgnoreCase("true")) {
if (retriesLeft >= 1) {
retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "xpathRetry result [" + retry + "], retries left [" + retriesLeft + "]");
}
} else {
replyIsValid = true;
}
} else {
replyIsValid = true;
}
} catch (TimeoutException toe) {
if (retriesLeft >= 1) {
retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "timeout occured, retries left [" + retriesLeft + "]");
} else {
throw toe;
}
} catch (SenderException se) {
if (retriesLeft >= 1) {
retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "exception [" + se.getMessage() + "] occured, retries left [" + retriesLeft + "]");
} else {
throw se;
}
}
}
if (!replyIsValid) {
throw new PipeRunException(this, getLogPrefix(session) + "invalid reply message is received");
}
if (sendResult == null) {
throw new PipeRunException(this, getLogPrefix(session) + "retrieved null result from sender");
}
if (sendResult.getPipeForward() != null) {
forward = sendResult.getPipeForward();
}
if (getSender().isSynchronous()) {
if (log.isInfoEnabled()) {
log.info(getLogPrefix(session) + "sent message to [" + getSender().getName() + "] synchronously");
}
result = sendResult.getResult();
} else {
messageID = sendResult.getResult().asString();
if (log.isInfoEnabled()) {
log.info(getLogPrefix(session) + "sent message to [" + getSender().getName() + "] messageID [" + messageID + "] linkMethod [" + getLinkMethod() + "]");
}
// as this will be used with the listener
if (getLinkMethod() == LinkMethod.MESSAGEID) {
correlationID = sendResult.getResult().asString();
if (log.isDebugEnabled())
log.debug(getLogPrefix(session) + "setting correlationId to listen for to messageId [" + correlationID + "]");
}
}
ITransactionalStorage messageLog = getMessageLog();
if (messageLog != null) {
long messageLogStartTime = System.currentTimeMillis();
String messageTrail = "no audit trail";
if (auditTrailTp != null) {
if (isUseInputForExtract()) {
messageTrail = auditTrailTp.transform(originalMessage, null);
} else {
messageTrail = auditTrailTp.transform(input, null);
}
} else {
if (StringUtils.isNotEmpty(getAuditTrailSessionKey())) {
messageTrail = session.getMessage(getAuditTrailSessionKey()).asString();
}
}
String storedMessageID = messageID;
if (storedMessageID == null) {
storedMessageID = "-";
}
if (correlationIDTp != null) {
if (StringUtils.isNotEmpty(getCorrelationIDSessionKey())) {
String sourceString = session.getMessage(getCorrelationIDSessionKey()).asString();
correlationID = correlationIDTp.transform(sourceString, null);
} else {
if (isUseInputForExtract()) {
correlationID = correlationIDTp.transform(originalMessage, null);
} else {
correlationID = correlationIDTp.transform(input, null);
}
}
if (StringUtils.isEmpty(correlationID)) {
correlationID = "-";
}
}
String label = null;
if (labelTp != null) {
if (isUseInputForExtract()) {
label = labelTp.transform(originalMessage, null);
} else {
label = labelTp.transform(input, null);
}
}
messageLog.storeMessage(storedMessageID, correlationID, new Date(), messageTrail, label, input);
long messageLogEndTime = System.currentTimeMillis();
long messageLogDuration = messageLogEndTime - messageLogStartTime;
StatisticsKeeper sk = getPipeLine().getPipeStatistics(messageLog);
sk.addValue(messageLogDuration);
}
if (getListener() != null) {
result = Message.asMessage(listenerProcessor.getMessage(getListener(), correlationID, session));
} else {
// is this correct? result was already set at line 634!
result = sendResult.getResult();
}
if (result == null || result.asObject() == null) {
result = new Message("");
}
if (timeoutPending) {
timeoutPending = false;
throwEvent(PIPE_CLEAR_TIMEOUT_MONITOR_EVENT);
}
} catch (TimeoutException toe) {
throwEvent(PIPE_TIMEOUT_MONITOR_EVENT);
if (!timeoutPending) {
timeoutPending = true;
}
PipeForward timeoutForward = findForward(TIMEOUT_FORWARD);
log.warn(getLogPrefix(session) + "timeout occured");
if (timeoutForward == null) {
if (StringUtils.isEmpty(getResultOnTimeOut())) {
timeoutForward = findForward(PipeForward.EXCEPTION_FORWARD_NAME);
} else {
timeoutForward = getSuccessForward();
}
}
if (timeoutForward != null) {
Message resultmsg;
if (StringUtils.isNotEmpty(getResultOnTimeOut())) {
resultmsg = new Message(getResultOnTimeOut());
} else {
resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), toe, this, input, session.getMessageId(), 0);
}
return new PipeRunResult(timeoutForward, resultmsg);
}
throw new PipeRunException(this, getLogPrefix(session) + "caught timeout-exception", toe);
} catch (Throwable t) {
throwEvent(PIPE_EXCEPTION_MONITOR_EVENT);
PipeForward exceptionForward = findForward(PipeForward.EXCEPTION_FORWARD_NAME);
if (exceptionForward != null) {
log.warn(getLogPrefix(session) + "exception occured, forwarding to exception-forward [" + exceptionForward.getPath() + "], exception:\n", t);
return new PipeRunResult(exceptionForward, new ErrorMessageFormatter().format(getLogPrefix(session), t, this, input, session.getMessageId(), 0));
}
throw new PipeRunException(this, getLogPrefix(session) + "caught exception", t);
}
}
try {
if (!validResult(result)) {
PipeForward illegalResultForward = findForward(ILLEGAL_RESULT_FORWARD);
return new PipeRunResult(illegalResultForward, result);
}
} catch (IOException e) {
throw new PipeRunException(this, getLogPrefix(session) + "caught exception", e);
}
IPipe outputValidator = getOutputValidator();
if (outputValidator != null) {
log.debug(getLogPrefix(session) + "validating response");
PipeRunResult validationResult;
validationResult = pipeProcessor.processPipe(getPipeLine(), outputValidator, Message.asMessage(result), session);
if (validationResult != null) {
if (!validationResult.isSuccessful()) {
return validationResult;
}
result = validationResult.getResult();
}
}
if (getOutputWrapper() != null) {
log.debug(getLogPrefix(session) + "wrapping response");
PipeRunResult wrapResult = pipeProcessor.processPipe(getPipeLine(), outputWrapper, Message.asMessage(result), session);
if (wrapResult == null) {
throw new PipeRunException(outputWrapper, "retrieved null result from outputWrapper");
}
if (!wrapResult.isSuccessful()) {
return wrapResult;
}
result = wrapResult.getResult();
log.debug(getLogPrefix(session) + "response after wrapping (" + ClassUtils.nameOf(result) + ") [" + result + "]");
}
if (isStreamResultToServlet()) {
Message mia = Message.asMessage(result);
try {
InputStream resultStream = new Base64InputStream(mia.asInputStream(), false);
String contentType = session.getMessage("contentType").asString();
if (StringUtils.isNotEmpty(contentType)) {
RestListenerUtils.setResponseContentType(session, contentType);
}
RestListenerUtils.writeToResponseOutputStream(session, resultStream);
} catch (IOException e) {
throw new PipeRunException(this, getLogPrefix(session) + "caught exception", e);
}
return new PipeRunResult(forward, "");
}
return new PipeRunResult(forward, result);
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class MessageSendingPipe method sendMessage.
protected PipeRunResult sendMessage(Message input, PipeLineSession session, ISender sender, Map<String, Object> threadContext) throws SenderException, TimeoutException, IOException, InterruptedException {
long startTime = System.currentTimeMillis();
PipeRunResult sendResult = null;
String exitState = null;
try {
PipeLine pipeline = getPipeLine();
if (pipeline != null) {
Adapter adapter = pipeline.getAdapter();
if (adapter != null) {
if (getPresumedTimeOutInterval() >= 0 && !isConfigurationStubbed) {
long lastExitIsTimeoutDate = adapter.getLastExitIsTimeoutDate(getName());
if (lastExitIsTimeoutDate > 0) {
long duration = startTime - lastExitIsTimeoutDate;
if (duration < (1000L * getPresumedTimeOutInterval())) {
exitState = PRESUMED_TIMEOUT_FORWARD;
throw new TimeoutException(getLogPrefix(session) + exitState);
}
}
}
}
}
try {
if (sender instanceof IStreamingSender && canStreamToNextPipe() && getOutputValidator() == null && getOutputWrapper() == null && !isStreamResultToServlet()) {
sendResult = ((IStreamingSender) sender).sendMessage(input, session, getNextPipe());
} else {
// sendResult has a messageID for async senders, the result for sync senders
Message result = sender.sendMessage(input, session);
sendResult = new PipeRunResult(null, result);
}
} catch (SenderException se) {
exitState = PipeForward.EXCEPTION_FORWARD_NAME;
throw se;
} catch (TimeoutException toe) {
exitState = TIMEOUT_FORWARD;
throw toe;
}
if (Thread.currentThread().isInterrupted()) {
exitState = INTERRUPT_FORWARD;
throw new InterruptedException();
}
Message sendResultMessage = sendResult.getResult();
if (sendResultMessage.asObject() instanceof String) {
String result = (String) sendResultMessage.asObject();
if (StringUtils.isNotEmpty(getTimeOutOnResult()) && getTimeOutOnResult().equals(result)) {
exitState = TIMEOUT_FORWARD;
throw new TimeoutException(getLogPrefix(session) + "timeOutOnResult [" + getTimeOutOnResult() + "]");
}
if (StringUtils.isNotEmpty(getExceptionOnResult()) && getExceptionOnResult().equals(result)) {
exitState = PipeForward.EXCEPTION_FORWARD_NAME;
throw new SenderException(getLogPrefix(session) + "exceptionOnResult [" + getExceptionOnResult() + "]");
}
}
} finally {
if (exitState == null) {
exitState = PipeForward.SUCCESS_FORWARD_NAME;
}
PipeLine pipeline = getPipeLine();
if (pipeline != null) {
Adapter adapter = pipeline.getAdapter();
if (adapter != null) {
if (getPresumedTimeOutInterval() >= 0 && !ConfigurationUtils.isConfigurationStubbed(getConfigurationClassLoader())) {
if (!PRESUMED_TIMEOUT_FORWARD.equals(exitState)) {
adapter.setLastExitState(getName(), System.currentTimeMillis(), exitState);
}
}
String duration;
if (msgLogHumanReadable) {
duration = Misc.getAge(startTime);
} else {
duration = Misc.getDurationInMs(startTime);
}
if (msgLog.getLevel().isMoreSpecificThan(MSGLOG_LEVEL_TERSE)) {
msgLog.log(MSGLOG_LEVEL_TERSE, String.format("Sender [%s] class [%s] duration [%s] got exit-state [%s]", sender.getName(), ClassUtils.nameOf(sender), duration, exitState));
}
}
}
}
return sendResult;
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class Base64Pipe method doPipe.
@Override
public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException {
// TRUE encode - FALSE decode
boolean directionEncode = getDirection() == Direction.ENCODE;
InputStream binaryInputStream;
try {
binaryInputStream = message.asInputStream(directionEncode ? getCharset() : null);
} catch (IOException e) {
throw new PipeRunException(this, "cannot open stream", e);
}
InputStream base64 = new Base64InputStream(binaryInputStream, directionEncode, getLineLength(), lineSeparatorArray);
Message result = new Message(base64, message.copyContext().withoutSize().withCharset(directionEncode ? StandardCharsets.US_ASCII.name() : getCharset()));
if (getOutputTypeEnum() == OutputTypes.STRING) {
try {
result = new Message(result.asReader());
} catch (IOException e) {
throw new PipeRunException(this, "cannot open stream", e);
}
}
return new PipeRunResult(getSuccessForward(), result);
}
Aggregations