Search in sources :

Example 56 with VelocityContext

use of org.apache.velocity.VelocityContext in project xwiki-platform by xwiki.

the class DefaultWikiMacroTest method testDefaultParameterValues.

/**
 * Test default parameter value injection.
 */
@Test
public void testDefaultParameterValues() throws Exception {
    // Velocity Manager mock.
    final VelocityManager mockVelocityManager = getMockery().mock(VelocityManager.class);
    DefaultComponentDescriptor<VelocityManager> descriptorVM = new DefaultComponentDescriptor<VelocityManager>();
    descriptorVM.setRoleType(VelocityManager.class);
    getComponentManager().registerComponent(descriptorVM, mockVelocityManager);
    // Initialize velocity engine.
    final VelocityEngine vEngine = getComponentManager().getInstance(VelocityEngine.class);
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "file");
    vEngine.initialize(properties);
    // Hack into velocity context.
    Execution execution = getComponentManager().getInstance(Execution.class);
    Map<?, ?> xwikiContext = (Map<?, ?>) execution.getContext().getProperty("xwikicontext");
    final VelocityContext vContext = new VelocityContext();
    vContext.put("xcontext", xwikiContext);
    getMockery().checking(new Expectations() {

        {
            oneOf(mockVelocityManager).getCurrentVelocityContext();
            will(returnValue(vContext));
            oneOf(mockVelocityManager).evaluate(with(any(Writer.class)), with(any(String.class)), with(any(Reader.class)));
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    return vEngine.evaluate(vContext, (Writer) invocation.getParameter(0), (String) invocation.getParameter(1), (Reader) invocation.getParameter(2));
                }

                @Override
                public void describeTo(Description description) {
                }
            });
        }
    });
    List<WikiMacroParameterDescriptor> parameterDescriptors = Arrays.asList(new WikiMacroParameterDescriptor("param1", "This is param1", false, "default_value"));
    registerWikiMacro("wikimacro1", "{{velocity}}$xcontext.macro.params.param1 $xcontext.macro.params.paraM1{{/velocity}}", Syntax.XWIKI_2_0, parameterDescriptors);
    Converter converter = getComponentManager().getInstance(Converter.class);
    DefaultWikiPrinter printer = new DefaultWikiPrinter();
    converter.convert(new StringReader("{{wikimacro1/}}"), Syntax.XWIKI_2_0, Syntax.PLAIN_1_0, printer);
    Assert.assertEquals("default_value default_value", printer.toString());
}
Also used : Expectations(org.jmock.Expectations) VelocityEngine(org.xwiki.velocity.VelocityEngine) Action(org.jmock.api.Action) Description(org.hamcrest.Description) Invocation(org.jmock.api.Invocation) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) VelocityContext(org.apache.velocity.VelocityContext) Reader(java.io.Reader) StringReader(java.io.StringReader) Properties(java.util.Properties) WikiMacroParameterDescriptor(org.xwiki.rendering.macro.wikibridge.WikiMacroParameterDescriptor) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) Execution(org.xwiki.context.Execution) VelocityManager(org.xwiki.velocity.VelocityManager) StringReader(java.io.StringReader) Converter(org.xwiki.rendering.converter.Converter) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer) Test(org.junit.Test)

Example 57 with VelocityContext

use of org.apache.velocity.VelocityContext in project xwiki-platform by xwiki.

the class StubVelocityManager method evaluate.

@Override
public boolean evaluate(Writer out, String templateName, Reader source) throws XWikiVelocityException {
    // Get up to date Velocity context
    VelocityContext velocityContext = getVelocityContext();
    // Execute Velocity context
    boolean result = getVelocityEngine().evaluate(velocityContext, out, templateName, source);
    // Update current script context with potentially modified Velocity context
    ScriptContext scontext = this.scriptContextManager.getCurrentScriptContext();
    for (Object vkey : velocityContext.getKeys()) {
        if (vkey instanceof String) {
            String svkey = (String) vkey;
            // context is a reserved binding in JSR223 specification
            if (!"context".equals(svkey)) {
                scontext.setAttribute(svkey, velocityContext.get(svkey), ScriptContext.ENGINE_SCOPE);
            }
        }
    }
    return result;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) ScriptContext(javax.script.ScriptContext)

Example 58 with VelocityContext

use of org.apache.velocity.VelocityContext in project xwiki-platform by xwiki.

the class XWikiWebappResourceLoaderTest method testVelocityInitialization.

