Search in sources :

Example 11 with WikiPrinter

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

the class EmailTemplateRenderer method renderPlainText.

/**
 * Render a block to plain text syntax.
 * @param block block to render
 * @return the plain text rendered version of the block
 */
public String renderPlainText(Block block) {
    // TODO: this does not work at all (templates enforce HTML syntax I guess)
    WikiPrinter printer = new DefaultWikiPrinter();
    plainTextBlockRenderer.render(block, printer);
    return printer.toString();
}
Also used : DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter)

Example 12 with WikiPrinter

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

the class DefaultNotificationRSSRenderer method renderNotification.

@Override
public SyndEntry renderNotification(CompositeEvent eventNotification) throws NotificationException {
    SyndEntry entry = new SyndEntryImpl();
    SyndContent entryDescription = new SyndContentImpl();
    // The users contained in the CompositeEvent are already stored in a Set, they are therefore necessarily unique
    List<SyndPerson> eventAuthors = new ArrayList<SyndPerson>();
    // Convert every author of the CompositeEvent to a SyndPerson and add it to the new entry
    for (DocumentReference author : eventNotification.getUsers()) {
        SyndPerson person = new SyndPersonImpl();
        person.setName(author.getName());
        eventAuthors.add(person);
    }
    entry.setAuthors(eventAuthors);
    // Define the GUID of the event
    entry.setUri(String.join("-", eventNotification.getEventIds()));
    // Set the entry title
    entry.setTitle(this.contextualLocalizationManager.getTranslationPlain(eventNotification.getEvents().get(0).getTitle(), eventNotification.getEvents().get(0).getDocumentTitle()));
    // Render the description (the main part) of the feed entry
    try {
        this.scriptContextManager.getCurrentScriptContext().setAttribute(COMPOSITE_EVENT_BUILDING_NAME, eventNotification, ScriptContext.ENGINE_SCOPE);
        // Try to get a template associated with the composite event
        Template template = this.templateManager.getTemplate(String.format("notification/rss/%s.vm", eventNotification.getType().replaceAll("\\/", ".")));
        // If no template is found, fallback on the default one
        if (template == null) {
            template = this.templateManager.getTemplate("notification/rss/default.vm");
        }
        XDOM descriptionXDOM = this.templateManager.execute(template);
        WikiPrinter printer = new DefaultWikiPrinter();
        blockRenderer.render(descriptionXDOM, printer);
        // Add the description to the entry
        entryDescription.setType("text/html");
        entryDescription.setValue(printer.toString());
        entry.setDescription(entryDescription);
    } catch (Exception e) {
        throw new NotificationException(String.format("Unable to render the description of the event [%s].", eventNotification), e);
    } finally {
        this.scriptContextManager.getCurrentScriptContext().removeAttribute(COMPOSITE_EVENT_BUILDING_NAME, ScriptContext.ENGINE_SCOPE);
    }
    // Dates are sorted in descending order in a CompositeEvent, the first date is then the most recent one
    entry.setUpdatedDate(eventNotification.getDates().get(0));
    return entry;
}
Also used : XDOM(org.xwiki.rendering.block.XDOM) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) SyndEntry(com.rometools.rome.feed.synd.SyndEntry) SyndContentImpl(com.rometools.rome.feed.synd.SyndContentImpl) ArrayList(java.util.ArrayList) NotificationException(org.xwiki.notifications.NotificationException) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) NotificationException(org.xwiki.notifications.NotificationException) Template(org.xwiki.template.Template) SyndPerson(com.rometools.rome.feed.synd.SyndPerson) SyndPersonImpl(com.rometools.rome.feed.synd.SyndPersonImpl) SyndContent(com.rometools.rome.feed.synd.SyndContent) SyndEntryImpl(com.rometools.rome.feed.synd.SyndEntryImpl) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 13 with WikiPrinter

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

the class DocumentSolrMetadataExtractorTest method getSimpleDocument.

