Search in sources :

Example 51 with VelocityContext

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

the class MacrosTest method setup.

@Before
public void setup() {
    this.ve = new VelocityEngine();
    Properties props = new Properties();
    String path = String.format("%s/src/main/webapp/templates", BASEDIR);
    props.setProperty("file.resource.loader.path", path);
    props.setProperty("directive.set.null.allowed", "true");
    props.setProperty("velocimacro.permissions.allow.inline.local.scope", "true");
    props.setProperty("velocimacro.library", "macros.vm");
    this.ve.init(props);
    this.context = new VelocityContext();
    this.context.put("escapetool", new EscapeTool());
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) EscapeTool(org.xwiki.velocity.tools.EscapeTool) Properties(java.util.Properties) Before(org.junit.Before)

Example 52 with VelocityContext

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

the class PdfExportImpl method getPDFTemplateProperty.

/**
 * Extract XSLT file content using the following algorithm:
 * <ul>
 *   <li>Check if a query string named {@code pdftemplate} exists and if so use its value as the reference to
 *       a document containing a XWiki.PDFClass xobject from which to extract the XSLT data. If not defined
 *       (or if empty) then use the current document as the document having the XWiki.PDFClass xobject.</li>
 *   <li>Read the value of the xproperty named after the passed {@code propertyName} parameter. If the document
 *       or the property don't exist, then return an empty String. Otherwise execute Velocity on the xproperty's
 *       value and return this.</li>
 * </ul>
 *
 * @param propertyName the xproperty containing the XSLT to return
 * @param context the current request context
 * @return the content of the xproperty, velocity-parsed, or an empty string if there's no such property
 */
private String getPDFTemplateProperty(String propertyName, XWikiContext context) {
    String pdftemplate = context.getRequest().getParameter("pdftemplate");
    DocumentReference templateReference;
    DocumentReference classReference;
    if (StringUtils.isNotEmpty(pdftemplate)) {
        templateReference = referenceResolver.resolve(pdftemplate);
        classReference = new DocumentReference(templateReference.getWikiReference().getName(), "XWiki", "PDFClass");
    } else {
        templateReference = dab.getCurrentDocumentReference();
        String currentWiki = dab.getCurrentDocumentReference().getRoot().getName();
        classReference = new DocumentReference(currentWiki, "XWiki", "PDFClass");
    }
    String result = (String) dab.getProperty(templateReference, classReference, propertyName);
    if (StringUtils.isBlank(result)) {
        return "";
    }
    String templateName = referenceSerializer.serialize(templateReference);
    try {
        StringWriter writer = new StringWriter();
        VelocityContext vcontext = velocityManager.getVelocityContext();
        velocityManager.getVelocityEngine().evaluate(vcontext, writer, templateName, result);
        result = writer.toString();
    } catch (XWikiVelocityException e) {
        LOGGER.warn("Error applying Velocity to the [{}] property of the [{}] document. Using the property's value " + "without applying Velocity.", propertyName, templateName, ExceptionUtils.getRootCauseMessage(e));
    }
    return result;
}
Also used : XWikiVelocityException(org.xwiki.velocity.XWikiVelocityException) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 53 with VelocityContext

use of org.apache.velocity.VelocityContext 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 54 with VelocityContext

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

the class XWikiDocumentTest method testBackupRestoreContextUpdatesVContext.

/**
 * XWIKI-8025: XWikiDocument#backup/restoreContext doesn't update the reference to the Velocity context stored on
 * the XWiki context
 */
public void testBackupRestoreContextUpdatesVContext() throws Exception {
    final Execution execution = getComponentManager().getInstance(Execution.class);
    this.mockVelocityManager.stubs().method("getVelocityContext").will(new CustomStub("Implements VelocityManager.getVelocityContext") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            return (VelocityContext) execution.getContext().getProperty("velocityContext");
        }
    });
    VelocityContext oldVelocityContext = new VelocityContext();
    execution.getContext().setProperty("velocityContext", oldVelocityContext);
    Map<String, Object> backup = new HashMap<String, Object>();
    XWikiDocument.backupContext(backup, getContext());
    VelocityContext newVelocityContext = (VelocityContext) execution.getContext().getProperty("velocityContext");
    assertNotNull(newVelocityContext);
    assertNotSame(oldVelocityContext, newVelocityContext);
    assertSame(newVelocityContext, getContext().get("vcontext"));
    XWikiDocument.restoreContext(backup, getContext());
    assertSame(oldVelocityContext, execution.getContext().getProperty("velocityContext"));
    assertSame(oldVelocityContext, getContext().get("vcontext"));
}
Also used : Execution(org.xwiki.context.Execution) Invocation(org.jmock.core.Invocation) CustomStub(org.jmock.core.stub.CustomStub) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 55 with VelocityContext

use of org.apache.velocity.VelocityContext 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)

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