@Test
public void testVelocityInitialization() throws Exception {
    // Fake the initialization of the Servlet Environment
    ServletEnvironment environment = (ServletEnvironment) getComponentManager().getInstance(Environment.class);
    environment.setServletContext(getMockery().mock(ServletContext.class));
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "xwiki");
    properties.setProperty("xwiki.resource.loader.class", XWikiWebappResourceLoader.class.getName());
    VelocityFactory factory = getComponentManager().getInstance(VelocityFactory.class);
    VelocityEngine engine = factory.createVelocityEngine("key", properties);
    // Ensure Velocity has been correctly initialized by trying to evaluate some content.
    StringWriter out = new StringWriter();
    engine.evaluate(new VelocityContext(), out, "template", "#set ($var = 'value')$var");
    Assert.assertEquals("value", out.toString());
}
Also used : StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment) Environment(org.xwiki.environment.Environment) ServletContext(javax.servlet.ServletContext) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment) Properties(java.util.Properties) Test(org.junit.Test)

Example 59 with VelocityContext

use of org.apache.velocity.VelocityContext in project xwiki-platform by xwiki.

the class PackageMojo method expandJettyDistribution.

private void expandJettyDistribution() throws MojoExecutionException {
    Artifact jettyArtifact = resolveJettyArtifact();
    unzip(jettyArtifact.getFile(), this.outputPackageDirectory);
    // Replace properties in start shell scripts
    Collection<File> startFiles = org.apache.commons.io.FileUtils.listFiles(this.outputPackageDirectory, new WildcardFileFilter("start_xwiki*.*"), null);
    VelocityContext velocityContext = createVelocityContext();
    for (File startFile : startFiles) {
        getLog().info(String.format("  Replacing variables in [%s]...", startFile));
        try {
            String content = org.apache.commons.io.FileUtils.readFileToString(startFile, StandardCharsets.UTF_8);
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(startFile));
            writer.write(replaceProperty(content, velocityContext));
            writer.close();
        } catch (Exception e) {
            // Failed to read or write file...
            throw new MojoExecutionException(String.format("Failed to process start shell script [%s]", startFile), e);
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityContext(org.apache.velocity.VelocityContext) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) WildcardFileFilter(org.apache.commons.io.filefilter.WildcardFileFilter) Artifact(org.apache.maven.artifact.Artifact) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 60 with VelocityContext

use of org.apache.velocity.VelocityContext in project xwiki-platform by xwiki.

the class PackageMojo method generateConfigurationFiles.

private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException {
    VelocityContext context = createVelocityContext();
    Artifact configurationResourcesArtifact = this.repositorySystem.createArtifact("org.xwiki.platform", "xwiki-platform-tool-configuration-resources", getXWikiPlatformVersion(), "", "jar");
    resolveArtifact(configurationResourcesArtifact);
    configurationFileTargetDirectory.mkdirs();
    try (JarInputStream jarInputStream = new JarInputStream(new FileInputStream(configurationResourcesArtifact.getFile()))) {
        JarEntry entry;
        while ((entry = jarInputStream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".vm")) {
                String fileName = entry.getName().replace(".vm", "");
                File outputFile = new File(configurationFileTargetDirectory, fileName);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile));
                getLog().info("Writing config file: " + outputFile);
                // Note: Init is done once even if this method is called several times...
                Velocity.init();
                Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream, StandardCharsets.UTF_8));
                writer.close();
                jarInputStream.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to extract configuration files", e);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) JarInputStream(java.util.jar.JarInputStream) VelocityContext(org.apache.velocity.VelocityContext) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) JarEntry(java.util.jar.JarEntry) File(java.io.File) Artifact(org.apache.maven.artifact.Artifact) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Aggregations

VelocityContext (org.apache.velocity.VelocityContext)492 StringWriter (java.io.StringWriter)156 Template (org.apache.velocity.Template)120 Test (org.junit.Test)72 IOException (java.io.IOException)60 VelocityEngine (org.apache.velocity.app.VelocityEngine)53 File (java.io.File)47 ArrayList (java.util.ArrayList)39 HashMap (java.util.HashMap)36 Map (java.util.Map)36 Identity (org.olat.core.id.Identity)36 Context (org.apache.velocity.context.Context)32 MailTemplate (org.olat.core.util.mail.MailTemplate)28 Writer (java.io.Writer)22 Properties (java.util.Properties)20 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)19 ParseErrorException (org.apache.velocity.exception.ParseErrorException)16 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)16 FileWriter (java.io.FileWriter)15 OutputStreamWriter (java.io.OutputStreamWriter)14