@Test
public void getSimpleDocument() throws Exception {
    // 
    // Mock
    // 
    // ID
    String id = "wiki:Space.Name_" + Locale.ROOT.toString();
    SolrReferenceResolver documentSolrReferenceResolver = this.mocker.getInstance(SolrReferenceResolver.class, "document");
    when(documentSolrReferenceResolver.getId(documentReference)).thenReturn(id);
    // Full Name
    String fullName = "Space.Name";
    EntityReferenceSerializer<String> localEntityReferenceSerializer = this.mocker.registerMockComponent(EntityReferenceSerializer.TYPE_STRING, "local");
    when(localEntityReferenceSerializer.serialize(this.documentReference)).thenReturn(fullName);
    // Hierarchy
    when(localEntityReferenceSerializer.serialize(this.documentReference.getParent())).thenReturn("Path.To.Page");
    when(localEntityReferenceSerializer.serialize(this.documentReference.getParent().getParent())).thenReturn("Path.To");
    when(localEntityReferenceSerializer.serialize(this.documentReference.getParent().getParent().getParent())).thenReturn("Path");
    // Creator.
    DocumentReference creatorReference = new DocumentReference("wiki", "Space", "Creator");
    when(this.document.getCreatorReference()).thenReturn(creatorReference);
    String creatorStringReference = "wiki:Space.Creator";
    EntityReferenceSerializer<String> entityReferenceSerializer = this.mocker.registerMockComponent(EntityReferenceSerializer.TYPE_STRING, "default");
    when(entityReferenceSerializer.serialize(creatorReference)).thenReturn(creatorStringReference);
    String creatorDisplayName = "Crea Tor";
    when(this.xcontext.getWiki().getPlainUserName(creatorReference, this.xcontext)).thenReturn(creatorDisplayName);
    // Author.
    DocumentReference authorReference = new DocumentReference("wiki", "Space", "Author");
    when(this.document.getAuthorReference()).thenReturn(authorReference);
    String authorStringReference = "wiki:Space.Author";
    when(entityReferenceSerializer.serialize(authorReference)).thenReturn(authorStringReference);
    String authorDisplayName = "Au Thor";
    when(this.xcontext.getWiki().getPlainUserName(authorReference, this.xcontext)).thenReturn(authorDisplayName);
    // Creation Date
    Date creationDate = new Date();
    when(this.document.getCreationDate()).thenReturn(creationDate);
    // Date
    Date date = new Date();
    when(this.document.getContentUpdateDate()).thenReturn(date);
    // Version
    String version = "1.1";
    when(this.document.getVersion()).thenReturn(version);
    // Version summary
    String comment = "1.1 comment";
    when(this.document.getComment()).thenReturn(comment);
    // XObjects.
    when(this.document.getXObjects()).thenReturn(Collections.<DocumentReference, List<BaseObject>>emptyMap());
    // Title
    String title = "title";
    when(this.document.getRenderedTitle(any(), same(this.xcontext))).thenReturn(title);
    // Rendered Content
    final String renderedContent = "rendered content";
    BlockRenderer plainRenderer = this.mocker.registerMockComponent(BlockRenderer.class, "plain/1.0");
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            WikiPrinter printer = (WikiPrinter) args[1];
            printer.print(renderedContent);
            return null;
        }
    }).when(plainRenderer).render((Block) any(), any());
    // Raw Content
    String rawContent = "raw content";
    when(this.document.getContent()).thenReturn(rawContent);
    // 
    // Call
    // 
    SolrInputDocument solrDocument = this.mocker.getComponentUnderTest().getSolrDocument(this.documentReference);
    // 
    // Assert and verify
    // 
    assertEquals(id, solrDocument.getFieldValue(FieldUtils.ID));
    assertEquals(this.documentReference.getWikiReference().getName(), solrDocument.getFieldValue(FieldUtils.WIKI));
    assertEquals(Arrays.asList("Path", "To", "Page"), solrDocument.getFieldValues(FieldUtils.SPACES));
    assertEquals(this.documentReference.getName(), solrDocument.getFieldValue(FieldUtils.NAME));
    assertEquals(Arrays.asList("0/Path.", "1/Path.To.", "2/Path.To.Page."), solrDocument.getFieldValues(FieldUtils.SPACE_FACET));
    assertEquals(Arrays.asList("Path", "Path.To", "Path.To.Page"), solrDocument.getFieldValues(FieldUtils.SPACE_PREFIX));
    assertEquals(Locale.US.toString(), solrDocument.getFieldValue(FieldUtils.LOCALE));
    assertEquals(Locale.US.getLanguage(), solrDocument.getFieldValue(FieldUtils.LANGUAGE));
    Collection<?> actualLocales = solrDocument.getFieldValues(FieldUtils.LOCALES);
    // The order of the locales in the returned collection is nondeterministic.
    assertTrue(actualLocales.size() == 2 && actualLocales.contains("") && actualLocales.contains(Locale.US.toString()));
    assertEquals(this.document.isHidden(), solrDocument.getFieldValue(FieldUtils.HIDDEN));
    assertEquals(EntityType.DOCUMENT.name(), solrDocument.getFieldValue(FieldUtils.TYPE));
    assertEquals(fullName, solrDocument.getFieldValue(FieldUtils.FULLNAME));
    assertEquals(title, solrDocument.getFieldValue(FieldUtils.getFieldName(FieldUtils.TITLE, Locale.US)));
    assertEquals(rawContent, solrDocument.getFieldValue(FieldUtils.getFieldName(FieldUtils.DOCUMENT_RAW_CONTENT, Locale.US)));
    assertEquals(renderedContent, solrDocument.getFieldValue(FieldUtils.getFieldName(FieldUtils.DOCUMENT_RENDERED_CONTENT, Locale.US)));
    assertEquals(version, solrDocument.getFieldValue(FieldUtils.VERSION));
    assertEquals(comment, solrDocument.getFieldValue(FieldUtils.COMMENT));
    assertEquals(authorStringReference, solrDocument.getFieldValue(FieldUtils.AUTHOR));
    assertEquals(authorDisplayName, solrDocument.getFieldValue(FieldUtils.AUTHOR_DISPLAY));
    assertEquals(creatorStringReference, solrDocument.getFieldValue(FieldUtils.CREATOR));
    assertEquals(creatorDisplayName, solrDocument.getFieldValue(FieldUtils.CREATOR_DISPLAY));
    assertEquals(creationDate, solrDocument.getFieldValue(FieldUtils.CREATIONDATE));
    assertEquals(date, solrDocument.get(FieldUtils.DATE).getValue());
}
Also used : Date(java.util.Date) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) BaseObject(com.xpn.xwiki.objects.BaseObject) BlockRenderer(org.xwiki.rendering.renderer.BlockRenderer) SolrInputDocument(org.apache.solr.common.SolrInputDocument) SolrReferenceResolver(org.xwiki.search.solr.internal.reference.SolrReferenceResolver) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Example 14 with WikiPrinter

use of org.xwiki.rendering.renderer.printer.WikiPrinter 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 15 with WikiPrinter

use of org.xwiki.rendering.renderer.printer.WikiPrinter 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)

Aggregations

WikiPrinter (org.xwiki.rendering.renderer.printer.WikiPrinter)33 DefaultWikiPrinter (org.xwiki.rendering.renderer.printer.DefaultWikiPrinter)28 XDOM (org.xwiki.rendering.block.XDOM)12 BlockRenderer (org.xwiki.rendering.renderer.BlockRenderer)11 StringReader (java.io.StringReader)8 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)6 Parser (org.xwiki.rendering.parser.Parser)6 Test (org.junit.Test)5 Block (org.xwiki.rendering.block.Block)5 ParseException (org.xwiki.rendering.parser.ParseException)5 TransformationException (org.xwiki.rendering.transformation.TransformationException)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 TransformationContext (org.xwiki.rendering.transformation.TransformationContext)3 XWikiException (com.xpn.xwiki.XWikiException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 WordBlock (org.xwiki.rendering.block.WordBlock)2 Converter (org.xwiki.rendering.converter.Converter)2 TransformationManager (org.xwiki.rendering.transformation.TransformationManager)2