Search in sources :

Example 16 with DefaultWikiPrinter

use of org.xwiki.rendering.renderer.printer.DefaultWikiPrinter 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());
}
Also used : Expectations(org.jmock.Expectations) VelocityEngine(org.xwiki.velocity.VelocityEngine) Action(org.jmock.api.Action) Description(org.hamcrest.Description) Invocation(org.jmock.api.Invocation) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) VelocityContext(org.apache.velocity.VelocityContext) Reader(java.io.Reader) StringReader(java.io.StringReader) Properties(java.util.Properties) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) Execution(org.xwiki.context.Execution) VelocityManager(org.xwiki.velocity.VelocityManager) StringReader(java.io.StringReader) Converter(org.xwiki.rendering.converter.Converter) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer) Test(org.junit.Test)

Example 17 with DefaultWikiPrinter

use of org.xwiki.rendering.renderer.printer.DefaultWikiPrinter in project xwiki-platform by xwiki.

the class DefaultWikiMacroTest method testDefaultParameterValues.

/**
 * Test default parameter value injection.
 */
@Test
public void testDefaultParameterValues() 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) {
                }
            });
        }
    });
    List<WikiMacroParameterDescriptor> parameterDescriptors = Arrays.asList(new WikiMacroParameterDescriptor("param1", "This is param1", false, "default_value"));
    registerWikiMacro("wikimacro1", "{{velocity}}$xcontext.macro.params.param1 $xcontext.macro.params.paraM1{{/velocity}}", Syntax.XWIKI_2_0, parameterDescriptors);
    Converter converter = getComponentManager().getInstance(Converter.class);
    DefaultWikiPrinter printer = new DefaultWikiPrinter();
    converter.convert(new StringReader("{{wikimacro1/}}"), Syntax.XWIKI_2_0, Syntax.PLAIN_1_0, printer);
    Assert.assertEquals("default_value default_value", printer.toString());
}
Also used : Expectations(org.jmock.Expectations) VelocityEngine(org.xwiki.velocity.VelocityEngine) Action(org.jmock.api.Action) Description(org.hamcrest.Description) Invocation(org.jmock.api.Invocation) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) VelocityContext(org.apache.velocity.VelocityContext) Reader(java.io.Reader) StringReader(java.io.StringReader) Properties(java.util.Properties) WikiMacroParameterDescriptor(org.xwiki.rendering.macro.wikibridge.WikiMacroParameterDescriptor) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) Execution(org.xwiki.context.Execution) VelocityManager(org.xwiki.velocity.VelocityManager) StringReader(java.io.StringReader) Converter(org.xwiki.rendering.converter.Converter) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer) Test(org.junit.Test)

Example 18 with DefaultWikiPrinter

use of org.xwiki.rendering.renderer.printer.DefaultWikiPrinter in project xwiki-platform by xwiki.

the class EditableGadgetRenderer method getGadgetEditMetadata.

/**
 * @param gadget the gadget to decorate
 * @return the block containing the metadata that will allow clients to edit this gadget
 */
protected Block getGadgetEditMetadata(Gadget gadget) {
    GroupBlock metadataBlock = new GroupBlock();
    metadataBlock.setParameter(CLASS, METADATA);
    // look at the content of the gadget and store whether it's a macro or not
    boolean isMacro = gadget.getContent().size() == 1 && gadget.getContent().get(0) instanceof MacroMarkerBlock;
    GroupBlock isMacroBlock = new GroupBlock();
    isMacroBlock.setParameter(CLASS, "isMacro");
    isMacroBlock.addChild(new WordBlock(Boolean.toString(isMacro)));
    metadataBlock.addChild(isMacroBlock);
    if (isMacro) {
        // render the annotated macro call in the page, to be able to edit it. Only the macro call comments will be
        // rendered, since transformations are not ran, so there is no content in the macro. But annotation is
        // enough.
        GroupBlock renderedContentBlock = new GroupBlock();
        renderedContentBlock.setParameter(CLASS, "content");
        WikiPrinter printer = new DefaultWikiPrinter();
        BlockRenderer gadgetContentRenderer = getGadgetContentRenderer();
        gadgetContentRenderer.render(gadget.getContent(), printer);
        RawBlock rawBlock = new RawBlock(printer.toString(), getRawBlockSyntax(gadgetContentRenderer));
        renderedContentBlock.addChild(rawBlock);
        // render the title in the page as well, to be edited as source
        GroupBlock gadgetTitleBlock = new GroupBlock();
        gadgetTitleBlock.setParameter(CLASS, "title");
        // even if it's not a word, it's fine since it will be rendered in one piece
        gadgetTitleBlock.addChild(new WordBlock(gadget.getTitleSource()));
        metadataBlock.addChild(renderedContentBlock);
        metadataBlock.addChild(gadgetTitleBlock);
    }
    return metadataBlock;
}
Also used : DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) WordBlock(org.xwiki.rendering.block.WordBlock) RawBlock(org.xwiki.rendering.block.RawBlock) GroupBlock(org.xwiki.rendering.block.GroupBlock) MacroMarkerBlock(org.xwiki.rendering.block.MacroMarkerBlock) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) BlockRenderer(org.xwiki.rendering.renderer.BlockRenderer)

