use of org.xwiki.velocity.VelocityEngine in project xwiki-platform by xwiki.
the class WebJarsResourceReferenceHandlerTest method failingResourceEvaluation.
@Test
public void failingResourceEvaluation() 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);
when(velocityEngine.evaluate(any(), any(), eq("angular/2.1.11/angular.js"), any(Reader.class))).thenThrow(new VelocityException("Bad code!"));
this.handler.handle(reference, this.chain);
// Verify the exception is logged.
verify(this.componentManager.getMockedLogger()).error(eq("Failed to evaluate the Velocity code from WebJar resource [angular/2.1.11/angular.js]"), any(ResourceReferenceHandlerException.class));
// Verify that the client is properly notified about the failure.
verify(this.response.getHttpServletResponse()).sendError(500, "Failed to evaluate the Velocity code from WebJar resource [angular/2.1.11/angular.js]");
// The next handlers are still called.
verify(this.chain).handleNext(reference);
}
use of org.xwiki.velocity.VelocityEngine in project xwiki-platform by xwiki.
the class WikiUIExtensionParameters method get.
/**
* @return the parameters, after their values have been evaluated by the XWiki Velocity Engine.
*/
public Map<String, String> get() {
boolean isCacheValid = false;
// Even though the parameters are dynamic, we cache a rendered version of them in order to improve performance.
// This cache has a short lifespan, it gets discarded for each new request, or if the database has been switched
// during a request.
int currentContextId = this.execution.getContext().hashCode();
String currentWiki = modelContext.getCurrentEntityReference().extractReference(EntityType.WIKI).getName();
if (currentContextId == this.previousContextId && currentWiki.equals(previousWiki) && this.evaluatedParameters != null) {
isCacheValid = true;
}
if (!isCacheValid) {
this.evaluatedParameters = new HashMap<String, String>();
if (this.parameters.size() > 0) {
try {
VelocityEngine velocityEngine = this.velocityManager.getVelocityEngine();
VelocityContext velocityContext = this.velocityManager.getVelocityContext();
for (Map.Entry<String, String> entry : this.parameters.entrySet()) {
StringWriter writer = new StringWriter();
try {
String namespace = this.id + ':' + entry.getKey();
velocityEngine.evaluate(new VelocityContext(velocityContext), writer, namespace, entry.getValue());
this.evaluatedParameters.put(entry.getKey(), writer.toString());
} catch (XWikiVelocityException e) {
LOGGER.warn(String.format("Failed to evaluate UI extension data value, key [%s], value [%s]. Reason: [%s]", entry.getKey(), entry.getValue(), e.getMessage()));
}
}
} catch (XWikiVelocityException ex) {
LOGGER.warn(String.format("Failed to get velocity engine. Reason: [%s]", ex.getMessage()));
}
this.previousContextId = currentContextId;
this.previousWiki = currentWiki;
}
}
return this.evaluatedParameters;
}
use of org.xwiki.velocity.VelocityEngine in project xwiki-platform by xwiki.
the class VelocityRenderer method render.
/**
* Render a velocity code without messing with the document context and namespace.
* @param code code to render
* @return the rendered code
* @throws IconException if problem occurs
*/
public String render(String code) throws IconException {
// The macro namespace to use by the velocity engine, see afterwards.
String namespace = "IconVelocityRenderer_" + Thread.currentThread().getId();
// Create the output writer
StringWriter output = new StringWriter();
VelocityEngine engine = null;
try {
// Get the velocity engine
engine = velocityManager.getVelocityEngine();
// Use a new macro namespace to prevent the code redefining existing macro.
// We use the thread name to have a unique id.
engine.startedUsingMacroNamespace(namespace);
// Create a new VelocityContext to prevent the code creating variables in the current context.
// See https://jira.xwiki.org/browse/XWIKI-11400.
// We set the current context as inner context of the new one to be able to read existing variables.
// See https://jira.xwiki.org/browse/XWIKI-11426.
VelocityContext context = new VelocityContext(velocityManager.getVelocityContext());
// Render the code
if (engine.evaluate(context, output, "DefaultIconRenderer", code)) {
return output.toString();
} else {
// I don't know how to check the velocity runtime log
throw new IconException("Failed to render the icon. See the Velocity runtime log.", null);
}
} catch (XWikiVelocityException e) {
throw new IconException("Failed to render the icon.", e);
} finally {
// Do not forget to close the macro namespace we have created previously
if (engine != null) {
engine.stoppedUsingMacroNamespace(namespace);
}
}
}
use of org.xwiki.velocity.VelocityEngine in project xwiki-platform by xwiki.
the class VelocityRendererTest method renderTest.
@Test
public void renderTest() throws Exception {
// Mocks
VelocityEngine engine = mock(VelocityEngine.class);
when(velocityManager.getVelocityEngine()).thenReturn(engine);
when(engine.evaluate(any(VelocityContext.class), any(Writer.class), any(), eq("myCode"))).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// Get the writer
Writer writer = (Writer) invocation.getArguments()[1];
writer.write("Rendered code");
return true;
}
});
// Test
assertEquals("Rendered code", mocker.getComponentUnderTest().render("myCode"));
// Verify
verify(engine).startedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId());
verify(engine).stoppedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId());
}
use of org.xwiki.velocity.VelocityEngine in project xwiki-platform by xwiki.
the class VelocityRendererTest method renderWhenEvaluateReturnsFalse.
@Test
public void renderWhenEvaluateReturnsFalse() throws Exception {
// Mocks
VelocityEngine engine = mock(VelocityEngine.class);
when(velocityManager.getVelocityEngine()).thenReturn(engine);
when(engine.evaluate(any(VelocityContext.class), any(Writer.class), any(), eq("myCode"))).thenReturn(false);
// Test
IconException caughtException = null;
try {
mocker.getComponentUnderTest().render("myCode");
} catch (IconException e) {
caughtException = e;
}
// Verify
assertNotNull(caughtException);
assertEquals("Failed to render the icon. See the Velocity runtime log.", caughtException.getMessage());
verify(engine).startedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId());
verify(engine).stoppedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId());
}
Aggregations