com.hubspot.jinjava.interpret.TemplateError Java Examples

The following examples show how to use com.hubspot.jinjava.interpret.TemplateError. 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: Jinjava.java    From jinjava with Apache License 2.0 6 votes vote down vote up
/**
 * Render the given template using the given context bindings.
 *
 * @param template
 *          jinja source template
 * @param bindings
 *          map of objects to put into scope for this rendering action
 * @return the rendered template
 * @throws InterpretException
 *           if any syntax errors were encountered during rendering
 */
public String render(String template, Map<String, ?> bindings) {
  RenderResult result = renderForResult(template, bindings);

  List<TemplateError> fatalErrors = result
    .getErrors()
    .stream()
    .filter(error -> error.getSeverity() == ErrorType.FATAL)
    .collect(Collectors.toList());

  if (!fatalErrors.isEmpty()) {
    throw new FatalTemplateErrorsException(template, fatalErrors);
  }

  return result.getOutput();
}
 
Example #2
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: OutputList.java    From jinjava with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itBlocksDisabledFunctions() {
  Map<Context.Library, Set<String>> disabled = ImmutableMap.of(
    Library.FUNCTION,
    ImmutableSet.of(":range")
  );

  String template = "hi {% for i in range(1, 3) %}{{i}} {% endfor %}";

  String rendered = jinjava.render(template, context);
  assertEquals("hi 1 2 ", rendered);

  final JinjavaConfig config = JinjavaConfig
    .newBuilder()
    .withDisabled(disabled)
    .build();

  final RenderResult renderResult = jinjava.renderForResult(template, context, config);
  assertEquals("hi ", renderResult.getOutput());
  TemplateError e = renderResult.getErrors().get(0);
  assertThat(e.getItem()).isEqualTo(ErrorItem.FUNCTION);
  assertThat(e.getReason()).isEqualTo(ErrorReason.DISABLED);
  assertThat(e.getMessage()).contains("':range' is disabled in this context");
}
 
Example #5
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itBlocksDisabledFilters() {
  Map<Context.Library, Set<String>> disabled = ImmutableMap.of(
    Context.Library.FILTER,
    ImmutableSet.of("truncate")
  );
  assertThat(interpreter.resolveELExpression("\"hey\"|truncate(2)", -1))
    .isEqualTo("h...");

  try (
    JinjavaInterpreter.InterpreterScopeClosable c = interpreter.enterScope(disabled)
  ) {
    interpreter.resolveELExpression("\"hey\"|truncate(2)", -1);
    TemplateError e = interpreter.getErrorsCopy().get(0);
    assertThat(e.getItem()).isEqualTo(ErrorItem.FILTER);
    assertThat(e.getReason()).isEqualTo(ErrorReason.DISABLED);
    assertThat(e.getMessage()).contains("truncate' is disabled in this context");
  }
}
 
Example #6
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itBlocksDisabledTagsInIncludes() {
  final String jinja = "top {% include \"tags/includetag/raw.html\" %}";

  Map<Context.Library, Set<String>> disabled = ImmutableMap.of(
    Context.Library.TAG,
    ImmutableSet.of("raw")
  );
  assertThat(interpreter.render(jinja)).isEqualTo("top before raw after\n");

  try (
    JinjavaInterpreter.InterpreterScopeClosable c = interpreter.enterScope(disabled)
  ) {
    interpreter.render(jinja);
  }
  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getItem()).isEqualTo(ErrorItem.TAG);
  assertThat(e.getReason()).isEqualTo(ErrorReason.DISABLED);
  assertThat(e.getMessage()).contains("'raw' is disabled in this context");
}
 
Example #7
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void unknownProperty() {
  interpreter.resolveELExpression("foo", 23);
  assertThat(interpreter.getErrorsCopy()).isEmpty();

  context.put("foo", new Object());
  interpreter.resolveELExpression("foo.bar", 23);

  assertThat(interpreter.getErrorsCopy()).hasSize(1);

  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getReason()).isEqualTo(ErrorReason.UNKNOWN);
  assertThat(e.getLineno()).isEqualTo(23);
  assertThat(e.getFieldName()).isEqualTo("bar");
  assertThat(e.getMessage()).contains("Cannot resolve property 'bar'");
}
 
