com.hubspot.jinjava.interpret.Context Java Examples

The following examples show how to use com.hubspot.jinjava.interpret.Context. 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: DeferredValueUtils.java    From jinjava with Apache License 2.0 6 votes vote down vote up
public static HashMap<String, Object> getDeferredContextWithOriginalValues(
  Context context,
  Set<String> keysToKeep
) {
  HashMap<String, Object> deferredContext = new HashMap<>(context.size());
  context.forEach(
    (contextKey, contextItem) -> {
      if (keysToKeep.size() > 0 && !keysToKeep.contains(contextKey)) {
        return;
      }
      if (contextItem instanceof DeferredValue) {
        if (((DeferredValue) contextItem).getOriginalValue() != null) {
          deferredContext.put(
            contextKey,
            ((DeferredValue) contextItem).getOriginalValue()
          );
        }
      }
    }
  );
  return deferredContext;
}
 
Example #2
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itFindsGlobalProperties() {
  Context context = new Context();
  context.put("java_bean", getPopulatedJavaBean());

  context =
    getContext(
      Lists.newArrayList(getNodeForClass(TagNode.class, "{% if java_bean %}")),
      Optional.of(context)
    );

  Set<String> deferredProperties = DeferredValueUtils.findAndMarkDeferredProperties(
    context
  );

  assertThat(deferredProperties).contains("java_bean");
}
 
Example #3
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itDefersTheCompleteObjectWhenAtLeastOnePropertyIsUsed() {
  Context context = new Context();
  context.put("java_bean", getPopulatedJavaBean());

  context =
    getContext(
      Lists.newArrayList(
        getNodeForClass(
          TagNode.class,
          "{% if java_bean.property_one %}",
          Optional.empty(),
          Optional.empty()
        )
      ),
      Optional.of(context)
    );

  DeferredValueUtils.findAndMarkDeferredProperties(context);
  assertThat(context.containsKey("java_bean")).isTrue();
  assertThat(context.get("java_bean")).isInstanceOf(DeferredValue.class);
  DeferredValue deferredValue = (DeferredValue) context.get("java_bean");
  JavaBean originalValue = (JavaBean) deferredValue.getOriginalValue();
  assertThat(originalValue).hasFieldOrPropertyWithValue("propertyOne", "propertyOne");
  assertThat(originalValue).hasFieldOrPropertyWithValue("propertyTwo", "propertyTwo");
}
 
Example #4
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itHandlesCaseWhereValueIsNull() {
  Context context = getContext(
    Lists.newArrayList(
      getNodeForClass(
        TagNode.class,
        "{% if property.id %}",
        Optional.empty(),
        Optional.empty()
      )
    )
  );
  context.put("property", null);
  DeferredValueUtils.findAndMarkDeferredProperties(context);

  assertThat(context.get("property")).isNull();
}
 
Example #5
Source File: MacroFunctionMapper.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Override
public Method resolveFunction(String prefix, String localName) {
  final Context context = JinjavaInterpreter.getCurrent().getContext();
  MacroFunction macroFunction = context.getGlobalMacro(localName);

  if (macroFunction != null) {
    return AbstractCallableMethod.EVAL_METHOD;
  }

  final String functionName = buildFunctionName(prefix, localName);

  if (context.isFunctionDisabled(functionName)) {
    throw new DisabledException(functionName);
  }

  if (map.containsKey(functionName)) {
    context.addResolvedFunction(functionName);
  }

  return map.get(functionName);
}
 
Example #6
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Test
public void itPreservesNonDeferredProperties() {
  Context context = getContext(
    Lists.newArrayList(
      getNodeForClass(
        TagNode.class,
        "{% if deferred %}",
        Optional.empty(),
        Optional.empty()
      )
    )
  );
  context.put("deferred", "deferred");
  context.put("not_deferred", "test_value");

  DeferredValueUtils.findAndMarkDeferredProperties(context);
  assertThat(context.get("not_deferred")).isEqualTo("test_value");
}
 
Example #7
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 #8
Source File: MacroFunction.java    From jinjava with Apache License 2.0 6 votes vote down vote up
public MacroFunction(
  List<Node> content,
  String name,
  LinkedHashMap<String, Object> argNamesWithDefaults,
  boolean caller,
  Context localContextScope,
  int lineNumber,
  int startPosition
) {
  super(name, argNamesWithDefaults);
  this.content = content;
  this.caller = caller;
  this.localContextScope = localContextScope;
  this.definitionLineNumber = lineNumber;
  this.definitionStartPosition = startPosition;
  this.deferred = false;
}
 
Example #9
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 #10
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 #11
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 #12
Source File: Jinjava.java    From jinjava with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new jinjava processor instance with the specified global config
 *
 * @param globalConfig
 *          used for all render operations performed by this processor instance
 */
