Search in sources :

Example 6 with MutableRenderingContext

use of org.xwiki.rendering.internal.transformation.MutableRenderingContext in project xwiki-platform by xwiki.

the class DefaultWikiComponentMethodExecutor method execute.

@Override
public Object execute(Method method, Object[] args, DocumentReference componentDocumentReference, XDOM xdom, Syntax syntax, Map<String, Object> methodContext) throws WikiComponentRuntimeException {
    // Prepare and put the method context in the XWiki Context
    Map<Object, Object> xwikiContext = (Map<Object, Object>) execution.getContext().getProperty("xwikicontext");
    this.prepareMethodContext(methodContext, args);
    xwikiContext.put("method", methodContext);
    // Save current context document, to put it back after the execution.
    Object contextDoc = xwikiContext.get(XWIKI_CONTEXT_DOC_KEY);
    try {
        // component document and not the context one.
        try {
            xwikiContext.put(XWIKI_CONTEXT_DOC_KEY, dab.getDocumentInstance(componentDocumentReference));
        } catch (Exception e) {
            throw new WikiComponentRuntimeException(String.format("Failed to load wiki component document [%s]", componentDocumentReference), e);
        }
        // We need to clone the xdom to avoid transforming the original and make it useless after the first
        // transformation
        XDOM transformedXDOM = xdom.clone();
        // Perform internal macro transformations
        try {
            TransformationContext transformationContext = new TransformationContext(transformedXDOM, syntax);
            transformationContext.setId(method.getClass().getName() + "#" + method.getName());
            ((MutableRenderingContext) renderingContext).transformInContext(macroTransformation, transformationContext, transformedXDOM);
        } catch (TransformationException e) {
            throw new WikiComponentRuntimeException(String.format("Error while executing wiki component macro transformation for method [%s]", method.getName()), e);
        }
        if (!method.getReturnType().getName().equals("void")) {
            if (methodContext.get(OUTPUT_KEY) != null && ((WikiMethodOutputHandler) methodContext.get(OUTPUT_KEY)).getValue() != null) {
                return method.getReturnType().cast(((WikiMethodOutputHandler) methodContext.get(OUTPUT_KEY)).getValue());
            } else {
                return this.castRenderedContent(transformedXDOM, method);
            }
        } else {
            return null;
        }
    } finally {
        if (contextDoc != null) {
            xwikiContext.put(XWIKI_CONTEXT_DOC_KEY, contextDoc);
        }
    }
}
Also used : TransformationException(org.xwiki.rendering.transformation.TransformationException) XDOM(org.xwiki.rendering.block.XDOM) HashMap(java.util.HashMap) Map(java.util.Map) TransformationContext(org.xwiki.rendering.transformation.TransformationContext) TransformationException(org.xwiki.rendering.transformation.TransformationException) WikiComponentRuntimeException(org.xwiki.component.wiki.WikiComponentRuntimeException) ConversionException(org.xwiki.properties.converter.ConversionException) WikiComponentRuntimeException(org.xwiki.component.wiki.WikiComponentRuntimeException) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext)

Example 7 with MutableRenderingContext

use of org.xwiki.rendering.internal.transformation.MutableRenderingContext in project xwiki-platform by xwiki.

the class EmailTemplateRenderer method executeTemplate.

/**
 * Execute a template.
 *
 * @param event composite event to render
 * @param userId id of the user who will receive the email
 * @param template the template to use
 * @param syntax syntax of the template and of the output
 * @return the rendered template
 * @throws NotificationException if something wrong happens
 */
public Block executeTemplate(CompositeEvent event, String userId, Template template, Syntax syntax) throws NotificationException {
    XWikiContext context = contextProvider.get();
    XWikiURLFactory originalURLFactory = context.getURLFactory();
    ScriptContext scriptContext = scriptContextManager.getScriptContext();
    try {
        // Bind the event to some variable in the velocity context
        scriptContext.setAttribute(EVENT_BINDING_NAME, event, ScriptContext.ENGINE_SCOPE);
        scriptContext.setAttribute(USER_BINDING_NAME, userId, ScriptContext.ENGINE_SCOPE);
        // Use the external URL factory to generate full URLs
        context.setURLFactory(new ExternalServletURLFactory(context));
        // Set the given syntax in the rendering context
        if (renderingContext instanceof MutableRenderingContext) {
            ((MutableRenderingContext) renderingContext).push(null, null, syntax, null, false, syntax);
        }
        // Render the template or fallback to the default one
        return templateManager.execute(template);
    } catch (Exception e) {
        throw new NotificationException("Failed to render the notification.", e);
    } finally {
        // Cleaning the rendering context
        if (renderingContext instanceof MutableRenderingContext) {
            ((MutableRenderingContext) renderingContext).pop();
        }
        // Cleaning the URL factory
        context.setURLFactory(originalURLFactory);
        // Cleaning the velocity context
        scriptContext.removeAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE);
        scriptContext.removeAttribute(USER_BINDING_NAME, ScriptContext.ENGINE_SCOPE);
    }
}
Also used : XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) ExternalServletURLFactory(com.xpn.xwiki.web.ExternalServletURLFactory) NotificationException(org.xwiki.notifications.NotificationException) XWikiContext(com.xpn.xwiki.XWikiContext) ScriptContext(javax.script.ScriptContext) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) NotificationException(org.xwiki.notifications.NotificationException)

Example 8 with MutableRenderingContext

use of org.xwiki.rendering.internal.transformation.MutableRenderingContext in project xwiki-platform by xwiki.