Example 19 with DefaultWikiPrinter

use of org.xwiki.rendering.renderer.printer.DefaultWikiPrinter in project xwiki-platform by xwiki.

the class UntypedEventListener method isValidated.

/**
 * Evaluate the given velocity template and return a boolean.
 *
 * @param event the event that should be bound to the script context
 * @param source the source object of the event that should be bound to the template
 * @param userReference a user reference used to build context
 * @param templateContent the velocity template that should be evaluated
 * @return true if the template evaluation returned «true» or if the template is empty
 */
private boolean isValidated(Event event, Object source, DocumentReference userReference, String templateContent) {
    try {
        // When no validation expression is defined, then it's always valid
        if (StringUtils.isBlank(templateContent)) {
            return true;
        }
        // Execute the template
        XDOM xdom = evaluateVelocity(event, source, userReference, templateContent);
        // First check if the "xreturn" attribute has been set
        Object xreturn = scriptContextManager.getCurrentScriptContext().getAttribute(XRETURN_BINDING);
        if (xreturn != null && xreturn instanceof Boolean) {
            return (Boolean) xreturn;
        }
        // Otherwise, for backward-compatibility, render the template to a string, and compare this
        // string with "true".
        WikiPrinter printer = new DefaultWikiPrinter();
        renderer.render(xdom, printer);
        String render = printer.toString().trim();
        return "true".equals(render);
    } catch (Exception e) {
        logger.warn("Unable to render a notification validation template.", e);
        return false;
    }
}
Also used : XDOM(org.xwiki.rendering.block.XDOM) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException)

Example 20 with DefaultWikiPrinter

use of org.xwiki.rendering.renderer.printer.DefaultWikiPrinter in project xwiki-platform by xwiki.

the class XWikiDocumentOutputFilterStream method begin.