Example #8
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itBlocksDisabledTags() {
  Map<Context.Library, Set<String>> disabled = ImmutableMap.of(
    Context.Library.TAG,
    ImmutableSet.of("raw")
  );
  assertThat(interpreter.render("{% raw %}foo{% endraw %}")).isEqualTo("foo");

  try (
    JinjavaInterpreter.InterpreterScopeClosable c = interpreter.enterScope(disabled)
  ) {
    interpreter.render("{% raw %} foo {% endraw %}");
  }

  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getItem()).isEqualTo(ErrorItem.TAG);
  assertThat(e.getReason()).isEqualTo(ErrorReason.DISABLED);
  assertThat(e.getMessage()).contains("'raw' is disabled in this context");
}
 
Example #9
Source File: CbJinjaTester.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void verifySingleSaltFile(Path path) throws IOException {
    String file = FileReaderUtils.readFileFromPath(path);
    Jinjava jinjava = new Jinjava();
    JinjavaInterpreter interpreter = jinjava.newInterpreter();
    interpreter.parse(file);
    List<TemplateError> errors = interpreter.getErrors();
    if (!errors.isEmpty()) {
        StringBuilder errorMsg = new StringBuilder();
        errorMsg.append("Jinja validation failed for sls file: " + path);
        errorMsg.append("\n");
        errors.forEach(error -> errorMsg.append(error));
        fail(errorMsg.toString());
    }
}
 
Example #10
Source File: KerberosUserMapper.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: FreeipaJinjaTester.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void verifySingleSaltFile(Path path) throws IOException {
    String file = FileReaderUtils.readFileFromPath(path);
    Jinjava jinjava = new Jinjava();
    JinjavaInterpreter interpreter = jinjava.newInterpreter();
    interpreter.parse(file);
    List<TemplateError> errors = interpreter.getErrors();
    if (!errors.isEmpty()) {
        StringBuilder errorMsg = new StringBuilder();
        errorMsg.append("Jinja validation failed for sls file: " + path);
        errorMsg.append("\n");
        errors.forEach(error -> errorMsg.append(error));
        fail(errorMsg.toString());
    }
}
 
Example #12
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itWillNotReturnClassObjects() {
  context.put("myobj", new MyClass(new Date(0)));
  interpreter.resolveELExpression("myobj.getClass()", -1);

  assertThat(interpreter.getErrorsCopy()).isNotEmpty();
  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getMessage()).contains("Cannot find method 'getClass'");
}
 
Example #13
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void blackListedMethods() {
  context.put("myobj", new MyClass(new Date(0)));
  interpreter.resolveELExpression("myobj.wait()", -1);

  assertThat(interpreter.getErrorsCopy()).isNotEmpty();
  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getMessage()).contains("Cannot find method 'wait'");
}
 
Example #14
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void blackListedProperties() {
  context.put("myobj", new MyClass(new Date(0)));
  interpreter.resolveELExpression("myobj.class.methods[0]", -1);

  assertThat(interpreter.getErrorsCopy()).isNotEmpty();
  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getReason()).isEqualTo(ErrorReason.UNKNOWN);
  assertThat(e.getFieldName()).isEqualTo("class");
  assertThat(e.getMessage()).contains("Cannot resolve property 'class'");
}
 
Example #15
Source File: ExpressionResolverTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void syntaxError() {
  interpreter.resolveELExpression("(*&W", 123);
  assertThat(interpreter.getErrorsCopy()).hasSize(1);

  TemplateError e = interpreter.getErrorsCopy().get(0);
  assertThat(e.getReason()).isEqualTo(ErrorReason.SYNTAX_ERROR);
  assertThat(e.getLineno()).isEqualTo(123);
  assertThat(e.getMessage()).contains("invalid character");
}
 
Example #16
Source File: JinjavaInterpreterResolver.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private static Locale getLocale(JinjavaInterpreter interpreter, FormattedDate d) {
  if (!StringUtils.isBlank(d.getLanguage())) {
    try {
      return LocaleUtils.toLocale(d.getLanguage());
    } catch (IllegalArgumentException e) {
      interpreter.addError(
        new TemplateError(
          ErrorType.WARNING,
          ErrorReason.SYNTAX_ERROR,
          ErrorItem.OTHER,
          e.getMessage(),
          null,
          interpreter.getLineNumber(),
          -1,
          null,
          BasicTemplateErrorCategory.UNKNOWN_LOCALE,
          ImmutableMap.of(
            "date",
            d.getDate().toString(),
            "exception",
            e.getMessage(),
            "lineNumber",
            String.valueOf(interpreter.getLineNumber())
          )
        )
      );
    }
  }

  return Locale.US;
}
 