the class XWikiAction method renderInit.

private void renderInit(XWikiContext xcontext) throws Exception {
    RenderingContext renderingContext = Utils.getComponent(RenderingContext.class);
    MutableRenderingContext mutableRenderingContext = renderingContext instanceof MutableRenderingContext ? (MutableRenderingContext) renderingContext : null;
    if (mutableRenderingContext != null) {
        mutableRenderingContext.push(renderingContext.getTransformation(), renderingContext.getXDOM(), renderingContext.getDefaultSyntax(), "init.vm", renderingContext.isRestricted(), Syntax.XHTML_1_0);
    }
    xcontext.getResponse().setStatus(503);
    xcontext.getResponse().setContentType("text/html; charset=UTF-8");
    try {
        Utils.getComponent(TemplateManager.class).render("init.vm", xcontext.getResponse().getWriter());
    } finally {
        if (mutableRenderingContext != null) {
            mutableRenderingContext.pop();
        }
    }
    xcontext.getResponse().flushBuffer();
    xcontext.setFinished(true);
}
Also used : RenderingContext(org.xwiki.rendering.transformation.RenderingContext) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) TemplateManager(org.xwiki.template.TemplateManager) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext)

Example 9 with MutableRenderingContext

use of org.xwiki.rendering.internal.transformation.MutableRenderingContext in project xwiki-platform by xwiki.

the class InternalTemplateManager method evaluateContent.

private void evaluateContent(Template template, TemplateContent content, Writer writer) throws Exception {
    // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally
    // by Velocity as a cache index key for caching macros.
    String namespace = this.renderingContext.getTransformationId();
    boolean renderingContextPushed = false;
    if (namespace == null) {
        namespace = template.getId() != null ? template.getId() : "unknown namespace";
        if (this.renderingContext instanceof MutableRenderingContext) {
            // Make the current velocity template id available
            ((MutableRenderingContext) this.renderingContext).push(this.renderingContext.getTransformation(), this.renderingContext.getXDOM(), this.renderingContext.getDefaultSyntax(), namespace, this.renderingContext.isRestricted(), this.renderingContext.getTargetSyntax());
            renderingContextPushed = true;
        }
    }
    this.progress.startStep(template, "template.evaluateContent.message", "Evaluate content of template with id [{}]", template.getId());
    try {
        this.velocityManager.evaluate(writer, namespace, new StringReader(content.getContent()));
    } finally {
        // Get rid of temporary rendering context
        if (renderingContextPushed) {
            ((MutableRenderingContext) this.renderingContext).pop();
        }
        this.progress.endStep(template);
    }
}
Also used : StringReader(java.io.StringReader) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext)

Example 10 with MutableRenderingContext

use of org.xwiki.rendering.internal.transformation.MutableRenderingContext in project xwiki-platform by xwiki.

the class DefaultVelocityEvaluator method evaluateVelocity.

@Override
public String evaluateVelocity(String content, String namespace, VelocityContext vcontext) throws XWikiException {
    StringWriter writer = new StringWriter();
    boolean renderingContextPushed = false;
    try {
        // Switch current namespace if needed
        String currentNamespace = renderingContext.getTransformationId();
        if (namespace != null && !StringUtils.equals(namespace, currentNamespace)) {
            if (renderingContext instanceof MutableRenderingContext) {
                // Make the current velocity template id available
                ((MutableRenderingContext) renderingContext).push(renderingContext.getTransformation(), renderingContext.getXDOM(), renderingContext.getDefaultSyntax(), namespace, renderingContext.isRestricted(), renderingContext.getTargetSyntax());
                renderingContextPushed = true;
            }
        }
        velocityManager.getVelocityEngine().evaluate(vcontext, writer, namespace, content);
        return writer.toString();
    } catch (Exception e) {
        Object[] args = { namespace };
        throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_RENDERING_VELOCITY_EXCEPTION, "Error while parsing velocity page {0}", e, args);
    } finally {
        // Get rid of temporary rendering context
        if (renderingContextPushed) {
            ((MutableRenderingContext) this.renderingContext).pop();
        }
    }
}
Also used : StringWriter(java.io.StringWriter) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) XWikiException(com.xpn.xwiki.XWikiException) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

MutableRenderingContext (org.xwiki.rendering.internal.transformation.MutableRenderingContext)15 TransformationContext (org.xwiki.rendering.transformation.TransformationContext)8 XDOM (org.xwiki.rendering.block.XDOM)6 RenderingContext (org.xwiki.rendering.transformation.RenderingContext)4 StringReader (java.io.StringReader)3 HashMap (java.util.HashMap)3 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)3 WikiPrinter (org.xwiki.rendering.renderer.printer.WikiPrinter)3 Transformation (org.xwiki.rendering.transformation.Transformation)3 XWikiException (com.xpn.xwiki.XWikiException)2 Test (org.junit.Test)2 CompositeBlock (org.xwiki.rendering.block.CompositeBlock)2 Parser (org.xwiki.rendering.parser.Parser)2 StreamParser (org.xwiki.rendering.parser.StreamParser)2 BlockRenderer (org.xwiki.rendering.renderer.BlockRenderer)2 TransformationException (org.xwiki.rendering.transformation.TransformationException)2 XWikiContext (com.xpn.xwiki.XWikiContext)1 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)1 WikiSkin (com.xpn.xwiki.internal.skin.WikiSkin)1 ExternalServletURLFactory (com.xpn.xwiki.web.ExternalServletURLFactory)1