public Jinjava(JinjavaConfig globalConfig) {
  this.globalConfig = globalConfig;
  this.globalContext = new Context();

  Properties expConfig = new Properties();
  expConfig.setProperty(
    TreeBuilder.class.getName(),
    ExtendedSyntaxBuilder.class.getName()
  );

  TypeConverter converter = new TruthyTypeConverter();
  this.expressionFactory = new ExpressionFactoryImpl(expConfig, converter);

  this.resourceLocator = new ClasspathResourceLocator();
}
 
Example #13
Source File: KerberosUserMapper.java    From gcp-token-broker with Apache License 2.0 6 votes vote down vote up
@Override
public String map(String name) {
    Context context = new Context();
    KerberosName principal = new KerberosName(name);
    context.put("principal", principal.getFullName());
    context.put("primary", principal.getPrimary());
    context.put("instance", principal.getInstance());
    context.put("realm", principal.getRealm());
    // Look through the list of rules
    for (Rule rule : rulesList) {
        boolean isApplicable = rule.evaluateIfCondition(context);
        if (isApplicable) {
            // An applicable rule was found. Apply it to get the user mapping.
            return rule.evaluateThenExpression(context);
        }
    }
    throw new IllegalArgumentException("Principal `" + name + "` cannot be mapped to a Google identity.");
}
 
Example #14
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 #15
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private Context getContext(
  List<? extends Node> nodes,
  Optional<Context> initialContext
) {
  Context context = new Context();

  if (initialContext.isPresent()) {
    context = initialContext.get();
  }
  for (Node node : nodes) {
    context.handleDeferredNode(node);
  }
  return context;
}
 
Example #16
Source File: ExpressionNodeTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itRendersWithNestedExpressionInterpretationByDefault() throws Exception {
  final JinjavaConfig config = JinjavaConfig.newBuilder().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 world");
}
 
Example #17
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itIgnoresUnrestorableValuesFromDeferredContext() {
  Context context = new Context();
  context.put("simple_var", DeferredValue.instance());
  context.put("java_bean", DeferredValue.instance());

  HashMap<String, Object> result = DeferredValueUtils.getDeferredContextWithOriginalValues(
    context
  );
  assertThat(result).isEmpty();
}
 
Example #18
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itRestoresContextSuccessfully() {
  Context context = new Context();
  ImmutableMap<String, String> simpleMap = ImmutableMap.of("a", "x", "b", "y");
  ImmutableMap<String, Object> nestedMap = ImmutableMap.of("nested", simpleMap);
  Integer[] simpleArray = { 1, 2, 3, 4, 5, 6 };
  JavaBean javaBean = getPopulatedJavaBean();
  context.put("simple_var", DeferredValue.instance("SimpleVar"));
  context.put("java_bean", DeferredValue.instance(javaBean));
  context.put("simple_bool", DeferredValue.instance(true));
  context.put("simple_array", DeferredValue.instance(simpleArray));
  context.put("simple_map", DeferredValue.instance(simpleMap));
  context.put("nested_map", DeferredValue.instance(nestedMap));

  context.put("simple_var_undeferred", "SimpleVarUnDeferred");
  context.put("java_bean_undeferred", javaBean);
  context.put("nested_map_undeferred", nestedMap);

  HashMap<String, Object> result = DeferredValueUtils.getDeferredContextWithOriginalValues(
    context
  );
  assertThat(result).contains(entry("simple_var", "SimpleVar"));
  assertThat(result).contains(entry("java_bean", javaBean));
  assertThat(result).contains(entry("simple_bool", true));
  assertThat(result).contains(entry("simple_array", simpleArray));
  assertThat(result).contains(entry("simple_map", simpleMap));
  assertThat(result).contains(entry("nested_map", nestedMap));

  assertThat(result)
    .doesNotContain(entry("simple_var_undeferred", "SimpleVarUnDeferred"));
  assertThat(result).doesNotContain(entry("java_bean_undeferred", javaBean));
  assertThat(result).doesNotContain(entry("nested_map_undeferred", nestedMap));
}
 
Example #19
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itDefersWholePropertyOnDictAccess() {
  Context context = getContext(
    Lists.newArrayList(getNodeForClass(TagNode.class, "{{ dict['a'] }}"))
  );
  context.put("dict", Collections.singletonMap("a", "x"));

  Set<String> deferredProperties = DeferredValueUtils.findAndMarkDeferredProperties(
    context
  );
  assertThat(deferredProperties).contains("dict");
}
 
Example #20
Source File: DeferredValueUtilsTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itDefersWholePropertyOnArrayAccess() {
  Context context = getContext(
    Lists.newArrayList(getNodeForClass(TagNode.class, "{{ array[0] }}"))
  );
  context.put("array", Lists.newArrayList("a", "b", "c"));

  Set<String> deferredProperties = DeferredValueUtils.findAndMarkDeferredProperties(
    context
  );
  assertThat(deferredProperties).contains("array");
}
 
