Search in sources :

Example 6 with VelocityEngine

use of org.xwiki.velocity.VelocityEngine 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 7 with VelocityEngine

use of org.xwiki.velocity.VelocityEngine 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 8 with VelocityEngine

use of org.xwiki.velocity.VelocityEngine 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 9 with VelocityEngine

use of org.xwiki.velocity.VelocityEngine 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 10 with VelocityEngine

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

the class DefaultGadgetSource method prepareGadgets.

/**
 * Prepares a list of gadgets from a list of XWiki objects.
 *
 * @param objects the objects to read the gadgets from
 * @param sourceSyntax the syntax of the source of the gadget objects
 * @param context the macro transformation context, where the dashboard macro is being executed
 * @return the list of gadgets, as read from the xwiki objects
 * @throws Exception in case something happens while rendering the content in the objects
 */
private List<Gadget> prepareGadgets(List<BaseObject> objects, Syntax sourceSyntax, MacroTransformationContext context) throws Exception {
    List<Gadget> gadgets = new ArrayList<>();
    // prepare velocity tools to render title
    VelocityContext velocityContext = velocityManager.getVelocityContext();
    // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally
    // by Velocity as a cache index key for caching macros.
    String key = context.getTransformationContext().getId();
    if (key == null) {
        key = "unknown namespace";
    }
    VelocityEngine velocityEngine = velocityManager.getVelocityEngine();
    for (BaseObject xObject : objects) {
        if (xObject == null) {
            continue;
        }
        // get the data about the gadget from the object
        // TODO: filter for dashboard name when that field will be in
        String title = xObject.getStringValue("title");
        String content = xObject.getLargeStringValue("content");
        String position = xObject.getStringValue("position");
        String id = xObject.getNumber() + "";
        // render title with velocity
        StringWriter writer = new StringWriter();
        // FIXME: the engine has an issue with $ and # as last character. To test and fix if it happens
        velocityEngine.evaluate(velocityContext, writer, key, title);
        String gadgetTitle = writer.toString();
        // parse both the title and content in the syntax of the transformation context
        List<Block> titleBlocks = renderGadgetProperty(gadgetTitle, sourceSyntax, xObject.getDocumentReference(), context);
        List<Block> contentBlocks = renderGadgetProperty(content, sourceSyntax, xObject.getDocumentReference(), context);
        // create a gadget will all these and add the gadget to the container of gadgets
        Gadget gadget = new Gadget(id, titleBlocks, contentBlocks, position);
        gadget.setTitleSource(title);
        gadgets.add(gadget);
    }
    return gadgets;
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) Gadget(org.xwiki.rendering.macro.dashboard.Gadget) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) LinkBlock(org.xwiki.rendering.block.LinkBlock) Block(org.xwiki.rendering.block.Block) WordBlock(org.xwiki.rendering.block.WordBlock) GroupBlock(org.xwiki.rendering.block.GroupBlock) BaseObject(com.xpn.xwiki.objects.BaseObject)

Aggregations

VelocityEngine (org.xwiki.velocity.VelocityEngine)21 VelocityContext (org.apache.velocity.VelocityContext)18 VelocityManager (org.xwiki.velocity.VelocityManager)14 Test (org.junit.Test)11 Reader (java.io.Reader)6 StringWriter (java.io.StringWriter)6 Writer (java.io.Writer)6 Properties (java.util.Properties)5 DocumentAccessBridge (org.xwiki.bridge.DocumentAccessBridge)5 DocumentReference (org.xwiki.model.reference.DocumentReference)5 Map (java.util.Map)4 XWikiVelocityException (org.xwiki.velocity.XWikiVelocityException)4 HashMap (java.util.HashMap)3 Expectations (org.jmock.Expectations)3 Invocation (org.jmock.api.Invocation)3 Execution (org.xwiki.context.Execution)3 BaseObject (com.xpn.xwiki.objects.BaseObject)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 StringReader (java.io.StringReader)2 Description (org.hamcrest.Description)2