private void begin(FilterEventParameters parameters) throws FilterException {
    DocumentReference documentReference = this.documentEntityResolver.resolve(this.currentEntityReference, getDefaultDocumentReference());
    if (this.entity == null) {
        this.entity = new XWikiDocument(documentReference, this.currentLocale);
    } else {
        this.entity.setDocumentReference(documentReference);
        this.entity.setLocale(this.currentLocale);
    }
    // Find default author
    DocumentReference defaultAuthorReference;
    if (this.properties.isAuthorSet()) {
        defaultAuthorReference = this.properties.getAuthor();
    } else {
        XWikiContext xcontext = xcontextProvider.get();
        defaultAuthorReference = xcontext != null ? xcontext.getUserReference() : null;
    }
    this.entity.setCreationDate(getDate(WikiDocumentFilter.PARAMETER_CREATION_DATE, this.currentLocaleParameters, null));
    this.entity.setCreatorReference(getUserReference(WikiDocumentFilter.PARAMETER_CREATION_AUTHOR, this.currentLocaleParameters, defaultAuthorReference));
    this.entity.setDefaultLocale(this.currentDefaultLocale);
    this.entity.setSyntax(getSyntax(WikiDocumentFilter.PARAMETER_SYNTAX, parameters, null));
    this.entity.setParentReference(getEntityReference(WikiDocumentFilter.PARAMETER_PARENT, parameters, null));
    this.entity.setCustomClass(getString(WikiDocumentFilter.PARAMETER_CUSTOMCLASS, parameters, null));
    this.entity.setTitle(getString(WikiDocumentFilter.PARAMETER_TITLE, parameters, null));
    this.entity.setDefaultTemplate(getString(WikiDocumentFilter.PARAMETER_DEFAULTTEMPLATE, parameters, null));
    this.entity.setValidationScript(getString(WikiDocumentFilter.PARAMETER_VALIDATIONSCRIPT, parameters, null));
    this.entity.setHidden(getBoolean(WikiDocumentFilter.PARAMETER_HIDDEN, parameters, false));
    this.entity.setMinorEdit(getBoolean(WikiDocumentFilter.PARAMETER_REVISION_MINOR, parameters, false));
    this.entity.setAuthorReference(getUserReference(WikiDocumentFilter.PARAMETER_REVISION_AUTHOR, parameters, defaultAuthorReference));
    this.entity.setContentAuthorReference(getUserReference(WikiDocumentFilter.PARAMETER_CONTENT_AUTHOR, parameters, defaultAuthorReference));
    String revisions = getString(XWikiWikiDocumentFilter.PARAMETER_JRCSREVISIONS, this.currentLocaleParameters, null);
    if (revisions != null) {
        try {
            this.entity.setDocumentArchive(revisions);
        } catch (XWikiException e) {
            throw new FilterException("Failed to set document archive", e);
        }
    }
    if (this.currentVersion != null && this.properties.isVersionPreserved()) {
        if (VALID_VERSION.matcher(this.currentVersion).matches()) {
            this.entity.setVersion(this.currentVersion);
        } else if (NumberUtils.isDigits(this.currentVersion)) {
            this.entity.setVersion(this.currentVersion + ".1");
        } else {
        // TODO: log something, probably a warning
        }
    }
    this.entity.setDate(getDate(WikiDocumentFilter.PARAMETER_REVISION_DATE, parameters, new Date()));
    this.entity.setComment(getString(WikiDocumentFilter.PARAMETER_REVISION_COMMENT, parameters, ""));
    this.entity.setContentUpdateDate(getDate(WikiDocumentFilter.PARAMETER_CONTENT_DATE, parameters, new Date()));
    if (this.contentListener != null) {
        // Remember the current rendering context target syntax
        this.previousTargetSyntax = this.renderingContext.getTargetSyntax();
    }
    if (parameters.containsKey(WikiDocumentFilter.PARAMETER_CONTENT)) {
        this.entity.setContent(getString(WikiDocumentFilter.PARAMETER_CONTENT, parameters, null));
        if (this.contentListener != null) {
            // Cancel any existing content listener
            this.currentWikiPrinter = null;
            this.contentListener.setWrappedListener(null);
        }
    } else if (this.contentListener != null) {
        if (this.properties != null && this.properties.getDefaultSyntax() != null) {
            this.entity.setSyntax(this.properties.getDefaultSyntax());
        } else {
            // Make sure to set the default syntax if none were provided
            this.entity.setSyntax(this.entity.getSyntax());
        }
        ComponentManager componentManager = this.componentManagerProvider.get();
        String syntaxString = this.entity.getSyntax().toIdString();
        if (componentManager.hasComponent(PrintRendererFactory.class, syntaxString)) {
            PrintRendererFactory rendererFactory;
            try {
                rendererFactory = componentManager.getInstance(PrintRendererFactory.class, syntaxString);
            } catch (ComponentLookupException e) {
                throw new FilterException(String.format("Failed to find PrintRendererFactory for syntax [%s]", this.entity.getSyntax()), e);
            }
            this.currentWikiPrinter = new DefaultWikiPrinter();
            ((MutableRenderingContext) this.renderingContext).setTargetSyntax(rendererFactory.getSyntax());
            this.contentListener.setWrappedListener(rendererFactory.createRenderer(this.currentWikiPrinter));
        }
    }
    // Initialize the class
    getBaseClassOutputFilterStream().setEntity(this.entity.getXClass());
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) ComponentManager(org.xwiki.component.manager.ComponentManager) XWikiContext(com.xpn.xwiki.XWikiContext) FilterException(org.xwiki.filter.FilterException) PrintRendererFactory(org.xwiki.rendering.renderer.PrintRendererFactory) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) Date(java.util.Date)

Aggregations

DefaultWikiPrinter (org.xwiki.rendering.renderer.printer.DefaultWikiPrinter)41 WikiPrinter (org.xwiki.rendering.renderer.printer.WikiPrinter)28 StringReader (java.io.StringReader)18 Test (org.junit.Test)12 Converter (org.xwiki.rendering.converter.Converter)12 XDOM (org.xwiki.rendering.block.XDOM)10 BlockRenderer (org.xwiki.rendering.renderer.BlockRenderer)8 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)7 Block (org.xwiki.rendering.block.Block)6 ParseException (org.xwiki.rendering.parser.ParseException)5 Parser (org.xwiki.rendering.parser.Parser)5 TransformationException (org.xwiki.rendering.transformation.TransformationException)4 XWikiException (com.xpn.xwiki.XWikiException)3 HashMap (java.util.HashMap)3 Expectations (org.jmock.Expectations)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 TransformationContext (org.xwiki.rendering.transformation.TransformationContext)3 XWikiContext (com.xpn.xwiki.XWikiContext)2 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)2 Reader (java.io.Reader)2