/** * Create a new Jinjava processor instance with the default global config */ public Jinjava() { this(new JinjavaConfig()); }
private static JinjavaConfig buildJinjavaConfig(boolean failOnUnknownTokens) { JinjavaConfig.Builder configBuilder = JinjavaConfig.newBuilder(); configBuilder.withFailOnUnknownTokens(failOnUnknownTokens); Map<Library, Set<String>> disabled = new HashMap<>(); disabled.put(Library.TAG, new HashSet<>(Arrays.asList("from", "import", "include"))); configBuilder.withDisabled(disabled); return configBuilder.build(); } }
@Override public Object filter(Object object, JinjavaInterpreter interpreter, String... arg) { if (object instanceof String) { return md5((String) object, interpreter.getConfig().getCharset()); } return object; }
private void resolveBlockStubs(OutputList output, Stack<String> blockNames) { for (BlockPlaceholderOutputNode blockPlaceholder : output.getBlocks()) { if (!blockNames.contains(blockPlaceholder.getBlockName())) { Collection<List<? extends Node>> blockChain = blocks.get(blockPlaceholder.getBlockName()); List<? extends Node> block = Iterables.getFirst(blockChain, null); if (block != null) { List<? extends Node> superBlock = Iterables.get(blockChain, 1, null); context.setSuperBlock(superBlock); OutputList blockValueBuilder = new OutputList(config.getMaxOutputSize()); for (Node child : block) { blockValueBuilder.addNode(child.render(this)); } blockNames.push(blockPlaceholder.getBlockName()); resolveBlockStubs(blockValueBuilder, blockNames); blockNames.pop(); context.removeSuperBlock(); blockPlaceholder.resolve(blockValueBuilder.getValue()); } } if (!blockPlaceholder.isResolved()) { blockPlaceholder.resolve(""); } } }
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { int defaultVal = 0; if (args.length > 0) { defaultVal = NumberUtils.toInt(args[0], 0); } if (var == null) { return defaultVal; } if (Number.class.isAssignableFrom(var.getClass())) { return ((Number) var).intValue(); } String input = var.toString().trim(); Locale locale = interpreter.getConfig().getLocale(); NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); ParsePosition pp = new ParsePosition(0); int result; try { result = numberFormat.parse(input, pp).intValue(); } catch (Exception e) { result = defaultVal; } if (pp.getErrorIndex() != -1 || pp.getIndex() != input.length()) { result = defaultVal; } return result; }
public JinjavaInterpreter(Jinjava application, Context context, JinjavaConfig renderConfig) { this.context = context; this.config = renderConfig; this.application = application; if (config.getRandomNumberGeneratorStrategy() == RandomNumberGeneratorStrategy.THREAD_LOCAL) { random = ThreadLocalRandom.current(); } else if (config.getRandomNumberGeneratorStrategy() == RandomNumberGeneratorStrategy.CONSTANT_ZERO) { random = new ConstantZeroRandomNumberGenerator(); } else { throw new IllegalStateException("No random number generator with strategy " + config.getRandomNumberGeneratorStrategy()); } this.expressionResolver = new ExpressionResolver(this, application.getExpressionFactory()); }
/** * Parse the given string into a root Node, and then render it without processing any extend parents. * This method should be used when the template is known to not have any extends or block tags. * * @param template * string to parse * @return rendered result */ public String renderFlat(String template) { int depth = context.getRenderDepth(); try { if (depth > config.getMaxRenderDepth()) { ENGINE_LOG.warn("Max render depth exceeded: {}", Integer.toString(depth)); return template; } else { context.setRenderDepth(depth + 1); return render(parse(template), false); } } finally { context.setRenderDepth(depth); } }
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { LengthLimitingStringBuilder stringBuilder = new LengthLimitingStringBuilder(interpreter.getConfig().getMaxStringLength()); ErrorReason.OTHER, ErrorItem.FILTER, String.format("Result of %s filter has been truncated to the max String length of %d", getName(), interpreter.getConfig().getMaxStringLength()), null, interpreter.getLineNumber(),
Context context = new Context(globalContext, bindings, renderConfig.getDisabled());
@Override public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) { LengthLimitingStringBuilder result = new LengthLimitingStringBuilder(interpreter.getConfig().getMaxOutputSize()); for (Node n : tagNode.getChildren()) { result.append(renderNodeRaw(n)); } return result.toString(); }
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { float defaultVal = 0; if (args.length > 0) { defaultVal = NumberUtils.toFloat(args[0], 0.0f); } if (var == null) { return defaultVal; } if (Float.class.isAssignableFrom(var.getClass())) { return var; } if (Number.class.isAssignableFrom(var.getClass())) { return ((Number) var).floatValue(); } String input = var.toString(); Locale locale = interpreter.getConfig().getLocale(); NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); ParsePosition pp = new ParsePosition(0); float result; try { result = numberFormat.parse(input, pp).floatValue(); } catch (Exception e) { result = defaultVal; } if (pp.getErrorIndex() != -1 || pp.getIndex() != input.length()) { result = defaultVal; } return result; }
@Before public void setup() { config = JinjavaConfig.newBuilder().build(); }
public JinjavaEngine() { this(new JinjavaConfig()); }
@Override public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) { try (InterpreterScopeClosable c = interpreter.enterScope()) { String boolFlagStr = StringUtils.trim(tagNode.getHelpers()); boolean escapeFlag = BooleanUtils.toBoolean(StringUtils.isNotBlank(boolFlagStr) ? boolFlagStr : "true"); interpreter.getContext().setAutoEscape(escapeFlag); LengthLimitingStringBuilder result = new LengthLimitingStringBuilder(interpreter.getConfig().getMaxOutputSize()); for (Node child : tagNode.getChildren()) { result.append(child.render(interpreter)); } return result.toString(); } }
private static DateTimeFormatter getFormatter(JinjavaInterpreter interpreter, FormattedDate d) { if (!StringUtils.isBlank(d.getFormat())) { try { return StrftimeFormatter.formatter(d.getFormat(), interpreter.getConfig().getLocale()); } catch (IllegalArgumentException e) { interpreter.addError(new TemplateError(ErrorType.WARNING, ErrorReason.SYNTAX_ERROR, ErrorItem.OTHER, e.getMessage(), null, interpreter.getLineNumber(), -1, null, BasicTemplateErrorCategory.UNKNOWN_DATE, ImmutableMap.of("date", d.getDate().toString(), "exception", e.getMessage(), "lineNumber", String.valueOf(interpreter.getLineNumber())))); } } return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); }
public String getResource(String resource) throws IOException { return application.getResourceLocator().getString(resource, config.getCharset(), this); }
private JinjavaConfig trimBlocksConfig() { return JinjavaConfig.newBuilder().withTrimBlocks(true).build(); }
public JinjavaConfig build() { return new JinjavaConfig(charset, locale, timeZone, maxRenderDepth, disabled, trimBlocks, lstripBlocks, readOnlyResolver, enableRecursiveMacroCalls, failOnUnknownTokens, maxOutputSize, nestedInterpretationEnabled, randomNumberGeneratorStrategy, validationMode, maxStringLength); }
@Override public Object doEvaluate(Map<String, Object> argMap, Map<String, Object> kwargMap, List<Object> varArgs) { JinjavaInterpreter interpreter = JinjavaInterpreter.getCurrent(); try (InterpreterScopeClosable c = interpreter.enterScope()) { for (Map.Entry<String, Object> scopeEntry : localContextScope.getScope().entrySet()) { if (scopeEntry.getValue() instanceof MacroFunction) { interpreter.getContext().addGlobalMacro((MacroFunction) scopeEntry.getValue()); } else { interpreter.getContext().put(scopeEntry.getKey(), scopeEntry.getValue()); } } // named parameters for (Map.Entry<String, Object> argEntry : argMap.entrySet()) { interpreter.getContext().put(argEntry.getKey(), argEntry.getValue()); } // parameter map interpreter.getContext().put("kwargs", kwargMap); // varargs list interpreter.getContext().put("varargs", varArgs); LengthLimitingStringBuilder result = new LengthLimitingStringBuilder(interpreter.getConfig().getMaxOutputSize()); for (Node node : content) { result.append(node.render(interpreter)); } return result.toString(); } }
@Before public void setup() { config = JinjavaConfig.newBuilder().build(); }