Search in sources :

Example 1 with ClassBlockMatcher

use of org.xwiki.rendering.block.match.ClassBlockMatcher in project OsmAnd-tools by osmandapp.

the class WikiDatabasePreparation method mainTest.

public static void mainTest(String[] args) throws ConversionException, ComponentLookupException, ParseException, IOException {
    EmbeddableComponentManager cm = new EmbeddableComponentManager();
    cm.initialize(WikiDatabasePreparation.class.getClassLoader());
    Parser parser = cm.getInstance(Parser.class, Syntax.MEDIAWIKI_1_0.toIdString());
    FileReader fr = new FileReader(new File("/Users/victorshcherb/Documents/b.src.html"));
    BufferedReader br = new BufferedReader(fr);
    String content = "";
    String s;
    while ((s = br.readLine()) != null) {
        content += s;
    }
    content = removeMacroBlocks(content, new HashMap<>());
    XDOM xdom = parser.parse(new StringReader(content));
    // Find all links and make them italic
    for (Block block : xdom.getBlocks(new ClassBlockMatcher(LinkBlock.class), Block.Axes.DESCENDANT)) {
        Block parentBlock = block.getParent();
        Block newBlock = new FormatBlock(Collections.<Block>singletonList(block), Format.ITALIC);
        parentBlock.replaceChild(newBlock, block);
    }
    // for (Block block : xdom.getBlocks(new ClassBlockMatcher(ParagraphBlock.class), Block.Axes.DESCENDANT)) {
    // ParagraphBlock b = (ParagraphBlock) block;
    // block.getParent().removeBlock(block);
    // }
    WikiPrinter printer = new DefaultWikiPrinter();
    // BlockRenderer renderer = cm.getInstance(BlockRenderer.class, Syntax.XHTML_1_0.toIdString());
    // renderer.render(xdom, printer);
    // System.out.println(printer.toString());
    Converter converter = cm.getInstance(Converter.class);
    // Convert input in XWiki Syntax 2.1 into XHTML. The result is stored in the printer.
    printer = new DefaultWikiPrinter();
    converter.convert(new FileReader(new File("/Users/victorshcherb/Documents/a.src.html")), Syntax.MEDIAWIKI_1_0, Syntax.XHTML_1_0, printer);
    System.out.println(printer.toString());
    final HTMLConverter nconverter = new HTMLConverter(false);
    String lang = "be";
    WikiModel wikiModel = new WikiModel("http://" + lang + ".wikipedia.com/wiki/${image}", "http://" + lang + ".wikipedia.com/wiki/${title}");
// String plainStr = wikiModel.render(nconverter, content);
// System.out.println(plainStr);
// downloadPage("https://be.m.wikipedia.org/wiki/%D0%93%D0%BE%D1%80%D0%B0%D0%B4_%D0%9C%D1%96%D0%BD%D1%81%D0%BA",
// "/Users/victorshcherb/Documents/a.wiki.html");
}
Also used : HTMLConverter(info.bliki.wiki.filter.HTMLConverter) XDOM(org.xwiki.rendering.block.XDOM) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FormatBlock(org.xwiki.rendering.block.FormatBlock) WikiModel(info.bliki.wiki.model.WikiModel) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) SAXParser(javax.xml.parsers.SAXParser) Parser(org.xwiki.rendering.parser.Parser) ClassBlockMatcher(org.xwiki.rendering.block.match.ClassBlockMatcher) LinkBlock(org.xwiki.rendering.block.LinkBlock) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) FormatBlock(org.xwiki.rendering.block.FormatBlock) LinkBlock(org.xwiki.rendering.block.LinkBlock) Block(org.xwiki.rendering.block.Block) HTMLConverter(info.bliki.wiki.filter.HTMLConverter) Converter(org.xwiki.rendering.converter.Converter) EmbeddableComponentManager(org.xwiki.component.embed.EmbeddableComponentManager) FileReader(java.io.FileReader) File(java.io.File)

Example 2 with ClassBlockMatcher

use of org.xwiki.rendering.block.match.ClassBlockMatcher in project xwiki-platform by xwiki.

the class DefaultOfficeResourceViewer method processImages.

