use of nl.nn.adapterframework.core.PipeLineSessionBase in project iaf by ibissource.
the class RestListener method transformToXml.
public String transformToXml(String message) throws PipeRunException {
JsonPipe pipe = new JsonPipe();
PipeRunResult pipeResult = pipe.doPipe(message, new PipeLineSessionBase());
return (String) pipeResult.getResult();
}
use of nl.nn.adapterframework.core.PipeLineSessionBase in project iaf by ibissource.
the class RestListener method transformToJson.
public String transformToJson(String message) throws PipeRunException {
JsonPipe pipe = new JsonPipe();
pipe.setDirection("xml2json");
PipeRunResult pipeResult = pipe.doPipe(message, new PipeLineSessionBase());
return (String) pipeResult.getResult();
}
use of nl.nn.adapterframework.core.PipeLineSessionBase in project iaf by ibissource.
the class RestServiceDispatcher method dispatchRequest.
/**
* Dispatch a request.
* @param uri the name of the IReceiver object
* @param method the correlationId of this request;
* @param request the <code>String</code> with the request/input
* @return String with the result of processing the <code>request</code> through the <code>serviceName</code>
*/
public String dispatchRequest(String restPath, String uri, HttpServletRequest httpServletRequest, String contentType, String request, IPipeLineSession context, HttpServletResponse httpServletResponse, ServletContext servletContext) throws ListenerException {
String method = httpServletRequest.getMethod();
if (log.isTraceEnabled())
log.trace("searching listener for uri [" + uri + "] method [" + method + "]");
String matchingPattern = findMatchingPattern(uri);
if (matchingPattern == null) {
if (uri != null && (uri.equals("/showFlowDiagram") || uri.startsWith("/showFlowDiagram/"))) {
log.info("no REST listener configured for uri [" + uri + "], so using 'no image available'");
noImageAvailable(httpServletResponse);
return "";
}
if (uri != null && (uri.equals("/showConfigurationStatus") || uri.startsWith("/showConfigurationStatus/"))) {
log.info("no REST listener configured for uri [" + uri + "], if REST listener does exist then trying to restart");
if (RestListenerUtils.restartShowConfigurationStatus(servletContext)) {
httpServletResponse.setHeader("REFRESH", "0");
return "";
}
}
throw new ListenerException("no REST listener configured for uri [" + uri + "]");
}
Map methodConfig = getMethodConfig(matchingPattern, method);
if (methodConfig == null) {
throw new ListenerException("No REST listener specified for uri [" + uri + "] method [" + method + "]");
}
if (context == null) {
context = new PipeLineSessionBase();
}
context.put("restPath", restPath);
context.put("uri", uri);
context.put("method", method);
String etag = null;
String ifNoneMatch = httpServletRequest.getHeader("If-None-Match");
if (ifNoneMatch != null && !ifNoneMatch.isEmpty()) {
context.put("if-none-match", ifNoneMatch);
etag = ifNoneMatch;
}
String ifMatch = httpServletRequest.getHeader("If-Match");
if (ifMatch != null && !ifMatch.isEmpty()) {
context.put("if-match", ifMatch);
etag = ifMatch;
}
context.put("contentType", contentType);
context.put("userAgent", httpServletRequest.getHeader("User-Agent"));
ServiceClient listener = (ServiceClient) methodConfig.get(KEY_LISTENER);
String etagKey = (String) methodConfig.get(KEY_ETAG_KEY);
String contentTypeKey = (String) methodConfig.get(KEY_CONTENT_TYPE_KEY);
Principal principal = null;
if (httpServletRequest != null) {
principal = httpServletRequest.getUserPrincipal();
if (principal != null) {
context.put("principal", principal.getName());
}
}
String ctName = Thread.currentThread().getName();
try {
boolean writeToSecLog = false;
if (listener instanceof RestListener) {
RestListener restListener = (RestListener) listener;
if (restListener.isRetrieveMultipart()) {
if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
try {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = servletFileUpload.parseRequest(httpServletRequest);
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 parameter [" + fieldName + "] to [" + fieldValue + "]");
context.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());
if (log.isTraceEnabled())
log.trace("setting parameter [" + fieldNameName + "] to [" + fileName + "]");
context.put(fieldNameName, fileName);
InputStream inputStream = item.getInputStream();
if (inputStream.available() > 0) {
log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
context.put(fieldName, inputStream);
} else {
log.trace("setting parameter [" + fieldName + "] to [" + null + "]");
context.put(fieldName, null);
}
}
}
} catch (FileUploadException e) {
throw new ListenerException(e);
} catch (IOException e) {
throw new ListenerException(e);
}
}
}
writeToSecLog = restListener.isWriteToSecLog();
if (writeToSecLog) {
context.put("writeSecLogMessage", restListener.isWriteSecLogMessage());
}
boolean authorized = false;
if (principal == null) {
authorized = true;
} else {
String authRoles = restListener.getAuthRoles();
if (StringUtils.isNotEmpty(authRoles)) {
StringTokenizer st = new StringTokenizer(authRoles, ",;");
while (st.hasMoreTokens()) {
String authRole = st.nextToken();
if (httpServletRequest.isUserInRole(authRole)) {
authorized = true;
}
}
}
}
if (!authorized) {
throw new ListenerException("Not allowed for uri [" + uri + "]");
}
Thread.currentThread().setName(restListener.getName() + "[" + ctName + "]");
}
if (etagKey != null)
context.put(etagKey, etag);
if (contentTypeKey != null)
context.put(contentTypeKey, contentType);
if (log.isTraceEnabled())
log.trace("dispatching request, uri [" + uri + "] listener pattern [" + matchingPattern + "] method [" + method + "] etag [" + etag + "] contentType [" + contentType + "]");
if (httpServletRequest != null)
context.put(IPipeLineSession.HTTP_REQUEST_KEY, httpServletRequest);
if (httpServletResponse != null)
context.put(IPipeLineSession.HTTP_RESPONSE_KEY, httpServletResponse);
if (servletContext != null)
context.put(IPipeLineSession.SERVLET_CONTEXT_KEY, servletContext);
if (writeToSecLog) {
secLog.info(HttpUtils.getExtendedCommandIssuedBy(httpServletRequest));
}
// Caching: check for etags
if (uri.startsWith("/"))
uri = uri.substring(1);
if (uri.indexOf("?") > -1) {
uri = uri.split("?")[0];
}
String etagCacheKey = restPath + "_" + uri;
if (cache != null && cache.containsKey(etagCacheKey)) {
String cachedEtag = (String) cache.get(etagCacheKey);
if (ifNoneMatch != null && ifNoneMatch.equalsIgnoreCase(cachedEtag) && method.equalsIgnoreCase("GET")) {
// Exit with 304
context.put("exitcode", 304);
if (log.isDebugEnabled())
log.trace("aborting request with status 304, matched if-none-match [" + ifNoneMatch + "]");
return null;
}
if (ifMatch != null && !ifMatch.equalsIgnoreCase(cachedEtag) && !method.equalsIgnoreCase("GET")) {
// Exit with 412
context.put("exitcode", 412);
if (log.isDebugEnabled())
log.trace("aborting request with status 412, matched if-match [" + ifMatch + "] method [" + method + "]");
return null;
}
}
String result = listener.processRequest(null, request, context);
// Caching: pipeline has been processed, save etag
if (result != null && cache != null && context.containsKey("etag")) {
// In case the eTag has manually been set and the pipeline exited in error state...
cache.put(etagCacheKey, context.get("etag"));
}
if (result == null && !context.containsKey("exitcode")) {
log.warn("result is null!");
}
return result;
} finally {
if (listener instanceof RestListener) {
Thread.currentThread().setName(ctName);
}
}
}
use of nl.nn.adapterframework.core.PipeLineSessionBase 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);
}
}
}
use of nl.nn.adapterframework.core.PipeLineSessionBase in project iaf by ibissource.
the class ObjectServiceImpl method getObject.
@Override
public ObjectData getObject(String repositoryId, String objectId, String filter, Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter, Boolean includePolicyIds, Boolean includeAcl, ExtensionsData extensions) {
boolean bypass = AppConstants.getInstance().getBoolean("cmis.proxy.bypass.getObject", false);
if (!bypass) {
ObjectData objectData = objectService.getObject(repositoryId, objectId, filter, includeAllowableActions, includeRelationships, renditionFilter, includePolicyIds, includeAcl, extensions);
return objectData;
} else {
XmlBuilder cmisXml = new XmlBuilder("cmis");
cmisXml.addSubElement(buildXml("repositoryId", repositoryId));
cmisXml.addSubElement(buildXml("objectId", objectId));
cmisXml.addSubElement(buildXml("filter", filter));
cmisXml.addSubElement(buildXml("includeAllowableActions", includeAllowableActions));
cmisXml.addSubElement(buildXml("includePolicies", includePolicyIds));
cmisXml.addSubElement(buildXml("includeAcl", includeAcl));
ObjectDataImpl impl = new ObjectDataImpl();
try {
IPipeLineSession messageContext = new PipeLineSessionBase();
String result = CmisServletDispatcher.getInstance().getCmisListener().processRequest(null, cmisXml.toXML(), messageContext);
Element cmisElement;
if (XmlUtils.isWellFormed(result, "cmis")) {
cmisElement = XmlUtils.buildElement(result);
} else {
cmisElement = XmlUtils.buildElement("<cmis/>");
}
// Handle allowable actions
Element allowableActionsElem = XmlUtils.getFirstChildTag(cmisElement, "allowableActions");
if (allowableActionsElem != null) {
AllowableActionsImpl allowableActions = new AllowableActionsImpl();
Set<Action> actions = EnumSet.noneOf(Action.class);
Iterator<Node> actionIterator = XmlUtils.getChildTags(allowableActionsElem, "action").iterator();
while (actionIterator.hasNext()) {
String property = XmlUtils.getStringValue((Element) actionIterator.next());
actions.add(Action.fromValue(property));
}
allowableActions.setAllowableActions(actions);
impl.setAllowableActions(allowableActions);
}
// Handle isExactAcl
impl.setIsExactAcl(XmlUtils.getChildTagAsBoolean(cmisElement, "isExactAcl"));
// Handle policyIds
Element policyIdsElem = XmlUtils.getFirstChildTag(cmisElement, "policyIds");
if (policyIdsElem != null) {
PolicyIdListImpl policyIdList = new PolicyIdListImpl();
List<String> policies = new ArrayList<String>();
Iterator<Node> policyIterator = XmlUtils.getChildTags(allowableActionsElem, "policyId").iterator();
while (policyIterator.hasNext()) {
String policyId = XmlUtils.getStringValue((Element) policyIterator.next());
policies.add(policyId);
}
policyIdList.setPolicyIds(policies);
impl.setPolicyIds(policyIdList);
}
// Handle properties
impl.setProperties(processProperties(cmisElement));
} catch (Exception e) {
log.error("error creating CMIS objectData: " + e.getMessage(), e.getCause());
}
impl.setRenditions(null);
impl.setExtensions(null);
impl.setChangeEventInfo(null);
impl.setRelationships(null);
return impl;
}
}
Aggregations