Search in sources :

Example 11 with VelocityManager

use of org.xwiki.velocity.VelocityManager in project xwiki-platform by xwiki.

the class PageTest method registerVelocityTool.

/**
 * Adds a tool to the Velocity context.
 *
 * @param name the name of the tool
 * @param tool the tool to register; can be a mock
 * @throws Exception in case of errors
 * @since 7.4M1
 */
protected void registerVelocityTool(String name, Object tool) throws Exception {
    VelocityManager velocityManager = this.oldcore.getMocker().getInstance(VelocityManager.class);
    velocityManager.getVelocityContext().put(name, tool);
}
Also used : VelocityManager(org.xwiki.velocity.VelocityManager)

Example 12 with VelocityManager

use of org.xwiki.velocity.VelocityManager in project xwiki-platform by xwiki.

the class WebJarsResourceReferenceHandlerTest method evaluateResource.

@Test
public void evaluateResource() throws Exception {
    WebJarsResourceReference reference = new WebJarsResourceReference("wiki:wiki", Arrays.asList("angular", "2.1.11", "angular.js"));
    reference.addParameter("evaluate", true);
    ByteArrayInputStream resourceStream = new ByteArrayInputStream("content".getBytes());
    when(this.classLoader.getResourceAsStream("META-INF/resources/webjars/angular/2.1.11/angular.js")).thenReturn(resourceStream);
    VelocityManager velocityManager = this.componentManager.getInstance(VelocityManager.class);
    VelocityEngine velocityEngine = mock(VelocityEngine.class);
    when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            ((StringWriter) invocation.getArguments()[1]).write("evaluated content");
            return null;
        }
    }).when(velocityEngine).evaluate(any(), any(), eq("angular/2.1.11/angular.js"), any(Reader.class));
    this.handler.handle(reference, this.chain);
    // Verify that the resource content has been evaluated and copied to the Response output stream.
    assertEquals("evaluated content", this.response.getOutputStream().toString());
    // Verify that the correct Content Type has been set.
    verify(this.response).setContentType("application/javascript");
    // Verify that the dynamic resource is not cached.
    verify(this.response.getHttpServletResponse(), never()).setHeader(any(), any());
    verify(this.response.getHttpServletResponse(), never()).setDateHeader(any(), anyLong());
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) WebJarsResourceReference(org.xwiki.webjars.internal.WebJarsResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) VelocityManager(org.xwiki.velocity.VelocityManager) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Reader(java.io.Reader) Test(org.junit.Test)

Example 13 with VelocityManager

use of org.xwiki.velocity.VelocityManager in project xwiki-platform by xwiki.

the class XWikiDocumentRenderingTest method testGetRenderedContentCleansVelocityMacroCache.

/**
 * See XWIKI-5277 for details.
 */