/**
 * Processes all the image blocks in the given XDOM and changes image URL to point to a temporary file for those
 * images that are view artifacts.
 *
 * @param xdom the XDOM whose image blocks are to be processed
 * @param artifacts specify which of the image blocks should be processed; only the image blocks that were generated
 *            during the office import process should be processed
 * @param ownerDocumentReference specifies the document that owns the office file
 * @param resourceReference a reference to the office file that is being viewed; this reference is used to compute
 *            the path to the temporary directory holding the image artifacts
 * @param parameters the build parameters. Note that currently only {@code filterStyles} is supported and if "true"
 *            it means that styles will be filtered to the maximum and the focus will be put on importing only the
 * @return the set of temporary files corresponding to image artifacts
 */
private Set<File> processImages(XDOM xdom, Map<String, byte[]> artifacts, DocumentReference ownerDocumentReference, String resourceReference, Map<String, ?> parameters) {
    // Process all image blocks.
    Set<File> temporaryFiles = new HashSet<File>();
    List<ImageBlock> imgBlocks = xdom.getBlocks(new ClassBlockMatcher(ImageBlock.class), Block.Axes.DESCENDANT);
    for (ImageBlock imgBlock : imgBlocks) {
        String imageReference = imgBlock.getReference().getReference();
        // Check whether there is a corresponding artifact.
        if (artifacts.containsKey(imageReference)) {
            try {
                List<String> resourcePath = Arrays.asList(String.valueOf(parameters.hashCode()), imageReference);
                TemporaryResourceReference temporaryResourceReference = new TemporaryResourceReference(MODULE_NAME, resourcePath, ownerDocumentReference);
                // Write the image into a temporary file.
                File tempFile = this.temporaryResourceStore.createTemporaryFile(temporaryResourceReference, new ByteArrayInputStream(artifacts.get(imageReference)));
                // Create a URL image reference which links to above temporary image file.
                String temporaryResourceURL = this.urlTemporaryResourceReferenceSerializer.serialize(temporaryResourceReference).serialize();
                ResourceReference urlImageReference = new ResourceReference(temporaryResourceURL, ResourceType.PATH);
                urlImageReference.setTyped(true);
                // Replace the old image block with a new one that uses the above URL image reference.
                Block newImgBlock = new ImageBlock(urlImageReference, false, imgBlock.getParameters());
                imgBlock.getParent().replaceChild(Arrays.asList(newImgBlock), imgBlock);
                // Make sure the new image block is not inside an ExpandedMacroBlock whose's content syntax doesn't
                // support relative path resource references (we use relative paths to refer the temporary files).
                maybeFixExpandedMacroAncestor(newImgBlock);
                // Collect the temporary file so that it can be cleaned up when the view is disposed from cache.
                temporaryFiles.add(tempFile);
            } catch (Exception ex) {
                String message = "Error while processing artifact image [%s].";
                this.logger.error(String.format(message, imageReference), ex);
            }
        }
    }
    return temporaryFiles;
}
Also used : ImageBlock(org.xwiki.rendering.block.ImageBlock) InitializationException(org.xwiki.component.phase.InitializationException) CacheException(org.xwiki.cache.CacheException) TemporaryResourceReference(org.xwiki.resource.temporary.TemporaryResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) ClassBlockMatcher(org.xwiki.rendering.block.match.ClassBlockMatcher) MetaDataBlock(org.xwiki.rendering.block.MetaDataBlock) ExpandedMacroBlock(org.xwiki.rendering.block.ExpandedMacroBlock) ImageBlock(org.xwiki.rendering.block.ImageBlock) Block(org.xwiki.rendering.block.Block) TemporaryResourceReference(org.xwiki.resource.temporary.TemporaryResourceReference) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) File(java.io.File) HashSet(java.util.HashSet)

Example 3 with ClassBlockMatcher

use of org.xwiki.rendering.block.match.ClassBlockMatcher in project xwiki-platform by xwiki.

the class DefaultOfficeResourceViewer method maybeFixExpandedMacroAncestor.

