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());
}
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;
}
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());
}
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"));
}
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());
}
Aggregations