Example #21
Source File: ValidationModeTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
InstrumentedMacroFunction(
  List<Node> content,
  String name,
  LinkedHashMap<String, Object> argNamesWithDefaults,
  boolean caller,
  Context localContextScope
) {
  super(content, name, argNamesWithDefaults, caller, localContextScope, -1, -1);
}
 
Example #22
Source File: ExpressionNodeTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: ExpressionNodeTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@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: JinjavaConfig.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private JinjavaConfig(
  Charset charset,
  Locale locale,
  ZoneId timeZone,
  int maxRenderDepth,
  Map<Context.Library, Set<String>> disabled,
  boolean trimBlocks,
  boolean lstripBlocks,
  boolean enableRecursiveMacroCalls,
  int maxMacroRecursionDepth,
  boolean failOnUnknownTokens,
  long maxOutputSize,
  boolean nestedInterpretationEnabled,
  RandomNumberGeneratorStrategy randomNumberGenerator,
  boolean validationMode,
  long maxStringLength,
  InterpreterFactory interpreterFactory,
  TokenScannerSymbols tokenScannerSymbols,
  ELResolver elResolver
) {
  this.charset = charset;
  this.locale = locale;
  this.timeZone = timeZone;
  this.maxRenderDepth = maxRenderDepth;
  this.disabled = disabled;
  this.trimBlocks = trimBlocks;
  this.lstripBlocks = lstripBlocks;
  this.enableRecursiveMacroCalls = enableRecursiveMacroCalls;
  this.maxMacroRecursionDepth = maxMacroRecursionDepth;
  this.failOnUnknownTokens = failOnUnknownTokens;
  this.maxOutputSize = maxOutputSize;
  this.nestedInterpretationEnabled = nestedInterpretationEnabled;
  this.randomNumberGenerator = randomNumberGenerator;
  this.validationMode = validationMode;
  this.maxStringLength = maxStringLength;
  this.interpreterFactory = interpreterFactory;
  this.tokenScannerSymbols = tokenScannerSymbols;
  this.elResolver = elResolver;
}
 
Example #25
Source File: DeferredValueUtils.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private static void markDeferredProperties(Context context, Set<String> props) {
  props
    .stream()
    .filter(prop -> !(context.get(prop) instanceof DeferredValue))
    .forEach(
      prop -> {
        if (context.get(prop) != null) {
          context.put(prop, DeferredValue.instance(context.get(prop)));
        } else {
          //Handle set props
          context.put(prop, DeferredValue.instance());
        }
      }
    );
}
 
Example #26
Source File: DeferredValueUtils.java    From jinjava with Apache License 2.0 5 votes vote down vote up
public static Set<String> getPropertiesUsedInDeferredNodes(
  Context context,
  String templateSource
) {
  Set<String> propertiesUsed = findUsedProperties(templateSource);
  return propertiesUsed
    .stream()
    .map(prop -> prop.split("\\.", 2)[0]) // split accesses on .prop
    .filter(context::containsKey)
    .collect(Collectors.toSet());
}
 
Example #27
Source File: DeferredValueUtils.java    From jinjava with Apache License 2.0 5 votes vote down vote up
public static Set<String> findAndMarkDeferredProperties(Context context) {
  String templateSource = rebuildTemplateForNodes(context.getDeferredNodes());
  Set<String> deferredProps = getPropertiesUsedInDeferredNodes(context, templateSource);
  Set<String> setProps = getPropertiesSetInDeferredNodes(templateSource);

  markDeferredProperties(context, Sets.union(deferredProps, setProps));

  return deferredProps;
}
 
Example #28
Source File: Jinjava.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private Context copyGlobalContext() {
  Context context = new Context(null, globalContext);
  // copy registered.
  globalContext.getAllExpTests().forEach(context::registerExpTest);
  globalContext.getAllFilters().forEach(context::registerFilter);
  globalContext.getAllFunctions().forEach(context::registerFunction);
  globalContext.getAllTags().forEach(context::registerTag);
  return context;
}
 
Example #29
Source File: KerberosUserMapper.java    From gcp-token-broker with Apache License 2.0 4 votes vote down vote up
public boolean evaluateIfCondition(Context context) {
    JinjavaInterpreter interpreter = new JinjavaInterpreter(new Jinjava(), context, new JinjavaConfig());
    return ObjectTruthValue.evaluate(interpreter.resolveELExpression(ifCondition, 0));
}
 
Example #30
Source File: JinjavaConfig.java    From jinjava with Apache License 2.0 4 votes vote down vote up
public Builder withDisabled(Map<Context.Library, Set<String>> disabled) {
  this.disabled = disabled;
  return this;
}