private void maybeFixExpandedMacroAncestor(Block block) {
    ExpandedMacroBlock expandedMacro = block.getFirstBlock(new ClassBlockMatcher(ExpandedMacroBlock.class), Block.Axes.ANCESTOR_OR_SELF);
    if (expandedMacro != null) {
        Block parent = expandedMacro.getParent();
        if (!(parent instanceof MetaDataBlock) || !((MetaDataBlock) parent).getMetaData().contains(MODULE_NAME)) {
            MetaDataBlock metaData = new MetaDataBlock(Collections.<Block>emptyList());
            // Use a syntax that supports relative path resource references (we use relative paths to include the
            // temporary files).
            metaData.getMetaData().addMetaData(MetaData.SYNTAX, Syntax.XWIKI_2_1);
            metaData.getMetaData().addMetaData(MODULE_NAME, true);
            parent.replaceChild(metaData, expandedMacro);
            metaData.addChild(expandedMacro);
        }
    }
}
Also used : ExpandedMacroBlock(org.xwiki.rendering.block.ExpandedMacroBlock) ClassBlockMatcher(org.xwiki.rendering.block.match.ClassBlockMatcher) MetaDataBlock(org.xwiki.rendering.block.MetaDataBlock) ExpandedMacroBlock(org.xwiki.rendering.block.ExpandedMacroBlock) ImageBlock(org.xwiki.rendering.block.ImageBlock) Block(org.xwiki.rendering.block.Block) MetaDataBlock(org.xwiki.rendering.block.MetaDataBlock)

Example 4 with ClassBlockMatcher

use of org.xwiki.rendering.block.match.ClassBlockMatcher in project xwiki-platform by xwiki.

the class DefaultOfficeResourceViewerTest method testViewPresentation.