public void testGetRenderedContentCleansVelocityMacroCache() throws Exception {
    // Make sure we start not in the rendering engine since this is what happens in real: a document is
    // called by a template thus outside of the rendering engine.
    getContext().remove("isInRenderingEngine");
    // We display a text area since we know that rendering a text area will call getRenderedContent inside our top
    // level getRenderedContent call, thus testing that velocity macros are not removed during nested calls to
    // getRenderedContent.
    this.baseObject.setLargeStringValue("area", "{{velocity}}#macro(testmacrocache)ok#end{{/velocity}}");
    this.document.setContent("{{velocity}}$doc.display(\"area\")#testmacrocache{{/velocity}}");
    this.document.setSyntax(Syntax.XWIKI_2_0);
    // We need to put the current doc in the Velocity Context since it's normally set before the rendering is
    // called in the execution flow.
    VelocityManager originalVelocityManager = getComponentManager().getInstance(VelocityManager.class);
    VelocityContext vcontext = originalVelocityManager.getVelocityContext();
    vcontext.put("doc", new Document(this.document, getContext()));
    // Register a Mock for the VelocityManager to bypass skin APIs that we would need to mock otherwise.
    Mock mockVelocityManager = registerMockComponent(VelocityManager.class);
    mockVelocityManager.stubs().method("getCurrentVelocityContext").will(returnValue(vcontext));
    VelocityFactory velocityFactory = getComponentManager().getInstance(VelocityFactory.class);
    VelocityEngine vengine = velocityFactory.createVelocityEngine("default", new Properties());
    // Save the number of cached macro templates in the Velocity engine so that we can compare after the
    // document is rendered.
    JMXVelocityEngineMBean mbean = new JMXVelocityEngine(vengine);
    int cachedMacroNamespaceSize = mbean.getTemplates().values().size();
    assertTrue(cachedMacroNamespaceSize > 0);
    mockVelocityManager.stubs().method("getVelocityEngine").will(returnValue(vengine));
    mockVelocityManager.stubs().method("evaluate").will(new CustomStub("evaluate") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            return vengine.evaluate(vcontext, (Writer) invocation.parameterValues.get(0), (String) invocation.parameterValues.get(1), (Reader) invocation.parameterValues.get(2));
        }
    });
    // $doc.display will ask for the syntax of the current document so we need to mock it.
    this.mockXWiki.stubs().method("getCurrentContentSyntaxId").with(eq("xwiki/2.0"), ANYTHING).will(returnValue("xwiki/2.0"));
    // Verify that the macro located inside the TextArea has been taken into account when executing the doc's
    // content.
    assertEquals("<p>ok</p>", this.document.getRenderedContent(getContext()));
    // Now verify that the Velocity Engine doesn't contain any more cached macro namespace to prove that
    // getRenderedContent has correctly cleaned the Velocity macro cache.
    assertEquals(cachedMacroNamespaceSize, mbean.getTemplates().values().size());
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) JMXVelocityEngine(org.xwiki.velocity.internal.jmx.JMXVelocityEngine) Invocation(org.jmock.core.Invocation) VelocityFactory(org.xwiki.velocity.VelocityFactory) VelocityContext(org.apache.velocity.VelocityContext) JMXVelocityEngineMBean(org.xwiki.velocity.internal.jmx.JMXVelocityEngineMBean) Reader(java.io.Reader) Document(com.xpn.xwiki.api.Document) Properties(java.util.Properties) Mock(org.jmock.Mock) JMXVelocityEngine(org.xwiki.velocity.internal.jmx.JMXVelocityEngine) CustomStub(org.jmock.core.stub.CustomStub) VelocityManager(org.xwiki.velocity.VelocityManager) BaseObject(com.xpn.xwiki.objects.BaseObject) Writer(java.io.Writer)

Example 14 with VelocityManager

use of org.xwiki.velocity.VelocityManager in project xwiki-platform by xwiki.

the class DefaultWikiMacroTest method testDefaultParameterNames.

/**
 * Makes sure getParameterNames return parameters with source case.
 */
@Test
public void testDefaultParameterNames() 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) {
                }
            });
        }
    });
    registerWikiMacro("wikimacro1", "{{velocity}}$xcontext.macro.params.parameterNames{{/velocity}}", Syntax.XWIKI_2_0);
    Converter converter = getComponentManager().getInstance(Converter.class);
    DefaultWikiPrinter printer = new DefaultWikiPrinter();
    converter.convert(new StringReader("{{wikimacro1 paRam1=\"value1\" paraM2=\"value2\"/}}"), Syntax.XWIKI_2_0, Syntax.PLAIN_1_0, printer);
    Assert.assertEquals("[paRam1, paraM2]", 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) 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 15 with VelocityManager

use of org.xwiki.velocity.VelocityManager 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)

Aggregations

VelocityManager (org.xwiki.velocity.VelocityManager)31 VelocityContext (org.apache.velocity.VelocityContext)19 Test (org.junit.Test)15 VelocityEngine (org.xwiki.velocity.VelocityEngine)15 StringWriter (java.io.StringWriter)12 DocumentReference (org.xwiki.model.reference.DocumentReference)8 Reader (java.io.Reader)6 DocumentAccessBridge (org.xwiki.bridge.DocumentAccessBridge)5 XWikiException (com.xpn.xwiki.XWikiException)4 BaseObject (com.xpn.xwiki.objects.BaseObject)4 IOException (java.io.IOException)4 Writer (java.io.Writer)4 Map (java.util.Map)4 Properties (java.util.Properties)4 Execution (org.xwiki.context.Execution)4 MacroTransformationContext (org.xwiki.rendering.transformation.MacroTransformationContext)4 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Expectations (org.jmock.Expectations)3 Invocation (org.jmock.api.Invocation)3