use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class ChecksumPipe method provideOutputStream.
@Override
protected MessageOutputStream provideOutputStream(PipeLineSession session) throws StreamingException {
ChecksumGenerator cg;
try {
cg = createChecksumGenerator();
} catch (NoSuchAlgorithmException e) {
throw new StreamingException("Cannot create ChecksumGenerator", e);
}
OutputStream targetStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
cg.update(b);
}
@Override
public void write(byte[] buf, int offset, int length) throws IOException {
cg.update(buf, offset, length);
}
};
return new MessageOutputStream(this, targetStream, getNextPipe(), getCharset()) {
@Override
public Message getResponse() {
return new Message(cg.getResult());
}
};
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class Json2XmlValidator method doPipe.
/**
* Validate the XML or JSON input, and align/convert it into JSON or XML according to a XML-Schema.
* The format of the input message (XML or JSON) is automatically detected.
* @throws PipeRunException when <code>isThrowException</code> is true and a validationerror occurred.
*/
@Override
public PipeRunResult doPipe(Message input, PipeLineSession session, boolean responseMode, String messageRoot) throws PipeRunException {
String messageToValidate;
try {
messageToValidate = input == null || input.asObject() == null ? "{}" : input.asString();
} catch (IOException e) {
throw new PipeRunException(this, getLogPrefix(session) + "cannot open stream", e);
}
int i = 0;
while (i < messageToValidate.length() && Character.isWhitespace(messageToValidate.charAt(i))) i++;
if (i >= messageToValidate.length()) {
messageToValidate = "{}";
storeInputFormat(DocumentFormat.JSON, session, responseMode);
} else {
char firstChar = messageToValidate.charAt(i);
if (firstChar == '<') {
// message is XML
if (isAcceptNamespaceLessXml()) {
// TODO: do this via a filter
messageToValidate = addNamespace(messageToValidate);
// if (log.isDebugEnabled()) log.debug("added namespace to message ["+messageToValidate+"]");
}
storeInputFormat(DocumentFormat.XML, session, responseMode);
if (getOutputFormat(session, responseMode) != DocumentFormat.JSON) {
PipeRunResult result = super.doPipe(new Message(messageToValidate), session, responseMode, messageRoot);
if (isProduceNamespaceLessXml()) {
try {
result.setResult(XmlUtils.removeNamespaces(result.getResult().asString()));
} catch (IOException e) {
throw new PipeRunException(this, "Cannot remove namespaces", e);
}
}
return result;
}
try {
return alignXml2Json(messageToValidate, session, responseMode);
} catch (Exception e) {
throw new PipeRunException(this, "Alignment of XML to JSON failed", e);
}
}
if (firstChar != '{' && firstChar != '[') {
throw new PipeRunException(this, "message is not XML or JSON, because it starts with [" + firstChar + "] and not with '<', '{' or '['");
}
storeInputFormat(DocumentFormat.JSON, session, responseMode);
}
try {
return alignJson(messageToValidate, session, responseMode);
} catch (XmlValidatorException e) {
throw new PipeRunException(this, "Cannot align JSON", e);
}
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class Parameter method getValue.
/**
* determines the raw value
*/
public Object getValue(ParameterValueList alreadyResolvedParameters, Message message, PipeLineSession session, boolean namespaceAware) throws ParameterException {
Object result = null;
log.debug("Calculating value for Parameter [" + getName() + "]");
if (!configured) {
throw new ParameterException("Parameter [" + getName() + "] not configured");
}
String requestedSessionKey;
if (tpDynamicSessionKey != null) {
try {
requestedSessionKey = tpDynamicSessionKey.transform(message.asSource());
} catch (Exception e) {
throw new ParameterException("SessionKey for parameter [" + getName() + "] exception on transformation to get name", e);
}
} else {
requestedSessionKey = getSessionKey();
}
TransformerPool pool = getTransformerPool();
if (pool != null) {
try {
/*
* determine source for XSLT transformation from
* 1) value attribute
* 2) requestedSessionKey
* 3) pattern
* 4) input message
*
* N.B. this order differs from untransformed parameters
*/
Source source = null;
if (StringUtils.isNotEmpty(getValue())) {
source = XmlUtils.stringToSourceForSingleUse(getValue(), namespaceAware);
} else if (StringUtils.isNotEmpty(requestedSessionKey)) {
Object sourceObject = session.get(requestedSessionKey);
if (getType() == ParameterType.LIST && sourceObject instanceof List) {
// larva can produce the sourceObject as list
List<String> items = (List<String>) sourceObject;
XmlBuilder itemsXml = new XmlBuilder("items");
for (Iterator<String> it = items.iterator(); it.hasNext(); ) {
String item = it.next();
XmlBuilder itemXml = new XmlBuilder("item");
itemXml.setValue(item);
itemsXml.addSubElement(itemXml);
}
source = XmlUtils.stringToSourceForSingleUse(itemsXml.toXML(), namespaceAware);
} else if (getType() == ParameterType.MAP && sourceObject instanceof Map) {
// larva can produce the sourceObject as map
Map<String, String> items = (Map<String, String>) sourceObject;
XmlBuilder itemsXml = new XmlBuilder("items");
for (Iterator<String> it = items.keySet().iterator(); it.hasNext(); ) {
String item = it.next();
XmlBuilder itemXml = new XmlBuilder("item");
itemXml.addAttribute("name", item);
itemXml.setValue(items.get(item));
itemsXml.addSubElement(itemXml);
}
source = XmlUtils.stringToSourceForSingleUse(itemsXml.toXML(), namespaceAware);
} else {
Message sourceMsg = Message.asMessage(sourceObject);
if (StringUtils.isNotEmpty(getContextKey())) {
sourceMsg = Message.asMessage(sourceMsg.getContext().get(getContextKey()));
}
if (!sourceMsg.isEmpty()) {
log.debug("Parameter [" + getName() + "] using sessionvariable [" + requestedSessionKey + "] as source for transformation");
source = sourceMsg.asSource();
} else {
log.debug("Parameter [" + getName() + "] sessionvariable [" + requestedSessionKey + "] empty, no transformation will be performed");
}
}
} else if (StringUtils.isNotEmpty(getPattern())) {
String sourceString = format(alreadyResolvedParameters, session);
if (StringUtils.isNotEmpty(sourceString)) {
log.debug("Parameter [" + getName() + "] using pattern [" + getPattern() + "] as source for transformation");
source = XmlUtils.stringToSourceForSingleUse(sourceString, namespaceAware);
} else {
log.debug("Parameter [" + getName() + "] pattern [" + getPattern() + "] empty, no transformation will be performed");
}
} else {
if (StringUtils.isNotEmpty(getContextKey())) {
source = Message.asSource(message.getContext().get(getContextKey()));
} else {
source = message.asSource();
}
}
if (source != null) {
if (transformerPoolRemoveNamespaces != null) {
String rnResult = transformerPoolRemoveNamespaces.transform(source);
source = XmlUtils.stringToSource(rnResult);
}
ParameterValueList pvl = paramList == null ? null : paramList.getValues(message, session, namespaceAware);
switch(getType()) {
case NODE:
return transformToDocument(source, pvl).getFirstChild();
case DOMDOC:
return transformToDocument(source, pvl);
default:
String transformResult = pool.transform(source, pvl);
if (StringUtils.isNotEmpty(transformResult)) {
result = transformResult;
}
break;
}
}
} catch (Exception e) {
throw new ParameterException("Parameter [" + getName() + "] exception on transformation to get parametervalue", e);
}
} else {
/*
* No XSLT transformation, determine primary result from
* 1) requestedSessionKey
* 2) pattern
* 3) value attribute
* 4) input message
*
* N.B. this order differs from transformed parameters.
*/
if (StringUtils.isNotEmpty(requestedSessionKey)) {
result = session.get(requestedSessionKey);
if (result instanceof Message && StringUtils.isNotEmpty(getContextKey())) {
result = ((Message) result).getContext().get(getContextKey());
}
if (log.isDebugEnabled() && (result == null || result instanceof String && ((String) result).isEmpty() || result instanceof Message && ((Message) result).isEmpty())) {
log.debug("Parameter [" + getName() + "] session variable [" + requestedSessionKey + "] is empty");
}
} else if (StringUtils.isNotEmpty(getPattern())) {
result = format(alreadyResolvedParameters, session);
} else if (StringUtils.isNotEmpty(getValue())) {
result = getValue();
} else {
try {
if (message == null) {
return null;
}
if (StringUtils.isNotEmpty(getContextKey())) {
result = message.getContext().get(getContextKey());
} else {
message.preserve();
result = message;
}
} catch (IOException e) {
throw new ParameterException(e);
}
}
}
if (result != null && result instanceof Message) {
// avoid the IOException thrown by asString()
result = ((Message) result).asObject();
}
if (result != null) {
if (log.isDebugEnabled())
log.debug("Parameter [" + getName() + "] resolved to [" + (isHidden() ? hide(result.toString()) : result) + "]");
} else {
// if result is null then return specified default value
// N.B.
Iterator<DefaultValueMethods> it = getDefaultValueMethodsList().iterator();
while (result == null && it.hasNext()) {
DefaultValueMethods method = it.next();
switch(method) {
case DEFAULTVALUE:
result = getDefaultValue();
break;
case SESSIONKEY:
result = session.get(requestedSessionKey);
break;
case PATTERN:
result = format(alreadyResolvedParameters, session);
break;
case VALUE:
result = getValue();
break;
case INPUT:
try {
message.preserve();
result = message.asString();
} catch (IOException e) {
throw new ParameterException(e);
}
break;
default:
throw new IllegalArgumentException("Unknown defaultValues method [" + method + "]");
}
}
if (result != null) {
log.debug("Parameter [" + getName() + "] resolved to defaultvalue [" + (isHidden() ? hide(result.toString()) : result) + "]");
}
}
if (result != null && result instanceof String) {
if (getMinLength() >= 0 && getType() != ParameterType.NUMBER) {
if (((String) result).length() < getMinLength()) {
log.debug("Padding parameter [" + getName() + "] because length [" + ((String) result).length() + "] falls short of minLength [" + getMinLength() + "]");
result = StringUtils.rightPad(((String) result), getMinLength());
}
}
if (getMaxLength() >= 0) {
if (((String) result).length() > getMaxLength()) {
log.debug("Trimming parameter [" + getName() + "] because length [" + ((String) result).length() + "] exceeds maxLength [" + getMaxLength() + "]");
result = ((String) result).substring(0, getMaxLength());
}
}
}
if (result != null && getType().requiresTypeConversion) {
result = getValueAsType(result, namespaceAware);
}
if (result != null && result instanceof Number) {
if (getMinInclusiveString() != null && ((Number) result).floatValue() < minInclusive.floatValue()) {
log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] falls short of minInclusive [" + getMinInclusiveString() + "]");
result = minInclusive;
}
if (getMaxInclusiveString() != null && ((Number) result).floatValue() > maxInclusive.floatValue()) {
log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] exceeds maxInclusive [" + getMaxInclusiveString() + "]");
result = maxInclusive;
}
}
if (getType() == ParameterType.NUMBER && getMinLength() >= 0 && (result + "").length() < getMinLength()) {
log.debug("Adding leading zeros to parameter [" + getName() + "]");
result = StringUtils.leftPad(result + "", getMinLength(), '0');
}
return result;
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class Parameter method getValueForFormatting.
private Object getValueForFormatting(ParameterValueList alreadyResolvedParameters, PipeLineSession session, String targetPattern) throws ParameterException {
String[] patternElements = targetPattern.split(",");
String name = patternElements[0].trim();
String formatType = patternElements.length > 1 ? patternElements[1].trim() : null;
ParameterValue paramValue = alreadyResolvedParameters.getParameterValue(name);
Object substitutionValue = paramValue == null ? null : paramValue.getValue();
if (substitutionValue == null) {
Message substitutionValueMessage = session.getMessage(name);
if (!substitutionValueMessage.isEmpty()) {
if (substitutionValueMessage.asObject() instanceof Date) {
substitutionValue = preFormatDateType(substitutionValueMessage.asObject(), formatType);
} else {
try {
substitutionValue = substitutionValueMessage.asString();
} catch (IOException e) {
throw new ParameterException("Cannot get substitution value", e);
}
}
}
}
if (substitutionValue == null) {
String namelc = name.toLowerCase();
if ("now".equals(name.toLowerCase())) {
substitutionValue = preFormatDateType(new Date(), formatType);
} else if ("uid".equals(namelc)) {
substitutionValue = Misc.createSimpleUUID();
} else if ("uuid".equals(namelc)) {
substitutionValue = Misc.createRandomUUID();
} else if ("hostname".equals(namelc)) {
substitutionValue = Misc.getHostname();
} else if ("fixeddate".equals(namelc)) {
if (!ConfigurationUtils.isConfigurationStubbed(configurationClassLoader)) {
throw new ParameterException("Parameter pattern [" + name + "] only allowed in stub mode");
}
Object fixedDateTime = session.get(PutSystemDateInSession.FIXEDDATE_STUB4TESTTOOL_KEY);
if (fixedDateTime == null) {
fixedDateTime = PutSystemDateInSession.FIXEDDATETIME;
}
substitutionValue = preFormatDateType(fixedDateTime, formatType);
} else if ("fixeduid".equals(namelc)) {
if (!ConfigurationUtils.isConfigurationStubbed(configurationClassLoader)) {
throw new ParameterException("Parameter pattern [" + name + "] only allowed in stub mode");
}
substitutionValue = FIXEDUID;
} else if ("fixedhostname".equals(namelc)) {
if (!ConfigurationUtils.isConfigurationStubbed(configurationClassLoader)) {
throw new ParameterException("Parameter pattern [" + name + "] only allowed in stub mode");
}
substitutionValue = FIXEDHOSTNAME;
} else if ("username".equals(namelc)) {
substitutionValue = cf != null ? cf.getUsername() : "";
} else if ("password".equals(namelc)) {
substitutionValue = cf != null ? cf.getPassword() : "";
}
}
if (substitutionValue == null) {
throw new ParameterException("Parameter or session variable with name [" + name + "] in pattern [" + getPattern() + "] cannot be resolved");
}
return substitutionValue;
}
use of nl.nn.adapterframework.stream.Message in project iaf by ibissource.
the class JavaListener method processRequest.
@Override
public String processRequest(String correlationId, String rawMessage, HashMap context) throws ListenerException {
if (!isOpen()) {
throw new ListenerException("JavaListener [" + getName() + "] is not opened");
}
if (log.isDebugEnabled()) {
log.debug("JavaListener [" + getName() + "] processing correlationId [" + correlationId + "]");
}
if (context != null) {
Object object = context.get("httpRequest");
if (object != null) {
if (object instanceof HttpServletRequest) {
ISecurityHandler securityHandler = new HttpSecurityHandler((HttpServletRequest) object);
context.put(PipeLineSession.securityHandlerKey, securityHandler);
} else {
log.warn("No securityHandler added for httpRequest [" + object.getClass() + "]");
}
}
}
Message message = new Message(rawMessage);
if (throwException) {
try {
return handler.processRequest(this, correlationId, rawMessage, message, (Map<String, Object>) context).asString();
} catch (IOException e) {
throw new ListenerException("cannot convert stream", e);
}
}
try {
return handler.processRequest(this, correlationId, rawMessage, message, context).asString();
} catch (ListenerException | IOException e) {
try {
return handler.formatException(null, correlationId, message, e).asString();
} catch (IOException e1) {
e.addSuppressed(e1);
throw new ListenerException(e);
}
}
}
Aggregations