com.hubspot.jinjava.Jinjava Java Examples
The following examples show how to use
com.hubspot.jinjava.Jinjava.
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: K8sRemoteInterpreterProcess.java From zeppelin with Apache License 2.0 | 7 votes |
@VisibleForTesting String sparkUiWebUrlFromTemplate(String templateString, int port, String serviceName, String serviceDomain) { ImmutableMap<String, Object> binding = ImmutableMap.of( "PORT", port, "SERVICE_NAME", serviceName, ENV_SERVICE_DOMAIN, serviceDomain ); ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); Jinjava jinja = new Jinjava(); return jinja.render(templateString, binding); } finally { Thread.currentThread().setContextClassLoader(oldCl); } }
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: 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 #4
Source File: AdvancedFilterTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void testUnorderedArgsAndKwargs() { jinjava = new Jinjava(); Object[] expectedArgs = new Object[] { "1", 2L }; Map<String, Object> expectedKwargs = new HashMap<String, Object>() { { put("named", "test"); } }; jinjava .getGlobalContext() .registerFilter(new MyMirrorFilter(expectedArgs, expectedKwargs)); assertThat( jinjava.render("{{ 'test'|mirror('1', named='test', 2) }}", new HashMap<>()) ) .isEqualTo("test"); }
Example #5
Source File: UpdateIntelliJSdksTaskTest.java From curiostack with MIT License | 6 votes |
private String testTemplate(String path) { String template = resource(path); Jinjava jinjava = new Jinjava(); return jinjava.render( template, ImmutableMap.<String, Object>builder() .put("gradleHome", testGradleHome.toAbsolutePath().toString().replace('\\', '/')) .put("jdkFolder", "jdk-zulu13.28.11-ca-jdk13.0.1") .put("javaVersion", "zulu13.28.11-ca-jdk13.0.1") .put( "jdk8Folder", "zulu8.42.0.21-ca-jdk8.0.232/zulu8.42.0.21-ca-jdk8.0.232-" + suffix()) .put("java8Version", "zulu8.42.0.21-ca-jdk8.0.232") .put("goVersion", ToolDependencies.getDefaultVersion("golang")) .build()); }
Example #6
Source File: AdvancedFilterTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void testOnlyKwargs() { jinjava = new Jinjava(); Object[] expectedArgs = new Object[] {}; Map<String, Object> expectedKwargs = new HashMap<String, Object>() { { put("named10", "str"); put("named2", 3L); put("namedB", true); } }; jinjava .getGlobalContext() .registerFilter(new MyMirrorFilter(expectedArgs, expectedKwargs)); assertThat( jinjava.render( "{{ 'test'|mirror(named2=3, named10='str', namedB=true) }}", new HashMap<>() ) ) .isEqualTo("test"); }
Example #7
Source File: SubmarineUI.java From zeppelin with Apache License 2.0 | 6 votes |
public void createUsageUI() { try { List<CommandlineOption> commandlineOptions = getCommandlineOptions(); HashMap<String, Object> mapParams = new HashMap(); mapParams.put(unifyKey(SubmarineConstants.PARAGRAPH_ID), intpContext.getParagraphId()); mapParams.put(SubmarineConstants.COMMANDLINE_OPTIONS, commandlineOptions); URL urlTemplate = Resources.getResource(SUBMARINE_USAGE_JINJA); String template = Resources.toString(urlTemplate, Charsets.UTF_8); Jinjava jinjava = new Jinjava(); String submarineUsage = jinjava.render(template, mapParams); InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(0); outputUI.clear(); outputUI.write(submarineUsage); outputUI.flush(); // UI update, log needs to be cleaned at the same time InterpreterResultMessageOutput outputLOG = intpContext.out.getOutputAt(1); outputLOG.clear(); outputLOG.flush(); } catch (IOException e) { LOGGER.error("Can't print usage", e); } }
Example #8
Source File: SubmarineUI.java From zeppelin with Apache License 2.0 | 6 votes |
public void createLogHeadUI() { try { HashMap<String, Object> mapParams = new HashMap(); URL urlTemplate = Resources.getResource(SUBMARINE_LOG_HEAD_JINJA); String template = Resources.toString(urlTemplate, Charsets.UTF_8); Jinjava jinjava = new Jinjava(); String submarineUsage = jinjava.render(template, mapParams); InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(1); outputUI.clear(); outputUI.write(submarineUsage); outputUI.flush(); } catch (IOException e) { LOGGER.error("Can't print usage", e); } }
Example #9
Source File: SubmarineUI.java From zeppelin with Apache License 2.0 | 6 votes |
public void printCommnadUI(SubmarineCommand submarineCmd) { try { HashMap<String, Object> mapParams = new HashMap(); mapParams.put(unifyKey(SubmarineConstants.PARAGRAPH_ID), intpContext.getParagraphId()); URL urlTemplate = Resources.getResource(SUBMARINE_DASHBOARD_JINJA); String template = Resources.toString(urlTemplate, Charsets.UTF_8); Jinjava jinjava = new Jinjava(); String submarineUsage = jinjava.render(template, mapParams); InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(0); outputUI.clear(); outputUI.write(submarineUsage); outputUI.flush(); // UI update, log needs to be cleaned at the same time InterpreterResultMessageOutput outputLOG = intpContext.out.getOutputAt(1); outputLOG.clear(); outputLOG.flush(); } catch (IOException e) { LOGGER.error("Can't print usage", e); } }
Example #10
Source File: JinjavaInterpreterTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itLimitsOutputSizeWhenSumOfNodeSizesExceedsMax() { JinjavaConfig outputSizeLimitedConfig = JinjavaConfig .newBuilder() .withMaxOutputSize(19) .build(); String input = "1234567890{% block testchild %}1234567890{% endblock %}"; String output = "12345678901234567890"; // Note that this exceeds the max size RenderResult renderResult = new Jinjava().renderForResult(input, new HashMap<>()); assertThat(renderResult.getOutput()).isEqualTo(output); assertThat(renderResult.hasErrors()).isFalse(); renderResult = new Jinjava(outputSizeLimitedConfig).renderForResult(input, new HashMap<>()); assertThat(renderResult.hasErrors()).isTrue(); assertThat(renderResult.getErrors().get(0).getMessage()) .contains("OutputTooBigException"); }
Example #11
Source File: FileLocatorTest.java From jinjava with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { interpreter = new Jinjava().newInterpreter(); locatorWorkingDir = new FileLocator(); File tmpDir = java .nio.file.Files.createTempDirectory(getClass().getSimpleName()) .toFile(); locatorTmpDir = new FileLocator(tmpDir); first = new File(tmpDir, "foo/first.jinja"); second = new File("target/loader-test-data/second.jinja"); first.getParentFile().mkdirs(); second.getParentFile().mkdirs(); Files.write("first", first, StandardCharsets.UTF_8); Files.write("second", second, StandardCharsets.UTF_8); }
Example #12
Source File: ImportTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itDoesNotRenderTagsDependingOnDeferredGlobalImport() { try { Jinjava jinjava = new Jinjava(); interpreter = new JinjavaInterpreter(jinjava, context, jinjava.getGlobalConfig()); interpreter.getContext().put("primary_font_size_num", DeferredValue.instance()); String renderedImport = fixture("import-property"); assertThat(renderedImport) .isEqualTo( Resources.toString( Resources.getResource("tags/macrotag/import-property.jinja"), StandardCharsets.UTF_8 ) ); } catch (IOException e) { throw new RuntimeException(); } }
Example #13
Source File: MacroTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAllowsMacroRecursionWithMaxDepth() throws IOException { interpreter = new Jinjava( JinjavaConfig .newBuilder() .withEnableRecursiveMacroCalls(true) .withMaxMacroRecursionDepth(10) .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 #14
Source File: MacroTagTest.java From jinjava with Apache License 2.0 | 6 votes |
@Test public void itAllowsMacroRecursionWhenEnabledInConfiguration() throws IOException { // I need a different configuration here therefore interpreter = new Jinjava(JinjavaConfig.newBuilder().withEnableRecursiveMacroCalls(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 { // and I need to cleanup my mess... JinjavaInterpreter.popCurrent(); } }
Example #15
Source File: SelectAttrFilterTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { jinjava = new Jinjava(); jinjava .getGlobalContext() .put( "users", Lists.newArrayList( new User(0, false, "[email protected]", new Option(0, "option0")), new User(1, true, "[email protected]", new Option(1, "option1")), new User(2, false, null, new Option(2, "option2")) ) ); }
Example #16
Source File: PropertiesGenerator.java From vault-crd with Apache License 2.0 | 5 votes |
private Map<String, String> renderFiles(Map<String, Object> context, Map<String, String> files) throws FatalTemplateErrorsException { Jinjava jinjava = new Jinjava(); Map<String, String> targetFiles = new HashMap<>(); files.forEach((key, value) -> { String renderedContent = jinjava.render(value, context); targetFiles.put(key, Base64.getEncoder().encodeToString(renderedContent.getBytes())); }); return targetFiles; }
Example #17
Source File: TagTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { jinjava = new Jinjava(); bindings = new HashMap<>(); bindings.put("var1", new Integer[] { 23, 45, 45, 689 }); bindings.put("var2", "45"); bindings.put("var3", 12); bindings.put("var5", ""); }
Example #18
Source File: RejectAttrFilterTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { jinjava = new Jinjava(); jinjava .getGlobalContext() .put( "users", Lists.newArrayList( new User(0, false, "[email protected]", new Option(0, "option0")), new User(1, true, "[email protected]", new Option(1, "option1")), new User(2, false, null, new Option(2, "option2")) ) ); }
Example #19
Source File: MacroTagTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { interpreter = new Jinjava().newInterpreter(); JinjavaInterpreter.pushCurrent(interpreter); context = interpreter.getContext(); }
Example #20
Source File: JinjavaInterpreter.java From jinjava with Apache License 2.0 | 5 votes |
public JinjavaInterpreter( Jinjava application, Context context, JinjavaConfig renderConfig ) { this.context = context; this.config = renderConfig; this.application = application; switch (config.getRandomNumberGeneratorStrategy()) { case THREAD_LOCAL: random = ThreadLocalRandom.current(); break; case CONSTANT_ZERO: random = new ConstantZeroRandomNumberGenerator(); break; case DEFERRED: random = new DeferredRandomNumberGenerator(); break; default: throw new IllegalStateException( "No random number generator with strategy " + config.getRandomNumberGeneratorStrategy() ); } this.expressionResolver = new ExpressionResolver(this, application.getExpressionFactory()); }
Example #21
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@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 #22
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itFailsOnUnknownTokensVariables() throws Exception { final JinjavaConfig config = JinjavaConfig .newBuilder() .withFailOnUnknownTokens(true) .build(); JinjavaInterpreter jinjavaInterpreter = new Jinjava(config).newInterpreter(); String jinja = "{{ UnknownToken }}"; Node node = new TreeParser(jinjavaInterpreter, jinja).buildTree(); assertThatThrownBy(() -> jinjavaInterpreter.render(node)) .isInstanceOf(UnknownTokenException.class) .hasMessage("Unknown token found: UnknownToken"); }
Example #23
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 #24
Source File: ExpressionNodeTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itFailsOnUnknownTokensWithFilter() throws Exception { final JinjavaConfig config = JinjavaConfig .newBuilder() .withFailOnUnknownTokens(true) .build(); JinjavaInterpreter jinjavaInterpreter = new Jinjava(config).newInterpreter(); String jinja = "{{ UnknownToken }}"; Node node = new TreeParser(jinjavaInterpreter, jinja).buildTree(); assertThatThrownBy(() -> jinjavaInterpreter.render(node)) .isInstanceOf(UnknownTokenException.class) .hasMessage("Unknown token found: UnknownToken"); }
Example #25
Source File: TreeParserTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void trimAndLstripBlocks() { interpreter = new Jinjava( JinjavaConfig.newBuilder().withLstripBlocks(true).withTrimBlocks(true).build() ) .newInterpreter(); assertThat(interpreter.render(parse("parse/tokenizer/whitespace-tags.jinja"))) .isEqualTo("<div>\n" + " yay\n" + "</div>\n"); }
Example #26
Source File: CustomTokenScannerSymbolsTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { config = JinjavaConfig.newBuilder().withTokenScannerSymbols(new CustomTokens()).build(); jinjava = new Jinjava(config); jinjava.getGlobalContext().put("numbers", Lists.newArrayList(1L, 2L, 3L, 4L, 5L)); }
Example #27
Source File: FailOnUnknownTokensTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setUp() { JinjavaConfig.Builder builder = JinjavaConfig.newBuilder(); builder.withFailOnUnknownTokens(true); JinjavaConfig config = builder.build(); jinjava = new Jinjava(config); }
Example #28
Source File: JoinFilterTest.java From jinjava with Apache License 2.0 | 5 votes |
@Before public void setup() { jinjava = new Jinjava(); jinjava .getGlobalContext() .put("users", Lists.newArrayList(new User("foo"), new User("bar"))); }
Example #29
Source File: IncludeTagTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itIncludesFileViaRelativePath() throws IOException { jinjava = new Jinjava(); jinjava.setResourceLocator( new ResourceLocator() { private RelativePathResolver relativePathResolver = new RelativePathResolver(); @Override public String getString( String fullName, Charset encoding, JinjavaInterpreter interpreter ) throws IOException { return Resources.toString( Resources.getResource(String.format("%s", fullName)), StandardCharsets.UTF_8 ); } @Override public Optional<LocationResolver> getLocationResolver() { return Optional.of(relativePathResolver); } } ); jinjava .getGlobalContext() .put(CURRENT_PATH_CONTEXT_KEY, "tags/includetag/includes-relative-path.jinja"); RenderResult result = jinjava.renderForResult( Resources.toString( Resources.getResource("tags/includetag/includes-relative-path.jinja"), StandardCharsets.UTF_8 ), new HashMap<>() ); assertThat(result.getOutput().trim()).isEqualTo("INCLUDED"); }
Example #30
Source File: TemplateErrorTest.java From jinjava with Apache License 2.0 | 5 votes |
@Test public void itSetsFieldNameCaseForSyntaxErrorInFor() { RenderResult renderResult = new Jinjava() .renderForResult("{% for item inna navigation %}{% endfor %}", ImmutableMap.of()); assertThat(renderResult.getErrors().get(0).getFieldName()) .isEqualTo("item inna navigation"); }