Search in sources :

Example 16 with VelocityEngine

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);
}
Also used : ResourceReferenceHandlerException(org.xwiki.resource.ResourceReferenceHandlerException) VelocityEngine(org.xwiki.velocity.VelocityEngine) WebJarsResourceReference(org.xwiki.webjars.internal.WebJarsResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) VelocityManager(org.xwiki.velocity.VelocityManager) VelocityException(org.apache.velocity.exception.VelocityException) Reader(java.io.Reader) Test(org.junit.Test)

Example 17 with VelocityEngine

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;
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) XWikiVelocityException(org.xwiki.velocity.XWikiVelocityException) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with VelocityEngine

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);
        }
    }
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) XWikiVelocityException(org.xwiki.velocity.XWikiVelocityException) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) IconException(org.xwiki.icon.IconException)

Example 19 with VelocityEngine

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());
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Writer(java.io.Writer) Test(org.junit.Test)

Example 20 with VelocityEngine

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());
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) Writer(java.io.Writer) IconException(org.xwiki.icon.IconException) Test(org.junit.Test)

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