Search in sources :

Example 1 with VelocityEngine

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

the class ExplicitlyAllowedValuesDBListQueryBuilder method evaluateVelocityCode.

private String evaluateVelocityCode(String code, String namespace) throws Exception {
    VelocityManager velocityManager = this.velocityManagerProvider.get();
    VelocityContext velocityContext = velocityManager.getVelocityContext();
    VelocityEngine velocityEngine = velocityManager.getVelocityEngine();
    StringWriter writer = new StringWriter();
    velocityEngine.evaluate(velocityContext, writer, namespace, code);
    return writer.toString();
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) StringWriter(java.io.StringWriter) VelocityManager(org.xwiki.velocity.VelocityManager) VelocityContext(org.apache.velocity.VelocityContext)

Example 2 with VelocityEngine

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

the class DefaultVelocityManager method getVelocityEngine.

/**
 * @return the Velocity Engine corresponding to the current execution context. More specifically returns the
 *         Velocity Engine for the current skin since each skin has its own Velocity Engine so that each skin can
 *         have global velocimacros defined
 * @throws XWikiVelocityException in case of an error while creating a Velocity Engine
 */
@Override
public VelocityEngine getVelocityEngine() throws XWikiVelocityException {
    // Note: For improved performance we cache the Velocity Engines in order not to
    // recreate them all the time. The key we use is the location to the skin's macro.vm
    // file since caching on the skin would create more Engines than needed (some skins
    // don't have a macros.vm file and some skins inherit from others).
    // Create a Velocity context using the Velocity Manager associated to the current skin's
    // macros.vm
    // Get the location of the skin's macros.vm file
    XWikiContext xcontext = this.xcontextProvider.get();
    final Template template;
    if (xcontext != null && xcontext.getWiki() != null) {
        template = getVelocityEngineMacrosTemplate();
    } else {
        template = null;
    }
    String cacheKey = template != null ? template.getId() : "default";
    // Get the Velocity Engine to use
    VelocityEngine velocityEngine = this.velocityFactory.getVelocityEngine(cacheKey);
    if (velocityEngine == null) {
        // created only when a new skin is created and not be on the main execution path.
        synchronized (this) {
            velocityEngine = this.velocityFactory.getVelocityEngine(cacheKey);
            if (velocityEngine == null) {
                // Gather the global Velocity macros that we want to have. These are skin dependent.
                Properties properties = new Properties();
                // Loader
                if (!this.velocityConfiguration.getProperties().containsKey(RESOURCE_LOADER)) {
                    properties.setProperty(RESOURCE_LOADER, "xwiki");
                    properties.setProperty(RESOURCE_LOADER_CLASS, XWikiWebappResourceLoader.class.getName());
                }
                if (xcontext != null && xcontext.getWiki() != null) {
                    // Note: if you don't want any template to be used set the property named
                    // xwiki.render.velocity.macrolist to an empty string value.
                    String macroList = xcontext.getWiki().Param("xwiki.render.velocity.macrolist");
                    if (macroList == null) {
                        macroList = "/templates/macros.vm";
                    }
                    properties.put(RuntimeConstants.VM_LIBRARY, macroList);
                }
                velocityEngine = this.velocityFactory.createVelocityEngine(cacheKey, properties);
                if (template != null) {
                    // template by default
                    try {
                        final VelocityEngine finalVelocityEngine = velocityEngine;
                        this.authorExecutor.call(() -> {
                            finalVelocityEngine.evaluate(new VelocityContext(), NullWriter.NULL_WRITER, "", template.getContent().getContent());
                            return null;
                        }, template.getContent().getAuthorReference());
                    } catch (Exception e) {
                        this.logger.error("Failed to evaluate macros templates [{}]", template.getPath(), e);
                    }
                }
            }
        }
    }
    return velocityEngine;
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) XWikiContext(com.xpn.xwiki.XWikiContext) Properties(java.util.Properties) XWikiWebappResourceLoader(org.xwiki.velocity.XWikiWebappResourceLoader) XWikiVelocityException(org.xwiki.velocity.XWikiVelocityException) InitializationException(org.xwiki.component.phase.InitializationException) Template(org.xwiki.template.Template)

Example 3 with VelocityEngine

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

the class AbstractDocumentTitleDisplayer method evaluateTitle.

/**
 * Evaluates the Velocity script from the specified title.
 *
 * @param title the title to evaluate
 * @param documentReference a reference to the document whose title is evaluated
 * @param parameters display parameters
 * @return the result of evaluating the Velocity script from the given title
 */
