use of nl.nn.adapterframework.core.IPipeLineSession in project iaf by ibissource.
the class XmlValidatorSender method sendMessage.
@Override
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException {
IPipeLineSession session = prc.getSession();
String fullReasons = "tja";
try {
String resultEvent = validate(message, session, getLogPrefix(), null, null, false);
if (AbstractXmlValidator.XML_VALIDATOR_VALID_MONITOR_EVENT.equals(resultEvent)) {
return message;
}
// TODO: find real fullReasons
fullReasons = resultEvent;
if (isThrowException()) {
throw new SenderException(fullReasons);
}
log.warn(fullReasons);
return message;
} catch (Exception e) {
if (isThrowException()) {
throw new SenderException(e);
}
log.warn(fullReasons, e);
return message;
}
}
use of nl.nn.adapterframework.core.IPipeLineSession in project iaf by ibissource.
the class SendTibcoMessage method doPipeWithTimeoutGuarded.
public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException {
Connection connection = null;
Session jSession = null;
MessageProducer msgProducer = null;
Destination destination = null;
String url_work;
String authAlias_work;
String userName_work;
String password_work;
String queueName_work;
String messageProtocol_work;
int replyTimeout_work;
String soapAction_work;
String result = null;
ParameterValueList pvl = null;
if (getParameterList() != null) {
ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
try {
pvl = prc.getValues(getParameterList());
} catch (ParameterException e) {
throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e);
}
}
url_work = getParameterValue(pvl, "url");
if (url_work == null) {
url_work = getUrl();
}
authAlias_work = getParameterValue(pvl, "authAlias");
if (authAlias_work == null) {
authAlias_work = getAuthAlias();
}
userName_work = getParameterValue(pvl, "userName");
if (userName_work == null) {
userName_work = getUserName();
}
password_work = getParameterValue(pvl, "password");
if (password_work == null) {
password_work = getPassword();
}
queueName_work = getParameterValue(pvl, "queueName");
if (queueName_work == null) {
queueName_work = getQueueName();
}
messageProtocol_work = getParameterValue(pvl, "messageProtocol");
if (messageProtocol_work == null) {
messageProtocol_work = getMessageProtocol();
}
String replyTimeout_work_str = getParameterValue(pvl, "replyTimeout");
if (replyTimeout_work_str == null) {
replyTimeout_work = getReplyTimeout();
} else {
replyTimeout_work = Integer.parseInt(replyTimeout_work_str);
}
soapAction_work = getParameterValue(pvl, "soapAction");
if (soapAction_work == null)
soapAction_work = getSoapAction();
if (StringUtils.isEmpty(soapAction_work) && !StringUtils.isEmpty(queueName_work)) {
String[] q = queueName_work.split("\\.");
if (q.length > 0) {
if (q[0].equalsIgnoreCase("P2P") && q.length >= 4) {
soapAction_work = q[3];
} else if (q[0].equalsIgnoreCase("ESB") && q.length == 8) {
soapAction_work = q[5] + "_" + q[6];
} else if (q[0].equalsIgnoreCase("ESB") && q.length > 8) {
soapAction_work = q[6] + "_" + q[7];
}
}
}
if (StringUtils.isEmpty(soapAction_work)) {
log.debug(getLogPrefix(session) + "deriving default soapAction");
try {
URL resource = ClassUtils.getResourceURL(this, "/xml/xsl/esb/soapAction.xsl");
TransformerPool tp = TransformerPool.getInstance(resource, true);
soapAction_work = tp.transform(input.toString(), null);
} catch (Exception e) {
log.error(getLogPrefix(session) + "failed to execute soapAction.xsl");
}
}
if (messageProtocol_work == null) {
throw new PipeRunException(this, getLogPrefix(session) + "messageProtocol must be set");
}
if (!messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY) && !messageProtocol_work.equalsIgnoreCase(FIRE_AND_FORGET)) {
throw new PipeRunException(this, getLogPrefix(session) + "illegal value for messageProtocol [" + messageProtocol_work + "], must be '" + REQUEST_REPLY + "' or '" + FIRE_AND_FORGET + "'");
}
CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work);
try {
TibjmsAdmin admin;
try {
admin = TibcoUtils.getActiveServerAdmin(url_work, cf);
} catch (TibjmsAdminException e) {
log.debug(getLogPrefix(session) + "caught exception", e);
admin = null;
}
if (admin != null) {
QueueInfo queueInfo;
try {
queueInfo = admin.getQueue(queueName_work);
} catch (Exception e) {
throw new PipeRunException(this, getLogPrefix(session) + " exception on getting queue info", e);
}
if (queueInfo == null) {
throw new PipeRunException(this, getLogPrefix(session) + " queue [" + queueName_work + "] does not exist");
}
try {
admin.close();
} catch (TibjmsAdminException e) {
log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e);
}
}
ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work);
connection = factory.createConnection(cf.getUsername(), cf.getPassword());
jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
destination = jSession.createQueue(queueName_work);
msgProducer = jSession.createProducer(destination);
TextMessage msg = jSession.createTextMessage();
msg.setText(input.toString());
Destination replyQueue = null;
if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
replyQueue = jSession.createTemporaryQueue();
msg.setJMSReplyTo(replyQueue);
msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
msgProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
msgProducer.setTimeToLive(replyTimeout_work);
} else {
msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
msgProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
}
if (StringUtils.isNotEmpty(soapAction_work)) {
log.debug(getLogPrefix(session) + "setting [SoapAction] property to value [" + soapAction_work + "]");
msg.setStringProperty("SoapAction", soapAction_work);
}
msgProducer.send(msg);
if (log.isDebugEnabled()) {
log.debug(getLogPrefix(session) + "sent message [" + msg.getText() + "] " + "to [" + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]");
} else {
if (log.isInfoEnabled()) {
log.info(getLogPrefix(session) + "sent message to [" + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]");
}
}
if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
String replyCorrelationId = msg.getJMSMessageID();
MessageConsumer msgConsumer = jSession.createConsumer(replyQueue, "JMSCorrelationID='" + replyCorrelationId + "'");
log.debug(getLogPrefix(session) + "] start waiting for reply on [" + replyQueue + "] selector [" + replyCorrelationId + "] for [" + replyTimeout_work + "] ms");
try {
connection.start();
Message rawReplyMsg = msgConsumer.receive(replyTimeout_work);
if (rawReplyMsg == null) {
throw new PipeRunException(this, getLogPrefix(session) + "did not receive reply on [" + replyQueue + "] replyCorrelationId [" + replyCorrelationId + "] within [" + replyTimeout_work + "] ms");
}
TextMessage replyMsg = (TextMessage) rawReplyMsg;
result = replyMsg.getText();
} finally {
}
} else {
result = msg.getJMSMessageID();
}
} catch (JMSException e) {
throw new PipeRunException(this, getLogPrefix(session) + " exception on sending message to Tibco queue", e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
log.warn(getLogPrefix(session) + "exception on closing connection", e);
}
}
}
return result;
}
use of nl.nn.adapterframework.core.IPipeLineSession in project iaf by ibissource.
the class CmisHttpSender method invoke.
public Response invoke(String url, Map<String, String> headers, Output writer, BindingSession session, BigInteger offset, BigInteger length) throws SenderException, TimeOutException {
// Prepare the message. We will overwrite things later...
this.headers = headers;
int responseCode = -1;
IPipeLineSession pls = new PipeLineSessionBase();
pls.put("writer", writer);
pls.put("url", url);
ParameterResolutionContext prc = new ParameterResolutionContext("", pls);
try {
sendMessageWithTimeoutGuarded(null, null, prc);
return (Response) pls.get("response");
} catch (Exception e) {
throw new CmisConnectionException(getUrl(), responseCode, e);
}
}
use of nl.nn.adapterframework.core.IPipeLineSession in project iaf by ibissource.
the class FtpSender method sendMessage.
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
try {
IPipeLineSession session = null;
if (prc != null) {
session = prc.getSession();
}
ftpSession.put(paramList, session, message, remoteDirectory, remoteFilenamePattern, true);
} catch (SenderException e) {
throw e;
} catch (Exception e) {
throw new SenderException("Error during ftp-ing " + message, e);
}
return message;
}
use of nl.nn.adapterframework.core.IPipeLineSession in project iaf by ibissource.
the class ApiListenerServlet method service.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* Initiate and populate messageContext
*/
IPipeLineSession messageContext = new PipeLineSessionBase();
messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
ISecurityHandler securityHandler = new HttpSecurityHandler(request);
messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
try {
String uri = request.getPathInfo();
String method = request.getMethod().toUpperCase();
log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");
if (uri == null) {
response.setStatus(400);
log.warn("Aborting request with status [400], empty uri");
return;
}
if (uri.startsWith("/"))
uri = uri.substring(1);
if (uri.endsWith("/"))
uri = uri.substring(0, uri.length() - 1);
ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
if (config == null) {
response.setStatus(404);
log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
return;
}
/**
* Handle Cross-Origin Resource Sharing
*/
if (method.equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
String headers = request.getHeader("Access-Control-Request-Headers");
if (headers != null)
response.setHeader("Access-Control-Allow-Headers", headers);
response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);
StringBuilder methods = new StringBuilder();
for (String mtd : config.getMethods()) {
methods.append(", ").append(mtd);
}
response.setHeader("Access-Control-Allow-Methods", methods.toString());
response.setStatus(200);
log.trace("Aborting preflight request with status [200], method [" + method + "]");
return;
}
/**
* Get serviceClient
*/
ApiListener listener = config.getApiListener(method);
if (listener == null) {
response.setStatus(405);
log.trace("Aborting request with status [405], method [" + method + "] not allowed");
return;
}
log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");
/**
* Check authentication
*/
ApiPrincipal userPrincipal = null;
if (listener.getAuthenticationMethod() != null) {
String authorizationToken = null;
Cookie authorizationCookie = null;
if (listener.getAuthenticationMethod().equals("COOKIE")) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("authenticationToken")) {
authorizationToken = cookie.getValue();
authorizationCookie = cookie;
authorizationCookie.setPath("/");
}
}
} else if (listener.getAuthenticationMethod().equals("HEADER")) {
authorizationToken = request.getHeader("Authorization");
}
if (authorizationToken != null && cache.containsKey(authorizationToken))
userPrincipal = (ApiPrincipal) cache.get(authorizationToken);
if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
cache.remove(authorizationToken);
if (authorizationCookie != null) {
authorizationCookie.setMaxAge(0);
response.addCookie(authorizationCookie);
}
response.setStatus(401);
log.trace("Aborting request with status [401], no (valid) credentials supplied");
return;
}
if (authorizationCookie != null) {
authorizationCookie.setMaxAge(authTTL);
response.addCookie(authorizationCookie);
}
userPrincipal.updateExpiry();
userPrincipal.setToken(authorizationToken);
cache.put(authorizationToken, userPrincipal, authTTL);
messageContext.put("authorizationToken", authorizationToken);
}
messageContext.put("remoteAddr", request.getRemoteAddr());
messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
messageContext.put("uri", uri);
/**
* Evaluate preconditions
*/
String accept = request.getHeader("Accept");
if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
response.setStatus(406);
response.getWriter().print("It appears you expected the MediaType [" + accept + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
log.trace("Aborting request with status [406], client expects [" + accept + "] got [" + listener.getContentType() + "] instead");
return;
}
}
if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
response.setStatus(415);
log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes() + "] got [" + request.getContentType() + "] instead");
return;
}
String etagCacheKey = ApiCacheManager.buildCacheKey(config.getUriPattern());
if (cache.containsKey(etagCacheKey)) {
String cachedEtag = (String) cache.get(etagCacheKey);
if (method.equals("GET")) {
String ifNoneMatch = request.getHeader("If-None-Match");
if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
response.setStatus(304);
log.trace("Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
return;
}
} else {
String ifMatch = request.getHeader("If-Match");
if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
response.setStatus(412);
log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method [" + method + "]");
return;
}
}
}
/**
* Check authorization
*/
// TODO: authentication implementation
/**
* Map uriIdentifiers into messageContext
*/
String[] patternSegments = listener.getUriPattern().split("/");
String[] uriSegments = uri.split("/");
int uriIdentifier = 0;
for (int i = 0; i < patternSegments.length; i++) {
String segment = patternSegments[i];
if (segment.startsWith("{") && segment.endsWith("}")) {
String name;
if (segment.equals("*"))
name = "uriIdentifier_" + uriIdentifier;
else
name = segment.substring(1, segment.length() - 1);
uriIdentifier++;
log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
messageContext.put(name, uriSegments[i]);
}
}
/**
* Map queryParameters into messageContext
*/
Enumeration<?> paramnames = request.getParameterNames();
while (paramnames.hasMoreElements()) {
String paramname = (String) paramnames.nextElement();
String paramvalue = request.getParameter(paramname);
log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
messageContext.put(paramname, paramvalue);
}
/**
* Map multipart parts into messageContext
*/
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
messageContext.put(fieldName, fieldValue);
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fieldNameName = fieldName + "Name";
String fileName = FilenameUtils.getName(item.getName());
log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
messageContext.put(fieldNameName, fileName);
log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
messageContext.put(fieldName, item.getInputStream());
}
}
}
/**
* Compile Allow header
*/
StringBuilder methods = new StringBuilder();
methods.append("OPTIONS, ");
for (String mtd : config.getMethods()) {
methods.append(mtd + ", ");
}
messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));
/**
* Process the request through the pipeline
*/
String body = "";
if (!ServletFileUpload.isMultipartContent(request)) {
body = Misc.streamToString(request.getInputStream(), "\n", false);
}
String result = listener.processRequest(null, body, messageContext);
/**
* Calculate an etag over the processed result and store in cache
*/
if (listener.getUpdateEtag()) {
if (result != null && method.equals("GET")) {
String eTag = ApiCacheManager.buildEtag(listener.getCleanPattern(), result.hashCode());
cache.put(etagCacheKey, eTag);
response.addHeader("etag", eTag);
} else {
cache.remove(etagCacheKey);
}
}
/**
* Add headers
*/
response.addHeader("Allow", (String) messageContext.get("allowedMethods"));
String contentType = listener.getContentType() + "; charset=utf-8";
if (listener.getProduces().equals("ANY")) {
contentType = (String) messageContext.get("contentType");
}
response.setHeader("Content-Type", contentType);
/**
* Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
*/
int statusCode = 0;
if (messageContext.containsKey("exitcode"))
statusCode = Integer.parseInt("" + messageContext.get("exitcode"));
if (statusCode > 0)
response.setStatus(statusCode);
/**
* Finalize the pipeline and write the result to the response
*/
if (result != null)
response.getWriter().print(result);
log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
} catch (Exception e) {
log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
try {
response.flushBuffer();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
} catch (IllegalStateException ex) {
// We're only informing the end user(s), no need to catch this error...
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
Aggregations