@Test
public void testViewPresentation() throws Exception {
    AttachmentResourceReference attachResourceRef = new AttachmentResourceReference("xwiki:Some.Page@presentation.odp");
    DocumentReference documentReference = new DocumentReference("wiki", "Some", "Page");
    AttachmentReference attachmentReference = new AttachmentReference("presentation.odp", documentReference);
    AttachmentReferenceResolver<String> attachmentReferenceResolver = mocker.getInstance(AttachmentReferenceResolver.TYPE_STRING, "current");
    when(attachmentReferenceResolver.resolve(attachResourceRef.getReference())).thenReturn(attachmentReference);
    when(documentAccessBridge.getAttachmentReferences(attachmentReference.getDocumentReference())).thenReturn(Arrays.asList(attachmentReference));
    when(documentAccessBridge.getAttachmentVersion(attachmentReference)).thenReturn("3.2");
    ByteArrayInputStream attachmentContent = new ByteArrayInputStream(new byte[256]);
    when(documentAccessBridge.getAttachmentContent(attachmentReference)).thenReturn(attachmentContent);
    ResourceReference imageReference = new ResourceReference("slide0.png", ResourceType.URL);
    ExpandedMacroBlock galleryMacro = new ExpandedMacroBlock("gallery", Collections.singletonMap("width", "300px"), null, false);
    galleryMacro.addChild(new ImageBlock(imageReference, true));
    XDOM xdom = new XDOM(Collections.<Block>singletonList(galleryMacro));
    Map<String, byte[]> artifacts = Collections.singletonMap("slide0.png", new byte[8]);
    XDOMOfficeDocument xdomOfficeDocument = new XDOMOfficeDocument(xdom, artifacts, mocker);
    PresentationBuilder presentationBuilder = mocker.getInstance(PresentationBuilder.class);
    when(presentationBuilder.build(attachmentContent, attachmentReference.getName(), documentReference)).thenReturn(xdomOfficeDocument);
    Map<String, ?> viewParameters = Collections.singletonMap("ownerDocument", documentReference);
    TemporaryResourceReference temporaryResourceReference = new TemporaryResourceReference("officeviewer", Arrays.asList(String.valueOf(viewParameters.hashCode()), "slide0.png"), documentReference);
    Type type = new DefaultParameterizedType(null, ResourceReferenceSerializer.class, TemporaryResourceReference.class, ExtendedURL.class);
    ResourceReferenceSerializer<TemporaryResourceReference, ExtendedURL> urlTemporaryResourceReferenceSerializer = mocker.getInstance(type, "standard/tmp");
    ExtendedURL extendedURL = new ExtendedURL(Arrays.asList("url", "to", "slide0.png"));
    when(urlTemporaryResourceReferenceSerializer.serialize(temporaryResourceReference)).thenReturn(extendedURL);
    XDOM output = this.mocker.getComponentUnderTest().createView(attachResourceRef, viewParameters);
    ImageBlock imageBlock = (ImageBlock) output.getBlocks(new ClassBlockMatcher(ImageBlock.class), Block.Axes.DESCENDANT).get(0);
    assertEquals("/url/to/slide0.png", imageBlock.getReference().getReference());
    galleryMacro = (ExpandedMacroBlock) output.getBlocks(new ClassBlockMatcher(ExpandedMacroBlock.class), Block.Axes.DESCENDANT).get(0);
    assertFalse(galleryMacro.getParent() instanceof XDOM);
    assertEquals(Syntax.XWIKI_2_1, ((MetaDataBlock) galleryMacro.getParent()).getMetaData().getMetaData(MetaData.SYNTAX));
    TemporaryResourceStore store = mocker.getInstance(TemporaryResourceStore.class);
    verify(store).createTemporaryFile(eq(temporaryResourceReference), any(InputStream.class));
}
Also used : AttachmentReference(org.xwiki.model.reference.AttachmentReference) XDOM(org.xwiki.rendering.block.XDOM) ImageBlock(org.xwiki.rendering.block.ImageBlock) AttachmentResourceReference(org.xwiki.rendering.listener.reference.AttachmentResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ExtendedURL(org.xwiki.url.ExtendedURL) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) ResourceType(org.xwiki.rendering.listener.reference.ResourceType) Type(java.lang.reflect.Type) TemporaryResourceReference(org.xwiki.resource.temporary.TemporaryResourceReference) ByteArrayInputStream(java.io.ByteArrayInputStream) ExpandedMacroBlock(org.xwiki.rendering.block.ExpandedMacroBlock) ClassBlockMatcher(org.xwiki.rendering.block.match.ClassBlockMatcher) PresentationBuilder(org.xwiki.officeimporter.builder.PresentationBuilder) TemporaryResourceStore(org.xwiki.resource.temporary.TemporaryResourceStore) TemporaryResourceReference(org.xwiki.resource.temporary.TemporaryResourceReference) AttachmentResourceReference(org.xwiki.rendering.listener.reference.AttachmentResourceReference) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) DocumentReference(org.xwiki.model.reference.DocumentReference) XDOMOfficeDocument(org.xwiki.officeimporter.document.XDOMOfficeDocument) MetaDataBlock(org.xwiki.rendering.block.MetaDataBlock) Test(org.junit.Test)

Example 5 with ClassBlockMatcher

use of org.xwiki.rendering.block.match.ClassBlockMatcher in project xwiki-platform by xwiki.

the class DefaultPresentationBuilderTest method build.

