com.hubspot.jinjava.interpret.JinjavaInterpreter Java Examples
The following examples show how to use
com.hubspot.jinjava.interpret.JinjavaInterpreter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OutputList.java From jinjava with Apache License 2.0 | 6 votes |
public String getValue() { LengthLimitingStringBuilder val = new LengthLimitingStringBuilder(maxOutputSize); for (OutputNode node : nodes) { try { val.append(node.getValue()); } catch (OutputTooBigException e) { JinjavaInterpreter .getCurrent() .addError(TemplateError.fromOutputTooBigException(e)); return val.toString(); } } return val.toString(); }
Example #2
Source File: ImportTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAddsAllDeferredNodesOfGlobalImport() { Jinjava jinjava = new Jinjava(); interpreter = new JinjavaInterpreter(jinjava, context, jinjava.getGlobalConfig()); interpreter.getContext().put("primary_font_size_num", DeferredValue.instance()); fixture("import-property-global"); Set<String> deferredImages = interpreter .getContext() .getDeferredNodes() .stream() .map(Node::reconstructImage) .collect(Collectors.toSet()); assertThat( deferredImages .stream() .filter(image -> image.contains("{% set primary_line_height")) .collect(Collectors.toSet()) ) .isNotEmpty(); }
Example #3
Source File: ExpressionResolverTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itBlocksDisabledExpTests() { Map<Context.Library, Set<String>> disabled = ImmutableMap.of( Context.Library.EXP_TEST, ImmutableSet.of("even") ); assertThat(interpreter.render("{% if 2 is even %}yes{% endif %}")).isEqualTo("yes"); try ( JinjavaInterpreter.InterpreterScopeClosable c = interpreter.enterScope(disabled) ) { interpreter.render("{% if 2 is even %}yes{% endif %}"); TemplateError e = interpreter.getErrorsCopy().get(0); assertThat(e.getItem()).isEqualTo(ErrorItem.EXPRESSION_TEST); assertThat(e.getReason()).isEqualTo(ErrorReason.DISABLED); assertThat(e.getMessage()).contains("even' is disabled in this context"); } }
Example #4
Source File: DivisibleFilter.java From jinjava with Apache License 2.0 | 6 votes |
@Override public Object filter(Object object, JinjavaInterpreter interpreter, String... arg) { if (object == null) { return false; } if (object instanceof Number) { if (arg.length < 1) { throw new TemplateSyntaxException( interpreter, getName(), "requires 1 argument (number to divide by)" ); } long factor = Long.parseLong(arg[0]); long value = ((Number) object).longValue(); if (value % factor == 0) { return true; } } return false; }
Example #5
Source File: ImportTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAvoidsNestedImportCycle() throws IOException { Jinjava jinjava = new Jinjava(); interpreter = new JinjavaInterpreter(jinjava, context, jinjava.getGlobalConfig()); interpreter.render( Resources.toString( Resources.getResource("tags/importtag/a-imports-b.jinja"), StandardCharsets.UTF_8 ) ); assertThat(context.get("a")).isEqualTo("foo"); assertThat(context.get("b")).isEqualTo("bar"); assertThat(interpreter.getErrorsCopy().get(0).getMessage()) .contains("Import cycle detected", "b-imports-a.jinja"); }
Example #6
Source File: DictSortFilter.java From jinjava with Apache License 2.0 | 6 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { if (var == null || !Map.class.isAssignableFrom(var.getClass())) { return var; } boolean caseSensitive = false; if (args.length > 0) { caseSensitive = BooleanUtils.toBoolean(args[0]); } boolean sortByKey = true; if (args.length > 1) { sortByKey = "value".equalsIgnoreCase(args[1]); } @SuppressWarnings("unchecked") Map<String, Object> dict = (Map<String, Object>) var; List<Map.Entry<String, Object>> sorted = Lists.newArrayList(dict.entrySet()); sorted.sort(new MapEntryComparator(caseSensitive, sortByKey)); return sorted; }
Example #7
Source File: IpAddrFilter.java From jinjava with Apache License 2.0 | 6 votes |
private String filterItem( JinjavaInterpreter interpreter, String parameter, Object item ) { Object value; try { value = getValue(interpreter, item, parameter); } catch (InvalidArgumentException exception) { return null; } if (value instanceof String || value instanceof Integer) { return String.valueOf(value); } if (value instanceof Boolean && (Boolean) value) { return (String) item; } return null; }
Example #8
Source File: ImportTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAddsAllDeferredNodesOfImport() { Jinjava jinjava = new Jinjava(); interpreter = new JinjavaInterpreter(jinjava, context, jinjava.getGlobalConfig()); interpreter.getContext().put("primary_font_size_num", DeferredValue.instance()); fixture("import-property"); Set<String> deferredImages = interpreter .getContext() .getDeferredNodes() .stream() .map(Node::reconstructImage) .collect(Collectors.toSet()); assertThat( deferredImages .stream() .filter(image -> image.contains("{% set primary_line_height")) .collect(Collectors.toSet()) ) .isNotEmpty(); }
Example #9
Source File: IndentFilter.java From jinjava with Apache License 2.0 | 6 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { int width = 4; if (args.length > 0) { width = NumberUtils.toInt(args[0], 4); } boolean indentFirst = false; if (args.length > 1) { indentFirst = BooleanUtils.toBoolean(args[1]); } List<String> indentedLines = new ArrayList<>(); for (String line : NEWLINE_SPLITTER.split(Objects.toString(var, ""))) { int thisWidth = indentedLines.size() == 0 && !indentFirst ? 0 : width; indentedLines.add(StringUtils.repeat(' ', thisWidth) + line); } return NEWLINE_JOINER.join(indentedLines); }
Example #10
Source File: SortFilter.java From jinjava with Apache License 2.0 | 6 votes |
private Object mapObject( JinjavaInterpreter interpreter, Object o, List<String> propertyChain ) { if (o == null) { throw new InvalidInputException(interpreter, this, InvalidReason.NULL_IN_LIST); } if (propertyChain.isEmpty()) { return o; } Object result = interpreter.resolveProperty(o, propertyChain); if (result == null) { throw new InvalidArgumentException( interpreter, this, InvalidReason.NULL_ATTRIBUTE_IN_LIST, 2, DOT_JOINER.join(propertyChain) ); } return result; }
Example #11
Source File: UniqueFilter.java From jinjava with Apache License 2.0 | 6 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { Map<Object, Object> result = new LinkedHashMap<>(); String attr = null; if (args.length > 0) { attr = args[0]; } ForLoop loop = ObjectIterator.getLoop(var); while (loop.hasNext()) { Object val = loop.next(); Object key = val; if (attr != null) { key = interpreter.resolveProperty(val, attr); } if (!result.containsKey(key)) { result.put(key, val); } } return result.values(); }
Example #12
Source File: RelativePathResolver.java From jinjava with Apache License 2.0 | 6 votes |
@Override public String resolve(String path, JinjavaInterpreter interpreter) { if (path.startsWith("./") || path.startsWith("../")) { String parentPath = interpreter .getContext() .getCurrentPathStack() .peek() .orElseGet( () -> (String) interpreter.getContext().getOrDefault(CURRENT_PATH_CONTEXT_KEY, "") ); Path templatePath = Paths.get(parentPath); Path folderPath = templatePath.getParent() != null ? templatePath.getParent() : Paths.get(""); if (folderPath != null) { return folderPath.resolve(path).normalize().toString(); } } return path; }
Example #13
Source File: IpAddrFilter.java From jinjava with Apache License 2.0 | 6 votes |
private Object getMapOfFilteredItems( JinjavaInterpreter interpreter, String parameter, Object map ) { Iterator<Map.Entry<Object, Object>> iterator = ((Map) map).entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Object, Object> item = iterator.next(); String filteredItem = filterItem(interpreter, parameter, item.getValue()); if (filteredItem != null) { item.setValue(filteredItem); } else { iterator.remove(); } } return map; }
Example #14
Source File: ValidationModeTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itDoesNotExecuteFiltersInValidatedBlocks() { assertThat(validationFilter.getExecutionCount()).isEqualTo(0); String template = "{{ 10|validation_filter() }}" + "{% if false %}" + " {{ 10|validation_filter() }}" + " {{ hey( }}" + "{% endif %}"; String result = interpreter.render(template).trim(); assertThat(interpreter.getErrors()).isEmpty(); assertThat(result).isEqualTo("10"); assertThat(validationFilter.getExecutionCount()).isEqualTo(1); JinjavaInterpreter.pushCurrent(validatingInterpreter); result = validatingInterpreter.render(template).trim(); assertThat(validatingInterpreter.getErrors().size()).isEqualTo(1); assertThat(validatingInterpreter.getErrors().get(0).getMessage()).contains("hey("); assertThat(result).isEqualTo("10"); assertThat(validationFilter.getExecutionCount()).isEqualTo(2); }
Example #15
Source File: MacroTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAllowsMacroRecursionWithMaxDepthInValidationMode() throws IOException { interpreter = new Jinjava( JinjavaConfig .newBuilder() .withEnableRecursiveMacroCalls(true) .withMaxMacroRecursionDepth(10) .withValidationMode(true) .build() ) .newInterpreter(); JinjavaInterpreter.pushCurrent(interpreter); try { String template = fixtureText("ending-recursion"); String out = interpreter.render(template); assertThat(interpreter.getErrorsCopy()).isEmpty(); assertThat(out).contains("Hello Hello Hello Hello Hello"); } finally { JinjavaInterpreter.popCurrent(); } }
Example #16
Source File: Filter.java From jinjava with Apache License 2.0 | 5 votes |
default Object filter(SafeString var, JinjavaInterpreter interpreter, String... args) { if (var == null) { return filter((Object) null, interpreter, args); } Object filteredValue = filter(var.toString(), interpreter, args); if (preserveSafeString() && filteredValue instanceof String) { return new SafeString(filteredValue.toString()); } return filteredValue; }
Example #17
Source File: AdvancedFilterTest.java From jinjava with Apache License 2.0 | 5 votes |
@Override public Object filter( Object var, JinjavaInterpreter interpreter, Object[] args, Map<String, Object> kwargs ) { if (!Arrays.equals(expectedArgs, args)) { throw new RuntimeException( "Args are different than expected: " + Arrays.toString(args) + " to " + Arrays.toString(expectedArgs) ); } if (!expectedKwargs.equals(kwargs)) { throw new RuntimeException( "Kwargs are different than expected: " + Arrays.toString(kwargs.entrySet().toArray()) + " to " + Arrays.toString(expectedKwargs.entrySet().toArray()) ); } return var; }
Example #18
Source File: ReplaceFilter.java From jinjava with Apache License 2.0 | 5 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { if (var == null) { return null; } if (args.length < 2) { throw new TemplateSyntaxException( interpreter, getName(), "requires 2 arguments (substring to replace, replacement string) or 3 arguments (substring to replace, replacement string, number of occurrences to replace)" ); } String s = (String) var; String toReplace = args[0]; String replaceWith = args[1]; Integer count = null; if (args.length > 2) { count = NumberUtils.createInteger(args[2]); } if (count == null) { return StringUtils.replace(s, toReplace, replaceWith); } else { return StringUtils.replace(s, toReplace, replaceWith, count); } }
Example #19
Source File: IntFilter.java From jinjava with Apache License 2.0 | 5 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { Long defaultVal = 0L; if (args.length > 0) { defaultVal = NumberUtils.toLong(args[0], 0); } if (var == null) { return convertResult(defaultVal); } if (Number.class.isAssignableFrom(var.getClass())) { return convertResult(((Number) var).longValue()); } String input = var.toString().trim(); Locale locale = interpreter.getConfig().getLocale(); NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); ParsePosition pp = new ParsePosition(0); Long result; try { result = numberFormat.parse(input, pp).longValue(); } catch (Exception e) { result = defaultVal; } if (pp.getErrorIndex() != -1 || pp.getIndex() != input.length()) { result = defaultVal; } return convertResult(result); }
Example #20
Source File: LogFilter.java From jinjava with Apache License 2.0 | 5 votes |
private double calculateLog(JinjavaInterpreter interpreter, double num, Double base) { checkArguments(interpreter, num, base); if (base == null) { return Math.log(num); } return BigDecimalMath .log(new BigDecimal(num), PRECISION) .divide(BigDecimalMath.log(new BigDecimal(base), PRECISION), RoundingMode.HALF_EVEN) .doubleValue(); }
Example #21
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itFailsOnUnknownTokensOfIf() throws Exception { final JinjavaConfig config = JinjavaConfig .newBuilder() .withFailOnUnknownTokens(true) .build(); JinjavaInterpreter jinjavaInterpreter = new Jinjava(config).newInterpreter(); String jinja = "{% if bad %} BAD {% endif %}"; Node node = new TreeParser(jinjavaInterpreter, jinja).buildTree(); assertThatThrownBy(() -> jinjavaInterpreter.render(node)) .isInstanceOf(UnknownTokenException.class) .hasMessageContaining("Unknown token found: bad"); }
Example #22
Source File: KerberosUserMapper.java From gcp-token-broker with Apache License 2.0 | 5 votes |
private static void checkForSyntaxErrors(JinjavaInterpreter interpreter, String expression) { List<TemplateError> errors = interpreter.getErrors(); if (errors.size() > 0) { StringBuilder message = new StringBuilder(); for (TemplateError error: errors) { message.append(error.getMessage()); } throw new IllegalArgumentException(String.format("Invalid expression: %s\n%s", expression, message)); } }
Example #23
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itRendersResultWithoutNestedExpressionInterpretation() throws Exception { final JinjavaConfig config = JinjavaConfig .newBuilder() .withNestedInterpretationEnabled(false) .build(); JinjavaInterpreter noNestedInterpreter = new Jinjava(config).newInterpreter(); Context contextNoNestedInterpretation = noNestedInterpreter.getContext(); contextNoNestedInterpretation.put("myvar", "hello {{ place }}"); contextNoNestedInterpretation.put("place", "world"); ExpressionNode node = fixture("simplevar"); assertThat(node.render(noNestedInterpreter).toString()) .isEqualTo("hello {{ place }}"); }
Example #24
Source File: IfTagTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { jinjava = new Jinjava(); interpreter = jinjava.newInterpreter(); context = interpreter.getContext(); JinjavaInterpreter.pushCurrent(interpreter); }
Example #25
Source File: IsIterableExpTest.java From jinjava with Apache License 2.0 | 5 votes |
@Override public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) { return ( var != null && (var.getClass().isArray() || Iterable.class.isAssignableFrom(var.getClass())) ); }
Example #26
Source File: Variable.java From jinjava with Apache License 2.0 | 5 votes |
public Variable(JinjavaInterpreter interpreter, String variable) { this.interpreter = interpreter; if (variable.indexOf('.') == -1) { name = variable; chainList = Collections.emptyList(); } else { List<String> parts = Lists.newArrayList(DOT_SPLITTER.split(variable)); name = parts.get(0); chainList = parts.subList(1, parts.size()); } }
Example #27
Source File: JinjavaInterpreterResolver.java From jinjava with Apache License 2.0 | 5 votes |
private static String formattedDateToString( JinjavaInterpreter interpreter, FormattedDate d ) { DateTimeFormatter formatter = getFormatter(interpreter, d) .withLocale(getLocale(interpreter, d)); return formatter.format(localizeDateTime(interpreter, d.getDate())); }
Example #28
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itRendersNestedTags() throws Exception { final JinjavaConfig config = JinjavaConfig.newBuilder().build(); JinjavaInterpreter jinjava = new Jinjava(config).newInterpreter(); Context context = jinjava.getContext(); context.put("myvar", "hello {% if (true) %}nasty{% endif %}"); ExpressionNode node = fixture("simplevar"); assertThat(node.render(jinjava).toString()).isEqualTo("hello nasty"); }
Example #29
Source File: IsLowerExpTest.java From jinjava with Apache License 2.0 | 5 votes |
@Override public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) { if (var == null || !(var instanceof String)) { return false; } return StringUtils.isAllLowerCase((String) var); }
Example #30
Source File: LastFilter.java From jinjava with Apache License 2.0 | 5 votes |
@Override public Object filter(Object var, JinjavaInterpreter interpreter, String... args) { ForLoop loop = ObjectIterator.getLoop(var); Object last = null; while (loop.hasNext()) { last = loop.next(); } return last; }