use of com.dexels.navajo.expression.api.TMLExpressionException in project navajo by Dexels.
the class Parameters method store.
public void store(String name, String value, String type, String condition, Navajo doc) throws SystemException {
if (!this.isValueStored(name).equals(""))
return;
// First check condition.
boolean eval = false;
try {
if (condition.trim().equals(""))
eval = true;
else
eval = Condition.evaluate(condition, doc, null);
} catch (TMLExpressionException ce) {
eval = false;
}
// If condition succeeds evaluate parameter expression.
if (eval) {
Parameter p = new Parameter();
p.name = name;
try {
Operand op = Expression.evaluate(value, doc, null, null, null, null, null, null);
p.value = op.value;
} catch (TMLExpressionException tmle) {
// throw new SystemException(SystemException.PARSE_ERROR, "Invalid parameter expression: " + value + "\n"+tmle.getMessage());
}
p.type = type;
p.condition = condition;
super.put(name, p);
}
}
use of com.dexels.navajo.expression.api.TMLExpressionException in project navajo by Dexels.
the class CachedExpressionEvaluator method evaluate.
@Override
public Operand evaluate(String clause, Navajo inMessage, Object mappableTreeNode, Message parent, Optional<ImmutableMessage> immutableMessage, Optional<ImmutableMessage> paramMessage) {
ExpressionCache ce = ExpressionCache.getInstance();
Object val;
String type;
try {
val = ce.evaluate(clause, inMessage, parent, null, null, (MappableTreeNode) mappableTreeNode, null, null, immutableMessage, paramMessage);
type = MappingUtils.determineNavajoType(val);
return new Operand(val, type, "");
} catch (TMLExpressionException e) {
if (inMessage != null) {
// Only log if we have useful context
logger.error("TML parsing issue with expression: {} exception", clause, e);
}
throw new TMLExpressionException("TML parsing issue");
}
}
use of com.dexels.navajo.expression.api.TMLExpressionException in project navajo by Dexels.
the class MergePDFsFromDatasource method evaluate.
@SuppressWarnings("unchecked")
@Override
public Object evaluate() throws TMLExpressionException {
if (getOperands().size() != 7) {
throw new TMLExpressionException("Invalid number of operands.");
}
// List items contains all the ids of the document
ArrayList<String> items = null;
if (getOperand(0) != null) {
if (getOperand(0) instanceof ArrayList) {
items = (ArrayList<String>) getOperand(0);
} else if (getOperand(0) instanceof String) {
items = (ArrayList<String>) Arrays.stream(((String) getOperand(0)).split(";")).map(o -> o.toString()).collect(Collectors.toList());
}
}
int transactionContext = -1;
if (getOperand(1) != null && getOperand(1) instanceof Integer) {
transactionContext = ((Integer) getOperand(1)).intValue();
}
String datasource = null;
if (getOperand(2) != null && getOperand(2) instanceof String) {
datasource = (String) getOperand(2);
}
String username = null;
if (getOperand(3) != null && getOperand(3) instanceof String) {
username = (String) getOperand(3);
}
String tableId = null;
if (getOperand(4) != null && getOperand(4) instanceof String) {
tableId = (String) getOperand(4);
}
String objectType = null;
if (getOperand(5) != null && getOperand(5) instanceof String) {
objectType = (String) getOperand(5);
}
String binaryColumnName = null;
if (getOperand(6) != null && getOperand(6) instanceof String) {
binaryColumnName = (String) getOperand(6);
}
// Max in operator in oracle takes 1000 ites, but we need more ::
int numOfItems = items.size();
String queryPart = "";
if (numOfItems == 1) {
queryPart = " in " + items.toString().replace("[", "('").replace("]", "')").replace(" ", "");
} else {
int startPosition = 0;
int endPosition = 999;
if (startPosition + endPosition >= numOfItems) {
endPosition = numOfItems - 1;
} else {
endPosition = startPosition + 999;
}
while (endPosition <= numOfItems && startPosition != endPosition) {
queryPart = queryPart + " or " + tableId + " in " + items.subList(startPosition, endPosition).toString().replace(",", "','").replace("[", "('").replace("]", "')").replace(" ", "");
startPosition = endPosition;
if (endPosition + 999 >= numOfItems) {
endPosition = numOfItems;
} else {
endPosition = startPosition + 999;
}
}
queryPart = queryPart.substring(4).substring(tableId.length());
}
String query = "select * FROM document where (" + tableId + queryPart + ") AND objectType = '" + objectType + "'";
JDBCMappable sql = null;
ArrayList<Object> result = new ArrayList<>();
try {
sql = JDBCFactory.getJDBCMap(getAccess());
if (transactionContext != -1) {
sql.setTransactionContext(transactionContext);
} else {
sql.setDatasource(datasource);
sql.setUsername(username);
}
sql.setQuery(query);
System.out.println(query);
ResultSetMap[] resultSet = sql.getResultSet();
if (resultSet.length > 0) {
for (int i = 0; i < resultSet.length; i++) {
result.add(resultSet[i].getColumnValue(0));
}
}
int dataPosition = -1;
// We got them all, now MERGE :D
if (result.size() > 0) {
// First find DATA position
for (int i = 0; i < resultSet[0].getValuesSize(); i++) {
if (resultSet[0].getColumnName(i).equalsIgnoreCase(binaryColumnName)) {
dataPosition = i;
break;
}
}
// Then combine
try {
PDFMergerUtility merger = new PDFMergerUtility();
File tempFile = File.createTempFile("pdfmerge", "pdf");
String fileName = tempFile.getCanonicalPath();
merger.setDestinationFileName(fileName);
// Logic to short by items.
for (String item : items) {
for (int i = 0; i < resultSet.length; i++) {
if (resultSet[i].getColumnValue(tableId).toString().equals(item)) {
// FOUND
merger.addSource(((Binary) resultSet[i].getColumnValue(dataPosition)).getFile());
break;
}
}
}
merger.mergeDocuments();
Binary resultPDF = new Binary(new File(fileName), false);
tempFile.delete();
return resultPDF;
} catch (IOException e) {
throw new TMLExpressionException(this, e.getMessage(), e);
}
}
} catch (Exception e) {
sql.kill();
throw new TMLExpressionException(this, "Fatal error: " + e.getMessage() + ", query = " + query, e);
} finally {
sql.kill();
}
return null;
}
use of com.dexels.navajo.expression.api.TMLExpressionException in project navajo by Dexels.
the class GetBinaryFromStore method evaluate.
@Override
public Object evaluate() throws TMLExpressionException {
String resource = (String) getOperand(0);
if (resource == null) {
throw new TMLExpressionException("No resource defined in GetBinaryFromStore");
}
String bucket = (String) getOperand(1);
if (bucket == null) {
throw new TMLExpressionException("No bucket defined in GetBinaryFromStore");
}
Object idObj = getOperand(2);
String id = null;
if (idObj instanceof String) {
id = (String) idObj;
} else {
id = idObj.toString();
}
if (id == null) {
throw new TMLExpressionException("No id defined in GetBinaryFromStore");
}
Integer expiration = (Integer) super.getOperand(3);
if (expiration == null) {
throw new TMLExpressionException("No expiration defined in GetBinaryFromStore");
}
Access access = this.getAccess();
String tenant = access.getTenant();
HttpResourceFactory instance = HttpResourceFactory.getInstance();
if (instance == null) {
throw new TMLExpressionException("No HttpResourceFactory found in GetBinaryFromStore");
}
HttpResource httpResource = instance.getHttpResource(resource);
if (httpResource == null) {
throw new TMLExpressionException("HttpResource: " + resource + " not found in GetBinaryFromStore");
}
return httpResource.expiringURL(tenant, bucket, id, expiration);
}
use of com.dexels.navajo.expression.api.TMLExpressionException in project navajo by Dexels.
the class TslCompiler method optimizeExpresssion.
/**
* VERY NASTY METHOD. IT TRIES ALL KINDS OF TRICKS TO TRY TO AVOID CALLING
* THE EXPRESSION.EVALUATE() METHOD IN THE GENERATED JAVA.
*
* @param ident
* @param clause
* @param className
* @return
*/
public String optimizeExpresssion(int ident, String clause, String className, String objectName) throws UserException {
boolean exact = false;
StringBuilder result = new StringBuilder();
char firstChar = ' ';
boolean functionCall = false;
StringBuilder functionNameBuffer = new StringBuilder();
String functionName = "";
String call = "";
// attribute call.
for (int i = 0; i < clause.length(); i++) {
char c = clause.charAt(i);
if (c != ' ' && firstChar == ' ') {
firstChar = c;
}
if (((firstChar > 'a' && firstChar < 'z')) || ((firstChar > 'A') && (firstChar < 'Z'))) {
functionCall = true;
}
if ((functionCall) && (c != '(')) {
functionNameBuffer.append(c);
} else if (functionCall && c == '(') {
functionName = functionNameBuffer.toString();
functionNameBuffer = new StringBuilder();
}
if (c == '$') {
// New attribute found
StringBuilder name = new StringBuilder();
i++;
c = clause.charAt(i);
while (c != '(' && i < clause.length() && c != ')') {
name.append(c);
i++;
if (i < clause.length()) {
c = clause.charAt(i);
}
}
if (name.toString().contains("..")) {
// We cannot optimize these yet
continue;
}
i++;
StringBuilder params = new StringBuilder();
if (clause.indexOf("(") != -1) {
// Determine parameters.
int endOfParams = 1;
while (endOfParams > 0 && i < clause.length()) {
c = clause.charAt(i);
if (c == '(') {
endOfParams++;
} else if (c == ')') {
endOfParams--;
} else {
params.append(c);
}
i++;
}
}
String expr = "";
if (functionName.equals("")) {
expr = (params.toString().length() > 0 ? "$" + name + "(" + params + ")" : "$" + name);
} else {
expr = functionName + "(" + (params.toString().length() > 0 ? "$" + name + "(" + params + ")" : "$" + name) + ")";
}
if (removeWhiteSpaces(expr).equals(removeWhiteSpaces(clause))) {
// Let's evaluate this directly.
exact = true;
Class expressionContextClass = null;
try {
StringBuilder objectizedParams = new StringBuilder();
StringTokenizer allParams = new StringTokenizer(params.toString(), ",");
while (allParams.hasMoreElements()) {
String param = allParams.nextToken();
// Try to evaluate expression (NOTE THAT IF
// REFERENCES ARE MADE TO EITHER NAVAJO OR MAPPABLE
// OBJECTS THIS WILL FAIL
// SINCE THESE OBJECTS ARE NOT KNOWN AT COMPILE
// TIME!!!!!!!!!!!!!!1
Operand op = Expression.evaluate(param, null);
Object v = op.value;
if (v instanceof String) {
objectizedParams.append("\"" + v + "\"");
} else if (v instanceof Integer) {
objectizedParams.append("new Integer(" + v + ")");
} else if (v instanceof Long) {
objectizedParams.append("Long.valueOf(" + v + ")");
} else if (v instanceof Float) {
objectizedParams.append("new Float(" + v + ")");
} else if (v instanceof Boolean) {
objectizedParams.append("new Boolean(" + v + ")");
} else if (v instanceof Double) {
objectizedParams.append("Double.valueOf(" + v + ")");
} else if (v == null) {
// Null support
objectizedParams.append(v);
} else {
throw new UserException(-1, "Unknown type encountered during compile time: " + v.getClass().getName() + " @clause: " + clause);
}
if (allParams.hasMoreElements()) {
objectizedParams.append(',');
}
}
try {
expressionContextClass = Class.forName(className, false, loader);
} catch (Exception e) {
throw new Exception("Could not find adapter: " + className);
}
String attrType = MappingUtils.getFieldType(expressionContextClass, name.toString());
// Try to locate class:
if (!functionName.equals("")) {
try {
Class.forName("com.dexels.navajo.functions." + functionName, false, loader);
} catch (Exception e) {
throw new Exception("Could not find Navajo function: " + functionName);
}
}
call = objectName + ".get" + (name.charAt(0) + "").toUpperCase() + name.substring(1) + "(" + objectizedParams.toString() + ")";
if (attrType.equals("int")) {
call = "new Integer(" + call + ")";
} else if (attrType.equals("float") || attrType.equals("double")) {
call = "Double.valueOf(" + call + ")";
} else if (attrType.equals("boolean")) {
call = "new Boolean(" + call + ")";
} else if (attrType.equals("long")) {
call = "Long.valueOf(" + call + ")";
}
} catch (ClassNotFoundException cnfe) {
if (expressionContextClass == null) {
throw new UserException(-1, "Error in script: Could not find adapter: " + className + " @clause: " + clause);
} else {
throw new UserException(-1, "Error in script: Could not locate function: " + functionName + " @ clause: " + clause);
}
} catch (Throwable e) {
exact = false;
}
}
}
}
// Try to evaluate clause directly (compile time).
if ((!exact) && !clause.equals("TODAY") && !clause.equals("null") && (clause.indexOf("[") == -1) && (clause.indexOf("$") == -1) && (clause.indexOf("(") == -1) && (clause.indexOf("+") == -1)) {
try {
Operand op = Expression.evaluate(clause, null);
Object v = op.value;
exact = true;
if (v instanceof String) {
call = replaceQuotesValue((String) v);
} else if (v instanceof Integer) {
call = "new Integer(" + v + ")";
} else if (v instanceof Long) {
call = "Long.valueOf(" + v + ")";
} else if (v instanceof Float) {
call = "new Float(" + v + ")";
} else if (v instanceof Boolean) {
call = "new Boolean(" + v + ")";
} else if (v instanceof Double) {
call = "Double.valueOf(" + v + ")";
} else
throw new UserException(-1, "Unknown type encountered during compile time: " + v.getClass().getName() + " @clause: " + clause);
} catch (NullPointerException | TMLExpressionException ne) {
exact = false;
} catch (SystemException se) {
exact = false;
if (clause.length() == 0 || clause.charAt(0) != '#') {
throw new UserException(-1, "Could not compile script, Invalid expression: " + clause);
}
} catch (Throwable e) {
exact = false;
}
}
if (!exact && clause.equals("null")) {
call = "null";
exact = true;
}
// Use Expression.evaluate() if expression could not be executed in an
// optimized way.
result.append(printIdent(ident) + "op = Expression.evaluate(" + replaceQuotes(clause) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg, currentSelection, null, getEvaluationParams());\n");
result.append(printIdent(ident) + "sValue = op.value;\n");
return result.toString();
}
Aggregations