@Test
public void build() throws Exception {
    DocumentReference documentReference = new DocumentReference("wiki", Arrays.asList("Path", "To"), "Page");
    when(this.entityReferenceSerializer.serialize(documentReference)).thenReturn("wiki:Path.To.Page");
    DocumentModelBridge document = mock(DocumentModelBridge.class);
    DocumentAccessBridge dab = this.mocker.getInstance(DocumentAccessBridge.class);
    when(dab.getTranslatedDocumentInstance(documentReference)).thenReturn(document);
    when(document.getSyntax()).thenReturn(Syntax.XWIKI_2_1);
    InputStream officeFileStream = new ByteArrayInputStream("Presentation content".getBytes());
    Map<String, byte[]> artifacts = new HashMap<String, byte[]>();
    byte[] firstSlide = "first slide".getBytes();
    byte[] secondSlide = "second slide".getBytes();
    artifacts.put("img0.jpg", firstSlide);
    artifacts.put("img0.html", new byte[0]);
    artifacts.put("text0.html", new byte[0]);
    artifacts.put("img1.jpg", secondSlide);
    artifacts.put("img1.html", new byte[0]);
    artifacts.put("text1.html", new byte[0]);
    when(this.officeConverter.convert(Collections.singletonMap("file.odp", officeFileStream), "file.odp", "img0.html")).thenReturn(artifacts);
    HTMLCleanerConfiguration config = mock(HTMLCleanerConfiguration.class);
    when(this.officeHTMLCleaner.getDefaultConfiguration()).thenReturn(config);
    Document xhtmlDoc = XMLUtils.createDOMDocument();
    xhtmlDoc.appendChild(xhtmlDoc.createElement("html"));
    String presentationHTML = "<p><img src=\"file-slide0.jpg\"/></p><p><img src=\"file-slide1.jpg\"/></p>";
    when(this.officeHTMLCleaner.clean(any(Reader.class), eq(config))).then(returnMatchingDocument(presentationHTML, xhtmlDoc));
    XDOM galleryContent = new XDOM(Collections.<Block>emptyList());
    when(this.xhtmlParser.parse(any(Reader.class))).thenReturn(galleryContent);
    XDOMOfficeDocument result = this.mocker.getComponentUnderTest().build(officeFileStream, "file.odp", documentReference);
    verify(config).setParameters(Collections.singletonMap("targetDocument", "wiki:Path.To.Page"));
    Map<String, byte[]> expectedArtifacts = new HashMap<String, byte[]>();
    expectedArtifacts.put("file-slide0.jpg", firstSlide);
    expectedArtifacts.put("file-slide1.jpg", secondSlide);
    assertEquals(expectedArtifacts, result.getArtifacts());
    assertEquals("wiki:Path.To.Page", result.getContentDocument().getMetaData().getMetaData(MetaData.BASE));
    List<ExpandedMacroBlock> macros = result.getContentDocument().getBlocks(new ClassBlockMatcher(ExpandedMacroBlock.class), Block.Axes.CHILD);
    Assert.assertEquals(1, macros.size());
    Assert.assertEquals("gallery", macros.get(0).getId());
    Assert.assertEquals(galleryContent, macros.get(0).getChildren().get(0));
}
Also used : XDOM(org.xwiki.rendering.block.XDOM) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) DocumentAccessBridge(org.xwiki.bridge.DocumentAccessBridge) Reader(java.io.Reader) Document(org.w3c.dom.Document) XDOMOfficeDocument(org.xwiki.officeimporter.document.XDOMOfficeDocument) DocumentModelBridge(org.xwiki.bridge.DocumentModelBridge) ByteArrayInputStream(java.io.ByteArrayInputStream) ExpandedMacroBlock(org.xwiki.rendering.block.ExpandedMacroBlock) ClassBlockMatcher(org.xwiki.rendering.block.match.ClassBlockMatcher) DocumentReference(org.xwiki.model.reference.DocumentReference) XDOMOfficeDocument(org.xwiki.officeimporter.document.XDOMOfficeDocument) HTMLCleanerConfiguration(org.xwiki.xml.html.HTMLCleanerConfiguration) Test(org.junit.Test)

Aggregations

ClassBlockMatcher (org.xwiki.rendering.block.match.ClassBlockMatcher)16 XDOM (org.xwiki.rendering.block.XDOM)10 Block (org.xwiki.rendering.block.Block)6 LinkBlock (org.xwiki.rendering.block.LinkBlock)5 ResourceReference (org.xwiki.rendering.listener.reference.ResourceReference)5 HashMap (java.util.HashMap)4 Test (org.junit.Test)4 DocumentReference (org.xwiki.model.reference.DocumentReference)4 ExpandedMacroBlock (org.xwiki.rendering.block.ExpandedMacroBlock)4 ImageBlock (org.xwiki.rendering.block.ImageBlock)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 HeaderBlock (org.xwiki.rendering.block.HeaderBlock)3 MetaDataBlock (org.xwiki.rendering.block.MetaDataBlock)3 File (java.io.File)2 InputStream (java.io.InputStream)2 ToString (org.suigeneris.jrcs.util.ToString)2 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)2 XDOMOfficeDocument (org.xwiki.officeimporter.document.XDOMOfficeDocument)2 WikiDocument (org.xwiki.refactoring.WikiDocument)2 SplittingCriterion (org.xwiki.refactoring.splitter.criterion.SplittingCriterion)2