Example #17
Source File: JinjavaInterpreterResolver.java    From jinjava with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #18
Source File: TreeParser.java    From jinjava with Apache License 2.0 5 votes vote down vote up
/**
 * @return null if EOF or error
 */

private Node nextNode() {
  Token token = scanner.next();

  if (token.getType() == symbols.getFixed()) {
    return text((TextToken) token);
  } else if (token.getType() == symbols.getExprStart()) {
    return expression((ExpressionToken) token);
  } else if (token.getType() == symbols.getTag()) {
    return tag((TagToken) token);
  } else if (token.getType() == symbols.getNote()) {
    String commentClosed = symbols.getClosingComment();
    if (!token.getImage().endsWith(commentClosed)) {
      interpreter.addError(
        new TemplateError(
          ErrorType.WARNING,
          ErrorReason.SYNTAX_ERROR,
          ErrorItem.TAG,
          "Unclosed comment",
          "comment",
          token.getLineNumber(),
          token.getStartPosition(),
          null
        )
      );
    }
  } else {
    interpreter.addError(
      TemplateError.fromException(
        new UnexpectedTokenException(
          token.getImage(),
          token.getLineNumber(),
          token.getStartPosition()
        )
      )
    );
  }
  return null;
}
 
Example #19
Source File: TreeParser.java    From jinjava with Apache License 2.0 5 votes vote down vote up
public Node buildTree() {
  Node root = new RootNode(symbols);

  parent = root;

  while (scanner.hasNext()) {
    Node node = nextNode();

    if (node != null) {
      parent.getChildren().add(node);
    }
  }

  do {
    if (parent != root) {
      interpreter.addError(
        TemplateError.fromException(
          new MissingEndTagException(
            ((TagNode) parent).getEndName(),
            parent.getMaster().getImage(),
            parent.getLineNumber(),
            parent.getStartPosition()
          )
        )
      );
      parent = parent.getParent();
    }
  } while (parent.getParent() != null);

  return root;
}
 
Example #20
Source File: JoinFilter.java    From jinjava with Apache License 2.0 4 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  LengthLimitingStringBuilder stringBuilder = new LengthLimitingStringBuilder(
    interpreter.getConfig().getMaxStringLength()
  );

  String separator = "";
  if (args.length > 0) {
    separator = args[0];
  }

  String attr = null;
  if (args.length > 1) {
    attr = args[1];
  }

  ForLoop loop = ObjectIterator.getLoop(var);
  boolean first = true;
  while (loop.hasNext()) {
    Object val = loop.next();

    if (attr != null) {
      val = interpreter.resolveProperty(val, attr);
    }

    try {
      if (!first) {
        stringBuilder.append(separator);
      } else {
        first = false;
      }
      stringBuilder.append(Objects.toString(val, ""));
    } catch (OutputTooBigException ex) {
      interpreter.addError(
        new TemplateError(
          ErrorType.WARNING,
          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(),
          interpreter.getPosition(),
          ex
        )
      );

      return stringBuilder.toString();
    }
  }

  return stringBuilder.toString();
}
 
Example #21
Source File: TreeParser.java    From jinjava with Apache License 2.0 4 votes vote down vote up
private void endTag(Tag tag, TagToken tagToken) {
  final Node lastSibling = getLastSibling();

  if (
    parent instanceof TagNode &&
    tagToken.isLeftTrim() &&
    lastSibling instanceof TextNode
  ) {
    lastSibling.getMaster().setRightTrim(true);
  }

  if (parent.getMaster() != null) { // root node
    parent.getMaster().setRightTrimAfterEnd(tagToken.isRightTrim());
  }

  boolean hasMatchingStartTag = false;
  while (!(parent instanceof RootNode)) {
    TagNode parentTag = (TagNode) parent;
    parent = parent.getParent();

    if (parentTag.getEndName().equals(tag.getEndTagName())) {
      hasMatchingStartTag = true;
      break;
    } else {
      interpreter.addError(
        TemplateError.fromException(
          new TemplateSyntaxException(
            tagToken.getImage(),
            "Mismatched end tag, expected: " + parentTag.getEndName(),
            tagToken.getLineNumber(),
            tagToken.getStartPosition()
          )
        )
      );
    }
  }
  if (!hasMatchingStartTag) {
    interpreter.addError(
      new TemplateError(
        ErrorType.WARNING,
        ErrorReason.SYNTAX_ERROR,
        ErrorItem.TAG,
        "Missing start tag",
        tag.getName(),
        tagToken.getLineNumber(),
        tagToken.getStartPosition(),
        null
      )
    );
  }
}