protected String evaluateTitle(String title, DocumentReference documentReference, DocumentDisplayerParameters parameters) {
    StringWriter writer = new StringWriter();
    String namespace = defaultEntityReferenceSerializer.serialize(parameters.isTransformationContextIsolated() ? documentReference : documentAccessBridge.getCurrentDocumentReference());
    // Get the velocity engine
    VelocityEngine velocityEngine;
    try {
        velocityEngine = this.velocityManager.getVelocityEngine();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // Execute Velocity code
    Map<String, Object> backupObjects = null;
    boolean canPop = false;
    EntityReference currentWikiReference = this.modelContext.getCurrentEntityReference();
    try {
        if (parameters.isExecutionContextIsolated()) {
            backupObjects = new HashMap<String, Object>();
            // The following method call also clones the execution context.
            documentAccessBridge.pushDocumentInContext(backupObjects, documentReference);
            // Pop the document from the context only if the push was successful!
            canPop = true;
            // Make sure to synchronize the context wiki with the context document's wiki.
            modelContext.setCurrentEntityReference(documentReference.getWikiReference());
        }
        velocityEngine.evaluate(velocityManager.getVelocityContext(), writer, namespace, title);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (canPop) {
            documentAccessBridge.popDocumentFromContext(backupObjects);
            // Also restore the context wiki.
            this.modelContext.setCurrentEntityReference(currentWikiReference);
        }
    }
    return writer.toString();
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) StringWriter(java.io.StringWriter) EntityReference(org.xwiki.model.reference.EntityReference) ParseException(org.xwiki.rendering.parser.ParseException)

Example 4 with VelocityEngine

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

the class DefaultMailTemplateManagerTest method evaluateWithObjectNotFoundWithLanguagePassed.

@Test
public void evaluateWithObjectNotFoundWithLanguagePassed() throws Exception {
    DocumentAccessBridge documentBridge = this.mocker.getInstance(DocumentAccessBridge.class);
    DocumentReference documentReference = new DocumentReference("wiki", "space", "page");
    // First call with the passed language, return -1 (No XWiki.Mail xobject found)
    when(documentBridge.getObjectNumber(any(), any(), eq("language"), eq("fr"))).thenReturn(-1);
    // Second call with the default language (en), return one (Only XWiki.Mail xobject is found)
    when(documentBridge.getObjectNumber(any(), any(), eq("language"), eq("en"))).thenReturn(1);
    when(documentBridge.getProperty(any(DocumentReference.class), any(), eq(1), eq("html"))).thenReturn("Salut <b>${name}</b> <br />${email}");
    VelocityEngine velocityEngine = mock(VelocityEngine.class);
    VelocityManager velocityManager = this.mocker.getInstance(VelocityManager.class);
    when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);
    when(velocityEvaluator.evaluateVelocity(eq("Salut <b>${name}</b> <br />${email}"), any(), any(VelocityContext.class))).thenReturn("Salut <b>John Doe</b> <br />john@doe.com");
    String result = this.mocker.getComponentUnderTest().evaluate(documentReference, "html", Collections.emptyMap(), Locale.FRENCH);
    verify(documentBridge).getObjectNumber(any(), any(), eq("language"), eq("fr"));
    verify(documentBridge).getObjectNumber(any(), any(), eq("language"), eq("en"));
    assertEquals(result, "Salut <b>John Doe</b> <br />john@doe.com");
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) VelocityManager(org.xwiki.velocity.VelocityManager) VelocityContext(org.apache.velocity.VelocityContext) DocumentAccessBridge(org.xwiki.bridge.DocumentAccessBridge) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Example 5 with VelocityEngine

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

the class DefaultMailTemplateManagerTest method evaluateWithObjectNotFoundWithDefaultLanguage.

@Test
public void evaluateWithObjectNotFoundWithDefaultLanguage() throws Exception {
    DocumentAccessBridge documentBridge = this.mocker.getInstance(DocumentAccessBridge.class);
    DocumentReference documentReference = new DocumentReference("wiki", "space", "page");
    // First call with the passed language, return -1 (No XWiki.Mail xobject found)
    when(documentBridge.getObjectNumber(any(), any(), eq("language"), eq("fr"))).thenReturn(-1);
    // Second call with the default language, return -1 (No XWiki.Mail xobject found)
    when(documentBridge.getObjectNumber(any(), any(), eq("language"), eq("en"))).thenReturn(-1);
    when(documentBridge.getProperty(any(DocumentReference.class), any(), eq(0), eq("html"))).thenReturn("Salut <b>${name}</b> <br />${email}");
    VelocityEngine velocityEngine = mock(VelocityEngine.class);
    VelocityManager velocityManager = this.mocker.getInstance(VelocityManager.class);
    when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);
    when(velocityEvaluator.evaluateVelocity(eq("Salut <b>${name}</b> <br />${email}"), any(), any(VelocityContext.class))).thenReturn("Salut <b>John Doe</b> <br />john@doe.com");
    String result = this.mocker.getComponentUnderTest().evaluate(documentReference, "html", Collections.emptyMap(), Locale.FRENCH);
    verify(documentBridge).getObjectNumber(any(), any(), eq("language"), eq("fr"));
    verify(documentBridge).getObjectNumber(any(), any(), eq("language"), eq("en"));
    assertEquals(result, "Salut <b>John Doe</b> <br />john@doe.com");
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) VelocityManager(org.xwiki.velocity.VelocityManager) VelocityContext(org.apache.velocity.VelocityContext) DocumentAccessBridge(org.xwiki.bridge.DocumentAccessBridge) DocumentReference(org.xwiki.model.reference.DocumentReference) 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