diff --git a/celements-component/pom.xml b/celements-component/pom.xml index d4ae5ee11..0f6098d51 100644 --- a/celements-component/pom.xml +++ b/celements-component/pom.xml @@ -74,16 +74,6 @@ org.xwiki.platform xwiki-core-shared-tests test - - - org.slf4j - slf4j-log4j12 - - - commons-logging - commons-logging - - - commons-logging - commons-logging - 1.1.1 - jakarta.ws.rs @@ -201,10 +201,6 @@ - - org.xwiki.platform - xwiki-core-xml - org.xwiki.platform xwiki-core-script @@ -213,10 +209,6 @@ org.xwiki.platform xwiki-core-bridge - - org.xwiki.platform - xwiki-core-rendering-xwiki - org.xwiki.platform xwiki-core-cache-api @@ -243,20 +235,6 @@ xwiki-core-captcha - - - org.xwiki.platform - xwiki-core-rendering-syntax-wikimodel - - runtime - - - org.xwiki.platform - xwiki-core-rendering-syntax-xwiki10 - - runtime - - diff --git a/celements-xwiki-core/src/main/java/com/xpn/xwiki/XWiki.java b/celements-xwiki-core/src/main/java/com/xpn/xwiki/XWiki.java index 058ed4a34..9ea4c45d9 100644 --- a/celements-xwiki-core/src/main/java/com/xpn/xwiki/XWiki.java +++ b/celements-xwiki-core/src/main/java/com/xpn/xwiki/XWiki.java @@ -261,11 +261,6 @@ public class XWiki implements EventListener { */ private static File tempDir = null; - /** - * List of configured syntax ids. - */ - private List configuredSyntaxes; - /** * Used to convert a proper Document Reference to string (standard form). */ @@ -405,10 +400,6 @@ protected void initXWiki() throws XWikiException { this.isReadOnly = ("yes".equalsIgnoreCase(ro) || "true".equalsIgnoreCase(ro) || "1".equalsIgnoreCase(ro)); - // Save the configured syntaxes - String syntaxes = Param("xwiki.rendering.syntaxes", "xwiki/1.0"); - this.configuredSyntaxes = Arrays.asList(StringUtils.split(syntaxes, " ,")); - Utils.getComponent(ObservationManager.class).addListener(this); LOGGER.debug("XWiki init done"); @@ -5472,17 +5463,20 @@ private void replaceAttachmentInPlace(XWikiDocument doc, XWikiAttachment attachm /** * @return the ids of configured syntaxes for this wiki (eg "xwiki/1.0", "xwiki/2.0", * "mediawiki/1.0", etc) + * @deprecated since 7.0 only syntax10 support in the future */ + @Deprecated(since = "7.0.", forRemoval = true) public List getConfiguredSyntaxes() { - return this.configuredSyntaxes; + return List.of(Syntax.XWIKI_1_0.toIdString()); } /** * @return the syntax id of the syntax to use when creating new documents. + * @deprecated since 7.0 only syntax10 support in the future */ + @Deprecated(since = "7.0.", forRemoval = true) public String getDefaultDocumentSyntax() { - // TODO: Fix this method to return a Syntax object instead of a String - return Utils.getComponent(CoreConfiguration.class).getDefaultDocumentSyntax().toIdString(); + return Syntax.XWIKI_1_0.toIdString(); } /** diff --git a/celements-xwiki-core/src/main/java/com/xpn/xwiki/api/XWiki.java b/celements-xwiki-core/src/main/java/com/xpn/xwiki/api/XWiki.java index ec0ee0a54..c336a9e19 100644 --- a/celements-xwiki-core/src/main/java/com/xpn/xwiki/api/XWiki.java +++ b/celements-xwiki-core/src/main/java/com/xpn/xwiki/api/XWiki.java @@ -2724,7 +2724,9 @@ public CriteriaService getCriteriaService() { /** * @return the ids of configured syntaxes for this wiki (eg "xwiki/1.0", "xwiki/2.0", * "mediawiki/1.0", etc) + * @deprecated since 7.0 only syntax10 support in the future */ + @Deprecated(since = "7.0.", forRemoval = true) public List getConfiguredSyntaxes() { return this.xwiki.getConfiguredSyntaxes(); } diff --git a/celements-xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java b/celements-xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java index 5df8f7544..bd96fe9a3 100644 --- a/celements-xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java +++ b/celements-xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java @@ -45,7 +45,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Stack; import java.util.TreeMap; import java.util.Vector; import java.util.function.Supplier; @@ -92,16 +91,9 @@ import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.listener.reference.ResourceReference; import org.xwiki.rendering.listener.reference.ResourceType; -import org.xwiki.rendering.parser.ParseException; -import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.renderer.BlockRenderer; -import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter; -import org.xwiki.rendering.renderer.printer.WikiPrinter; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.syntax.SyntaxFactory; -import org.xwiki.rendering.transformation.TransformationContext; -import org.xwiki.rendering.transformation.TransformationException; -import org.xwiki.rendering.transformation.TransformationManager; import org.xwiki.rendering.util.ParserUtils; import org.xwiki.velocity.VelocityManager; import org.xwiki.velocity.XWikiVelocityException; @@ -337,13 +329,6 @@ public class XWikiDocument implements DocumentModelBridge { */ private XWikiDocument originalDocument; - /** - * The document structure expressed as a tree of Block objects. We store it for performance - * reasons since parsing is a costly operation that we don't want to repeat whenever some code ask - * for the XDOM information. - */ - private XDOM xdom; - /** * Used to resolve a string into a proper Document Reference using the current document's * reference to fill the blanks. @@ -775,13 +760,10 @@ public void setContent(String content) { setWikiNode(null); } this.content = content; - - // invalidate parsed xdom - this.xdom = null; } public void setContent(XDOM content) throws XWikiException { - setContent(renderXDOM(content, getSyntax())); + setContent(content); } public String getRenderedContent(Syntax targetSyntax, XWikiContext context) @@ -1148,53 +1130,6 @@ private String getRenderedContentTitle10(XWikiContext context) { return title; } - /** - * Get the rendered version of the first or second level first found header content in the - * document content. - *
    - *
  • xwiki/1.0: the first found first or second level header content is rendered with - * {@link com.xpn.xwiki.render.XWikiRenderingEngine#interpretText(String, XWikiDocument, XWikiContext)}
  • - *
  • xwiki/2.0: the first found first or second level content is executed and rendered with - * renderer for the provided syntax
  • - *
- * - * @param outputSyntax - * the syntax to render to. This is not taken into account for xwiki/1.0 syntax. - * @param context - * the XWiki context - * @return the rendered version of the title. null or empty (when xwiki/1.0 syntax) string if none - * can be found - * @throws XWikiException - * failed to render content - */ - private String getRenderedContentTitle(Syntax outputSyntax, XWikiContext context) - throws XWikiException { - String title = null; - - // Protect against cycles. For example that cold happen with a call to getRenderedTitle on - // current document from - // a script in the first heading block title - Stack stackTrace = (Stack) context - .get("internal.getRenderedContentTitleStackTrace"); - if (stackTrace == null) { - stackTrace = new Stack<>(); - context.put("internal.getRenderedContentTitleStackTrace", stackTrace); - } else if (stackTrace.contains(getDocumentReference())) { - // TODO: generate an error message instead ? - return null; - } - stackTrace.push(getDocumentReference()); - - try { - // Extract and render the document title - title = getRenderedContentTitle10(context); - } finally { - stackTrace.pop(); - } - - return title; - } - /** * Get the rendered version of the title of the document. *
    @@ -1214,50 +1149,23 @@ private String getRenderedContentTitle(Syntax outputSyntax, XWikiContext context public String getRenderedTitle(Syntax outputSyntax, XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); - - try { - if (!StringUtils.isEmpty(title)) { - title = context.getWiki().getRenderingEngine().interpretText(title, this, context); - - // If there's been an error during the Velocity evaluation then consider that the title is - // empty as a - // fallback. - // TODO: Since interpretText() never throws an exception it's hard to know if there's been - // an error. - // Right now interpretText() returns some HTML when there's an error, so we need to check - // the returned - // result for some marker to decide if an error has occurred... Fix this by refactoring the - // whole - // system used for Velocity evaluation. - if (title.indexOf("
    defaultEntityReferenceSerializer.get().serialize(getDocumentReference())), e); } - try { // 2) If not, then try to extract the title from the first document section title - title = getRenderedContentTitle(outputSyntax, context); + title = getRenderedContentTitle10(context); } catch (Exception e) { LOG.warn("Failed to extract title from content of document [{}]", defer(() -> defaultEntityReferenceSerializer.get().serialize(getDocumentReference())), e); } - // 3) No title has been found, return the page name as the title if (StringUtils.isEmpty(title)) { title = getDocumentReference().getName(); } - return title; } @@ -5702,7 +5610,9 @@ public Vector getComments() { /** * @return the syntax of the document * @since 2.3M1 + * @deprecated since 7.0 only syntax10 support in the future */ + @Deprecated(since = "7.0.", forRemoval = true) public Syntax getSyntax() { return Syntax.XWIKI_1_0; } @@ -6842,18 +6752,11 @@ public void convertSyntax(Syntax targetSyntax, XWikiContext context) throws XWik } /** - * @return the XDOM conrrexponding to the document's string content. + * @deprecated since 7.0 */ + @Deprecated(since = "7.0", forRemoval = true) public XDOM getXDOM() { - if (this.xdom == null) { - try { - this.xdom = parseContent(getContent()); - } catch (XWikiException e) { - LOG.error("Failed to parse document content to XDOM", e); - } - } - - return this.xdom.clone(); + return null; } /** @@ -6919,147 +6822,6 @@ private boolean executeValidationScript(XWikiContext context, String validationS } } - /** - * Convert the passed content from the passed syntax to the passed new syntax. - * - * @param content - * the content to convert - * @param targetSyntax - * the new syntax after the conversion - * @param txContext - * the context when Transformation are executed or null if transformation shouldn't be - * executed - * @return the converted content in the new syntax - * @throws XWikiException - * if an exception occurred during the conversion process - * @since 2.4M2 - */ - private static String performSyntaxConversion(String content, Syntax targetSyntax, - TransformationContext txContext) - throws XWikiException { - try { - XDOM dom = parseContent(txContext.getSyntax().toIdString(), content); - - return performSyntaxConversion(dom, targetSyntax, txContext); - } catch (Exception e) { - throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, - XWikiException.ERROR_XWIKI_UNKNOWN, - "Failed to convert document to syntax [" + targetSyntax + "]", e); - } - } - - /** - * Convert the passed content from the passed syntax to the passed new syntax. - * - * @param content - * the content to convert - * @param currentSyntaxId - * the syntax of the current content to convert - * @param targetSyntax - * the new syntax after the conversion - * @return the converted content in the new syntax - * @throws XWikiException - * if an exception occurred during the conversion process - * @since 2.4M2 - */ - private static String performSyntaxConversion(String content, String currentSyntaxId, - Syntax targetSyntax) - throws XWikiException { - try { - XDOM dom = parseContent(currentSyntaxId, content); - - return performSyntaxConversion(dom, targetSyntax, null); - } catch (Exception e) { - throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, - XWikiException.ERROR_XWIKI_UNKNOWN, - "Failed to convert document to syntax [" + targetSyntax + "]", e); - } - } - - /** - * Convert the passed content from the passed syntax to the passed new syntax. - * - * @param content - * the XDOM content to convert, the XDOM can be modified during the transformation - * @param targetSyntax - * the new syntax after the conversion - * @param txContext - * the context when Transformation are executed or null if transformation shouldn't be - * executed - * @return the converted content in the new syntax - * @throws XWikiException - * if an exception occurred during the conversion process - * @since 2.4M2 - */ - private static String performSyntaxConversion(XDOM content, Syntax targetSyntax, - TransformationContext txContext) - throws XWikiException { - try { - if (txContext != null) { - // Transform XDOM - TransformationManager transformations = Utils.getComponent(TransformationManager.class); - if (txContext.getXDOM() == null) { - txContext.setXDOM(content); - } - try { - transformations.performTransformations(content, txContext); - } catch (TransformationException te) { - // An error happened during one of the transformations. Since the error has been logged - // continue - // TODO: We should have a visual clue for the user in the future to let him know something - // didn't work as expected. - } - } - - // Render XDOM - return renderXDOM(content, targetSyntax); - } catch (Exception e) { - throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, - XWikiException.ERROR_XWIKI_UNKNOWN, - "Failed to convert document to syntax [" + targetSyntax + "]", e); - } - } - - /** - * Render privided XDOM into content of the provided syntax identifier. - * - * @param content - * the XDOM content to render - * @param targetSyntax - * the syntax identifier of the rendered content - * @return the rendered content - * @throws XWikiException - * if an exception occurred during the rendering process - */ - private static String renderXDOM(XDOM content, Syntax targetSyntax) throws XWikiException { - try { - BlockRenderer renderer = Utils.getComponent(BlockRenderer.class, targetSyntax.toIdString()); - WikiPrinter printer = new DefaultWikiPrinter(); - renderer.render(content, printer); - return printer.toString(); - } catch (Exception e) { - throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, - XWikiException.ERROR_XWIKI_UNKNOWN, - "Failed to render document to syntax [" + targetSyntax + "]", e); - } - } - - private XDOM parseContent(String content) throws XWikiException { - return parseContent(getSyntaxId(), content); - } - - private static XDOM parseContent(String syntaxId, String content) throws XWikiException { - try { - Parser parser = Utils.getComponent(Parser.class, syntaxId); - - return parser.parse(new StringReader(content)); - } catch (ParseException e) { - throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, - XWikiException.ERROR_XWIKI_UNKNOWN, - "Failed to parse content of syntax [" + syntaxId + "]", e); - } - } - private Syntax getDefaultDocumentSyntax() { return Syntax.XWIKI_1_0; } diff --git a/celements-xwiki-core/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java b/celements-xwiki-core/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java index 705007a49..2735729a6 100644 --- a/celements-xwiki-core/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java +++ b/celements-xwiki-core/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java @@ -225,7 +225,7 @@ public void testGetDisplayWhenNoTitleButSectionExists() { /** * Verify that if an error happens when evaluation the title, we fallback to the computed title. */ - public void testGetDisplayTitleWhenVelocityError() { + public void testGetDisplayTitleWhenVelocityError() throws Exception { this.document.setContent("Some content"); this.document.setTitle("some content that generate a velocity error"); expect(this.mockXWikiRenderingEngine.interpretText(EasyMock.isA(String.class), diff --git a/celements-xwiki-rendering-api/pom.xml b/celements-xwiki-rendering-api/pom.xml index da94e97ad..fc5386266 100644 --- a/celements-xwiki-rendering-api/pom.xml +++ b/celements-xwiki-rendering-api/pom.xml @@ -75,6 +75,12 @@ 7.0-SNAPSHOT provided + + com.celements + celements-xwiki-xml + 7.0-SNAPSHOT + provided + com.celements celements-servlet @@ -125,11 +131,6 @@ xwiki-core-bridge provided - - org.xwiki.platform - xwiki-core-xml - provided - org.dom4j dom4j diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/ConversionException.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/ConversionException.java deleted file mode 100644 index a4fec547d..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/ConversionException.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.converter; - -/** - * Encapsulate a conversion error. - * - * @version $Id$ - * @since 2.0M3 - */ -public class ConversionException extends Exception { - - /** - * Class ID for serialization. - */ - private static final long serialVersionUID = 1L; - - /** - * Construct a new ParseException with the specified detail message. - * - * @param message - * The detailed message. This can later be retrieved by the Throwable.getMessage() - * method. - */ - public ConversionException(String message) { - super(message); - } - - /** - * Construct a new ParseException with the specified detail message and cause. - * - * @param message - * The detailed message. This can later be retrieved by the Throwable.getMessage() - * method. - * @param throwable - * the cause. This can be retrieved later by the Throwable.getCause() method. (A null - * value is permitted, - * and indicates that the cause is nonexistent or unknown.) - */ - public ConversionException(String message, Throwable throwable) { - super(message, throwable); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/Converter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/Converter.java deleted file mode 100644 index c023971ca..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/converter/Converter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.converter; - -import java.io.Reader; -import org.xwiki.component.annotation.ComponentRole; -import org.xwiki.rendering.syntax.Syntax; -import org.xwiki.rendering.renderer.printer.WikiPrinter; - -/** - * Convert source content in a given Syntax to another Syntax. - * - * @version $Id$ - * @since 2.0M3 - */ -@ComponentRole -public interface Converter { - - /** - * Converts content from a Syntax to another and execute all registered Macro Transformations on - * the parsed content. - * - * @param source - * the content to be converted - * @param sourceSyntax - * the Syntax in which the content is represented - * @param targetSyntax - * the Syntax to which to convert to - * @param printer - * the printer that will receive the result of the conversion - * @throws ConversionException - * in case of a conversion error (invalid Syntax, etc) - */ - void convert(Reader source, Syntax sourceSyntax, Syntax targetSyntax, WikiPrinter printer) - throws ConversionException; -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/converter/DefaultConverter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/converter/DefaultConverter.java deleted file mode 100644 index e60fec698..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/converter/DefaultConverter.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.xwiki.rendering.internal.converter; - -import java.io.Reader; -import org.xwiki.component.annotation.Component; -import org.xwiki.component.annotation.Requirement; -import org.xwiki.component.manager.ComponentLookupException; -import org.xwiki.component.manager.ComponentManager; -import org.xwiki.rendering.block.XDOM; -import org.xwiki.rendering.converter.ConversionException; -import org.xwiki.rendering.converter.Converter; -import org.xwiki.rendering.parser.ParseException; -import org.xwiki.rendering.parser.Parser; -import org.xwiki.rendering.syntax.Syntax; -import org.xwiki.rendering.renderer.BlockRenderer; -import org.xwiki.rendering.renderer.printer.WikiPrinter; -import org.xwiki.rendering.transformation.TransformationContext; -import org.xwiki.rendering.transformation.TransformationException; -import org.xwiki.rendering.transformation.TransformationManager; - -/** - * Default implementation for {@link Converter}. - * - * @version $Id$ - */ -@Component -public class DefaultConverter implements Converter { - - /** - * Used to lookup parser and renderer. - */ - @Requirement - private ComponentManager componentManager; - - /** - * Used to execute transformations. - */ - @Requirement - private TransformationManager transformationManager; - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.converter.Converter#convert(java.io.Reader, - * org.xwiki.rendering.syntax.Syntax, - * org.xwiki.rendering.syntax.Syntax, org.xwiki.rendering.renderer.printer.WikiPrinter) - */ - public void convert(Reader source, Syntax sourceSyntax, Syntax targetSyntax, WikiPrinter printer) - throws ConversionException { - // Step 1: Find the parser and generate a XDOM - XDOM xdom; - try { - Parser parser = this.componentManager.lookup(Parser.class, sourceSyntax.toIdString()); - xdom = parser.parse(source); - } catch (ComponentLookupException e) { - throw new ConversionException("Failed to locate Parser for syntax [" + sourceSyntax + "]", e); - } catch (ParseException e) { - throw new ConversionException("Failed to parse input source", e); - } - - // Step 2: Run transformations - try { - TransformationContext context = new TransformationContext(xdom, sourceSyntax); - this.transformationManager.performTransformations(xdom, context); - } catch (TransformationException e) { - throw new ConversionException("Failed to execute some transformations", e); - } - - // Step 3: Locate the Renderer and render the content in the passed printer - BlockRenderer renderer; - try { - renderer = this.componentManager.lookup(BlockRenderer.class, targetSyntax.toIdString()); - } catch (ComponentLookupException e) { - throw new ConversionException("Failed to locate Renderer for syntax [" + targetSyntax + "]", - e); - } - renderer.render(xdom, printer); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/AbstractBlockParser.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/AbstractBlockParser.java deleted file mode 100644 index 37318c70e..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/AbstractBlockParser.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.parser; - -import java.io.Reader; - -import org.xwiki.component.annotation.Requirement; -import org.xwiki.component.manager.ComponentLookupException; -import org.xwiki.component.manager.ComponentManager; -import org.xwiki.rendering.block.XDOM; -import org.xwiki.rendering.parser.ParseException; -import org.xwiki.rendering.parser.Parser; -import org.xwiki.rendering.parser.StreamParser; - -/** - * Common code for {@link Parser} implementation that produce a {@link XDOM} from - * {@link StreamParser}. - * - * @version $Id$ - * @since 2.1M1 - */ -public abstract class AbstractBlockParser implements Parser { - - /** - * Used to lookup the {@link StreamParser} for the syntax. - */ - @Requirement - private ComponentManager componentManager; - - /** - * @return the {@link StreamParser} to use to parser the input content - */ - protected StreamParser getStreamParser() { - StreamParser streamParser; - try { - streamParser = this.componentManager.lookup(StreamParser.class, getSyntax().toIdString()); - } catch (ComponentLookupException e) { - throw new RuntimeException("Failed to create [" + getSyntax().toString() + "] renderer", e); - } - - return streamParser; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.parser.Parser#parse(java.io.Reader) - */ - public XDOM parse(Reader source) throws ParseException { - XDOMGeneratorListener listener = new XDOMGeneratorListener(); - - getStreamParser().parse(source, listener); - - return listener.getXDOM(); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextBlockParser.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextBlockParser.java deleted file mode 100644 index d1d138e6e..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextBlockParser.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.parser; - -import org.xwiki.component.annotation.Component; -import org.xwiki.rendering.syntax.Syntax; - -/** - * Plain Text Parser to convert a text source into a XDOM object. - * - * @version $Id$ - * @since 2.1M1 - */ -@Component("plain/1.0") -public class PlainTextBlockParser extends AbstractBlockParser { - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.parser.Parser#getSyntax() - */ - public Syntax getSyntax() { - return Syntax.PLAIN_1_0; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextStreamParser.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextStreamParser.java deleted file mode 100644 index 28396d72d..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/PlainTextStreamParser.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.parser; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.regex.Pattern; - -import org.xwiki.component.annotation.Component; -import org.xwiki.rendering.listener.Listener; -import org.xwiki.rendering.parser.ParseException; -import org.xwiki.rendering.parser.StreamParser; -import org.xwiki.rendering.syntax.Syntax; - -/** - * Plain Text Parser to convert a text source into a events. - * - * @version $Id$ - * @since 2.1M1 - */ -@Component("plain/1.0") -public class PlainTextStreamParser implements StreamParser { - - /** - * The characters which are considered as "special" symbols for - * {@link org.xwiki.rendering.block.SpecialSymbolBlock} - * . - */ - public static final Pattern SPECIALSYMBOL_PATTERN = Pattern - .compile("[!\"#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]"); - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.parser.Parser#getSyntax() - */ - public Syntax getSyntax() { - return Syntax.PLAIN_1_0; - } - - /** - * Read a single char from an Reader source. - * - * @param source - * the input to read from - * @return the char read - * @throws ParseException - * in case of reading error - */ - private int readChar(Reader source) throws ParseException { - int c; - - try { - c = source.read(); - } catch (IOException e) { - throw new ParseException("Failed to read input source", e); - } - - return c; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.parser.StreamParser#parse(java.io.Reader, - * org.xwiki.rendering.listener.Listener) - */ - public void parse(Reader source, Listener listener) throws ParseException { - StringBuffer word = new StringBuffer(); - BufferedReader bufferedSource = new BufferedReader(source); - int charAsInt; - - listener.beginParagraph(Listener.EMPTY_PARAMETERS); - - while ((charAsInt = readChar(bufferedSource)) != -1) { - char c = (char) charAsInt; - if (c == '\n') { - if (word.length() > 0) { - listener.onWord(word.toString()); - } - listener.onNewLine(); - - word.setLength(0); - } else if (c == '\r') { - // Do nothing, skip it - } else if (c == ' ') { - if (word.length() > 0) { - listener.onWord(word.toString()); - } - listener.onSpace(); - - word.setLength(0); - } else if (SPECIALSYMBOL_PATTERN.matcher(String.valueOf(c)).matches()) { - if (word.length() > 0) { - listener.onWord(word.toString()); - } - listener.onSpecialSymbol(c); - - word.setLength(0); - } else { - word.append(c); - } - } - - if (word.length() > 0) { - listener.onWord(word.toString()); - } - - listener.endParagraph(Listener.EMPTY_PARAMETERS); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/XDOMGeneratorListener.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/XDOMGeneratorListener.java deleted file mode 100644 index 5fccef087..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/XDOMGeneratorListener.java +++ /dev/null @@ -1,579 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.parser; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import org.xwiki.rendering.block.AbstractBlock; -import org.xwiki.rendering.block.Block; -import org.xwiki.rendering.block.BulletedListBlock; -import org.xwiki.rendering.block.DefinitionDescriptionBlock; -import org.xwiki.rendering.block.DefinitionListBlock; -import org.xwiki.rendering.block.DefinitionTermBlock; -import org.xwiki.rendering.block.EmptyLinesBlock; -import org.xwiki.rendering.block.FormatBlock; -import org.xwiki.rendering.block.GroupBlock; -import org.xwiki.rendering.block.HeaderBlock; -import org.xwiki.rendering.block.HorizontalLineBlock; -import org.xwiki.rendering.block.IdBlock; -import org.xwiki.rendering.block.ImageBlock; -import org.xwiki.rendering.block.LinkBlock; -import org.xwiki.rendering.block.ListItemBlock; -import org.xwiki.rendering.block.MacroBlock; -import org.xwiki.rendering.block.MacroMarkerBlock; -import org.xwiki.rendering.block.NewLineBlock; -import org.xwiki.rendering.block.NumberedListBlock; -import org.xwiki.rendering.block.ParagraphBlock; -import org.xwiki.rendering.block.QuotationBlock; -import org.xwiki.rendering.block.QuotationLineBlock; -import org.xwiki.rendering.block.RawBlock; -import org.xwiki.rendering.block.SectionBlock; -import org.xwiki.rendering.block.SpaceBlock; -import org.xwiki.rendering.block.SpecialSymbolBlock; -import org.xwiki.rendering.block.TableBlock; -import org.xwiki.rendering.block.TableCellBlock; -import org.xwiki.rendering.block.TableHeadCellBlock; -import org.xwiki.rendering.block.TableRowBlock; -import org.xwiki.rendering.block.VerbatimBlock; -import org.xwiki.rendering.block.WordBlock; -import org.xwiki.rendering.block.XDOM; -import org.xwiki.rendering.listener.Format; -import org.xwiki.rendering.listener.HeaderLevel; -import org.xwiki.rendering.listener.reference.ResourceReference; -import org.xwiki.rendering.listener.ListType; -import org.xwiki.rendering.listener.Listener; -import org.xwiki.rendering.syntax.Syntax; - -/** - * Produce a {@link XDOM} based on events. - * - * @version $Id$ - * @since 2.1M1 - */ -public class XDOMGeneratorListener implements Listener { - - private Stack stack = new Stack(); - - private final MarkerBlock marker = new MarkerBlock(); - - private static class MarkerBlock extends AbstractBlock { - - /** - * {@inheritDoc} - * - * @see AbstractBlock#traverse(Listener) - */ - public void traverse(Listener listener) { - // Nothing to do since this block is only used as a marker. - } - } - - public XDOM getXDOM() { - return new XDOM(generateListFromStack()); - } - - private List generateListFromStack() { - List blocks = new ArrayList(); - while (!this.stack.empty()) { - if (this.stack.peek() != this.marker) { - blocks.add(this.stack.pop()); - } else { - this.stack.pop(); - break; - } - } - Collections.reverse(blocks); - return blocks; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginDefinitionDescription() - */ - public void beginDefinitionDescription() { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginDefinitionList(java.util.Map) - */ - public void beginDefinitionList(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginDefinitionTerm() - */ - public void beginDefinitionTerm() { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginDocument(java.util.Map) - */ - public void beginDocument(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginFormat(org.xwiki.rendering.listener.Format, - * java.util.Map) - */ - public void beginFormat(Format format, Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginGroup(java.util.Map) - */ - public void beginGroup(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginHeader(org.xwiki.rendering.listener.HeaderLevel, - * java.lang.String, java.util.Map) - */ - public void beginHeader(HeaderLevel level, String id, Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginList(org.xwiki.rendering.listener.ListType, - * java.util.Map) - */ - public void beginList(ListType listType, Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginListItem() - */ - public void beginListItem() { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginMacroMarker(java.lang.String, java.util.Map, - * java.lang.String, - * boolean) - */ - public void beginMacroMarker(String name, Map macroParameters, String content, - boolean isInline) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginParagraph(java.util.Map) - */ - public void beginParagraph(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginQuotation(java.util.Map) - */ - public void beginQuotation(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginQuotationLine() - */ - public void beginQuotationLine() { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginSection(java.util.Map) - */ - public void beginSection(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginTable(java.util.Map) - */ - public void beginTable(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginTableCell(java.util.Map) - */ - public void beginTableCell(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginTableHeadCell(java.util.Map) - */ - public void beginTableHeadCell(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginTableRow(java.util.Map) - */ - public void beginTableRow(Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.LinkListener#beginLink(org.xwiki.rendering.listener.reference.ResourceReference - * , boolean, java.util.Map) - */ - public void beginLink(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - this.stack.push(this.marker); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endDefinitionDescription() - */ - public void endDefinitionDescription() { - this.stack.push(new DefinitionDescriptionBlock(generateListFromStack())); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endDefinitionList(java.util.Map) - */ - public void endDefinitionList(Map parameters) { - this.stack.push(new DefinitionListBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endDefinitionTerm() - */ - public void endDefinitionTerm() { - this.stack.push(new DefinitionTermBlock(generateListFromStack())); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endDocument(java.util.Map) - */ - public void endDocument(Map parameters) { - // Do nothing. This is supposed to append only once for the hole document - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endFormat(org.xwiki.rendering.listener.Format, - * java.util.Map) - */ - public void endFormat(Format format, Map parameters) { - this.stack.push(new FormatBlock(generateListFromStack(), format, parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endGroup(java.util.Map) - */ - public void endGroup(Map parameters) { - this.stack.push(new GroupBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endHeader(org.xwiki.rendering.listener.HeaderLevel, - * java.lang.String, - * java.util.Map) - */ - public void endHeader(HeaderLevel level, String id, Map parameters) { - this.stack.push(new HeaderBlock(generateListFromStack(), level, parameters, id)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endList(org.xwiki.rendering.listener.ListType, - * java.util.Map) - */ - public void endList(ListType listType, Map parameters) { - if (listType == ListType.BULLETED) { - this.stack.push(new BulletedListBlock(generateListFromStack(), parameters)); - } else { - this.stack.push(new NumberedListBlock(generateListFromStack(), parameters)); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endListItem() - */ - public void endListItem() { - this.stack.push(new ListItemBlock(generateListFromStack())); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endMacroMarker(java.lang.String, java.util.Map, - * java.lang.String, - * boolean) - */ - public void endMacroMarker(String name, Map macroParameters, String content, - boolean isInline) { - this.stack.push( - new MacroMarkerBlock(name, macroParameters, content, generateListFromStack(), isInline)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endParagraph(java.util.Map) - */ - public void endParagraph(Map parameters) { - this.stack.push(new ParagraphBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endQuotation(java.util.Map) - */ - public void endQuotation(Map parameters) { - this.stack.push(new QuotationBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endQuotationLine() - */ - public void endQuotationLine() { - this.stack.push(new QuotationLineBlock(generateListFromStack())); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endSection(java.util.Map) - */ - public void endSection(Map parameters) { - this.stack.push(new SectionBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endTable(java.util.Map) - */ - public void endTable(Map parameters) { - this.stack.push(new TableBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endTableCell(java.util.Map) - */ - public void endTableCell(Map parameters) { - this.stack.push(new TableCellBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endTableHeadCell(java.util.Map) - */ - public void endTableHeadCell(Map parameters) { - this.stack.push(new TableHeadCellBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#endTableRow(java.util.Map) - */ - public void endTableRow(Map parameters) { - this.stack.push(new TableRowBlock(generateListFromStack(), parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.LinkListener#endLink(org.xwiki.rendering.listener.reference.ResourceReference - * , - * boolean, java.util.Map) - */ - public void endLink(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - this.stack - .push(new LinkBlock(generateListFromStack(), reference, isFreeStandingURI, parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onEmptyLines(int) - */ - public void onEmptyLines(int count) { - this.stack.push(new EmptyLinesBlock(count)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onHorizontalLine(java.util.Map) - */ - public void onHorizontalLine(Map parameters) { - this.stack.push(new HorizontalLineBlock(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onId(java.lang.String) - */ - public void onId(String name) { - this.stack.push(new IdBlock(name)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onMacro(java.lang.String, java.util.Map, - * java.lang.String, boolean) - */ - public void onMacro(String id, Map macroParameters, String content, - boolean isInline) { - this.stack.push(new MacroBlock(id, macroParameters, content, isInline)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onNewLine() - */ - public void onNewLine() { - this.stack.push(new NewLineBlock()); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onRawText(java.lang.String, - * org.xwiki.rendering.syntax.Syntax) - */ - public void onRawText(String rawContent, Syntax syntax) { - this.stack.push(new RawBlock(rawContent, syntax)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onSpace() - */ - public void onSpace() { - this.stack.push(new SpaceBlock()); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onSpecialSymbol(char) - */ - public void onSpecialSymbol(char symbol) { - this.stack.push(new SpecialSymbolBlock(symbol)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onVerbatim(java.lang.String, boolean, java.util.Map) - */ - public void onVerbatim(String protectedString, boolean isInline, Map parameters) { - this.stack.push(new VerbatimBlock(protectedString, parameters, isInline)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#onWord(java.lang.String) - */ - public void onWord(String word) { - this.stack.push(new WordBlock(word)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.ImageListener#onImage(org.xwiki.rendering.listener.reference.ResourceReference - * , boolean, java.util.Map) - */ - public void onImage(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - this.stack.push(new ImageBlock(reference, isFreeStandingURI, parameters)); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractBlockRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractBlockRenderer.java deleted file mode 100644 index bf698e30b..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractBlockRenderer.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer; - -import java.util.Collection; -import java.util.Collections; -import org.xwiki.rendering.block.Block; -import org.xwiki.rendering.renderer.BlockRenderer; -import org.xwiki.rendering.renderer.PrintRendererFactory; -import org.xwiki.rendering.renderer.printer.WikiPrinter; -import org.xwiki.rendering.renderer.PrintRenderer; - -/** - * Common code for BlockRender implementation that uses Print Renderer Factory. - * - * @version $Id$ - * @since 2.0M3 - */ -public abstract class AbstractBlockRenderer implements BlockRenderer { - - /** - * @return provide the factory to use to create a new {@link PrintRenderer}. - */ - protected abstract PrintRendererFactory getPrintRendererFactory(); - - /** - * {@inheritDoc} - * - * @see BlockRenderer#render(org.xwiki.rendering.block.Block, - * org.xwiki.rendering.renderer.printer.WikiPrinter) - */ - public void render(Block block, WikiPrinter printer) { - render(Collections.singletonList(block), printer); - } - - /** - * {@inheritDoc} - * - * @see BlockRenderer#render(java.util.Collection, - * org.xwiki.rendering.renderer.printer.WikiPrinter) - */ - public void render(Collection blocks, WikiPrinter printer) { - PrintRenderer renderer = getPrintRendererFactory().createRenderer(printer); - for (Block block : blocks) { - block.traverse(renderer); - } - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractPrintRendererFactory.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractPrintRendererFactory.java deleted file mode 100644 index 37d4b5566..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/AbstractPrintRendererFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer; - -import org.xwiki.component.annotation.Requirement; -import org.xwiki.component.manager.ComponentLookupException; -import org.xwiki.component.manager.ComponentManager; -import org.xwiki.rendering.renderer.PrintRenderer; -import org.xwiki.rendering.renderer.PrintRendererFactory; -import org.xwiki.rendering.renderer.printer.WikiPrinter; - -/** - * Common code for {@link org.xwiki.rendering.renderer.PrintRendererFactory}, implements the logic - * to lookup and call - * the matching Print Renderer. - * - * @version $Id$ - * @since 2.0M3 - */ -public abstract class AbstractPrintRendererFactory implements PrintRendererFactory { - - /** - * Used to lookup the {@link PrintRenderer}. - */ - @Requirement - private ComponentManager componentManager; - - /** - * {@inheritDoc} - * - * @see PrintRendererFactory#createRenderer(org.xwiki.rendering.renderer.printer.WikiPrinter) - */ - public PrintRenderer createRenderer(WikiPrinter printer) { - PrintRenderer renderer; - try { - renderer = this.componentManager.lookup(PrintRenderer.class, getSyntax().toIdString()); - } catch (ComponentLookupException e) { - throw new RuntimeException("Failed to create [" + getSyntax().toString() + "] renderer", e); - } - - renderer.setPrinter(printer); - - return renderer; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventBlockRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventBlockRenderer.java deleted file mode 100644 index 71410a398..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventBlockRenderer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.event; - -import org.xwiki.component.annotation.Component; -import org.xwiki.component.annotation.Requirement; -import org.xwiki.rendering.internal.renderer.AbstractBlockRenderer; -import org.xwiki.rendering.renderer.PrintRendererFactory; - -@Component("event/1.0") -public class EventBlockRenderer extends AbstractBlockRenderer { - - @Requirement("event/1.0") - private PrintRendererFactory eventRendererFactory; - - @Override - protected PrintRendererFactory getPrintRendererFactory() { - return this.eventRendererFactory; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRenderer.java deleted file mode 100644 index 01a39a00e..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRenderer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.event; - -import org.xwiki.component.annotation.Component; -import org.xwiki.component.annotation.InstantiationStrategy; -import org.xwiki.component.descriptor.ComponentInstantiationStrategy; -import org.xwiki.component.phase.Initializable; -import org.xwiki.component.phase.InitializationException; -import org.xwiki.rendering.listener.chaining.ListenerChain; -import org.xwiki.rendering.renderer.AbstractChainingPrintRenderer; - -/** - * Print names of events. Useful for debugging and tracing in general. Note that this class is not - * located in the test - * source tree since it's currently used at runtime by the WYSIWYG editor for its runtime debug - * mode. - * - * @version $Id$ - * @since 2.0M3 - */ -@Component("event/1.0") -@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) -public class EventRenderer extends AbstractChainingPrintRenderer implements Initializable { - - /** - * {@inheritDoc} - * - * @see Initializable#initialize() - * @since 2.0M3 - */ - public void initialize() throws InitializationException { - ListenerChain chain = new ListenerChain(); - setListenerChain(chain); - - // Construct the listener chain in the right order. Listeners early in the chain are called - // before listeners - // placed later in the chain. - chain.addListener(this); - chain.addListener(new EventsChainingRenderer(chain)); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRendererFactory.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRendererFactory.java deleted file mode 100644 index 80a3506ad..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventRendererFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.event; - -import org.xwiki.rendering.internal.renderer.*; -import org.xwiki.component.annotation.Component; -import org.xwiki.rendering.syntax.Syntax; - -/** - * Create XHTML Renderers. - * - * @version $Id$ - * @since 2.0M3 - */ -@Component("event/1.0") -public class EventRendererFactory extends AbstractPrintRendererFactory { - - /** - * {@inheritDoc} - * - * @see AbstractPrintRendererFactory#getSyntax() - */ - public Syntax getSyntax() { - return Syntax.EVENT_1_0; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventsChainingRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventsChainingRenderer.java deleted file mode 100644 index 326ad800b..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/event/EventsChainingRenderer.java +++ /dev/null @@ -1,651 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.event; - -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.xwiki.rendering.listener.Format; -import org.xwiki.rendering.listener.HeaderLevel; -import org.xwiki.rendering.listener.reference.ResourceReference; -import org.xwiki.rendering.listener.ListType; -import org.xwiki.rendering.listener.chaining.ListenerChain; -import org.xwiki.rendering.syntax.Syntax; -import org.xwiki.rendering.renderer.AbstractChainingPrintRenderer; - -/** - * Prints listener event names in a format useful for testing and debugging. - * - * @version $Id$ - * @since 1.8RC1 - */ -public class EventsChainingRenderer extends AbstractChainingPrintRenderer { - - public EventsChainingRenderer(ListenerChain listenerChain) { - setListenerChain(listenerChain); - } - - // Events - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.chaining.AbstractChainingListener#beginDocument(java.util.Map) - */ - @Override - public void beginDocument(Map parameters) { - getPrinter().println("beginDocument" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.chaining.AbstractChainingListener#endDocument(java.util.Map) - */ - @Override - public void endDocument(Map parameters) { - getPrinter().print("endDocument" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.chaining.AbstractChainingListener#beginGroup(Map) - */ - @Override - public void beginGroup(Map parameters) { - getPrinter().println("beginGroup" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.chaining.AbstractChainingListener#endGroup(Map) - */ - @Override - public void endGroup(Map parameters) { - getPrinter().println("endGroup" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginFormat(org.xwiki.rendering.listener.Format, - * java.util.Map) - */ - @Override - public void beginFormat(Format format, Map parameters) { - getPrinter().println("beginFormat [" + format + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endFormat(org.xwiki.rendering.listener.Format, - * java.util.Map) - */ - @Override - public void endFormat(Format format, Map parameters) { - getPrinter().println("endFormat [" + format + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginParagraph(java.util.Map) - */ - @Override - public void beginParagraph(Map parameters) { - getPrinter().println("beginParagraph" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endParagraph(java.util.Map) - */ - @Override - public void endParagraph(Map parameters) { - getPrinter().println("endParagraph" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onNewLine() - */ - @Override - public void onNewLine() { - getPrinter().println("onNewLine"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginLink( - * org.xwiki.rendering.listener.reference.ResourceReference , boolean, java.util.Map) - */ - @Override - public void beginLink(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - getPrinter() - .println("beginLink [" + reference + "] [" + isFreeStandingURI + "]" - + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endLink( - * org.xwiki.rendering.listener.reference.ResourceReference , boolean, java.util.Map) - */ - @Override - public void endLink(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - getPrinter() - .println("endLink [" + reference + "] [" + isFreeStandingURI + "]" - + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onMacro(java.lang.String, - * java.util.Map, - * java.lang.String, boolean) - */ - @Override - public void onMacro(String id, Map parameters, String content, boolean isInline) { - printMacroData("onMacro", id, parameters, content, isInline); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginSection(java.util.Map) - */ - @Override - public void beginSection(Map parameters) { - getPrinter().println("beginSection" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginHeader(org.xwiki.rendering.listener.HeaderLevel, - * String, java.util.Map) - */ - @Override - public void beginHeader(HeaderLevel level, String id, Map parameters) { - getPrinter() - .println("beginHeader [" + level + ", " + id + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endSection(java.util.Map) - */ - @Override - public void endSection(Map parameters) { - getPrinter().println("endSection" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endHeader( - * org.xwiki.rendering.listener.HeaderLevel, String, java.util.Map) - */ - @Override - public void endHeader(HeaderLevel level, String id, Map parameters) { - getPrinter().println("endHeader [" + level + ", " + id + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onWord(java.lang.String) - */ - @Override - public void onWord(String word) { - getPrinter().println("onWord [" + getEscaped(word) + "]"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginList(org.xwiki.rendering.listener.ListType, - * java.util.Map) - */ - @Override - public void beginList(ListType listType, Map parameters) { - getPrinter().println("beginList [" + listType + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginListItem() - */ - @Override - public void beginListItem() { - getPrinter().println("beginListItem"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endList(org.xwiki.rendering.listener.ListType, - * java.util.Map) - */ - @Override - public void endList(ListType listType, Map parameters) { - getPrinter().println("endList [" + listType + "]" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endListItem() - */ - @Override - public void endListItem() { - getPrinter().println("endListItem"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onSpace() - */ - @Override - public void onSpace() { - getPrinter().println("onSpace"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onSpecialSymbol(char) - */ - @Override - public void onSpecialSymbol(char symbol) { - getPrinter().println("onSpecialSymbol [" + symbol + "]"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onRawText(String, Syntax) - */ - @Override - public void onRawText(String text, Syntax syntax) { - getPrinter().println("onRawText [" + text + "] [" + syntax.toIdString() + "]"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginMacroMarker(java.lang.String, - * java.util.Map, - * java.lang.String, boolean) - */ - @Override - public void beginMacroMarker(String name, Map parameters, String content, - boolean isInline) { - printMacroData("beginMacroMarker", name, parameters, content, isInline); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endMacroMarker(java.lang.String, - * java.util.Map, - * java.lang.String, boolean) - */ - @Override - public void endMacroMarker(String name, Map parameters, String content, - boolean isInline) { - printMacroData("endMacroMarker", name, parameters, content, isInline); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onId(java.lang.String) - */ - @Override - public void onId(String name) { - getPrinter().println("onId [" + name + "]"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onHorizontalLine(java.util.Map) - */ - @Override - public void onHorizontalLine(Map parameters) { - getPrinter().println("onHorizontalLine" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onEmptyLines(int) - */ - @Override - public void onEmptyLines(int count) { - getPrinter().println("onEmptyLines [" + count + "]"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onVerbatim(String, boolean, - * Map) - */ - @Override - public void onVerbatim(String protectedString, boolean isInline, Map parameters) { - getPrinter() - .println("onVerbatim [" + protectedString + "] [" + isInline + "]" - + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginDefinitionList(java.util.Map) - * @since 2.0RC1 - */ - @Override - public void beginDefinitionList(Map parameters) { - getPrinter().println("beginDefinitionList" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endDefinitionList(java.util.Map) - * @since 2.0RC1 - */ - @Override - public void endDefinitionList(Map parameters) { - getPrinter().println("endDefinitionList" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginDefinitionTerm() - */ - @Override - public void beginDefinitionTerm() { - getPrinter().println("beginDefinitionTerm"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginDefinitionDescription() - */ - @Override - public void beginDefinitionDescription() { - getPrinter().println("beginDefinitionDescription"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endDefinitionTerm() - */ - @Override - public void endDefinitionTerm() { - getPrinter().println("endDefinitionTerm"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endDefinitionDescription() - */ - @Override - public void endDefinitionDescription() { - getPrinter().println("endDefinitionDescription"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginQuotation(java.util.Map) - */ - @Override - public void beginQuotation(Map parameters) { - getPrinter().println("beginQuotation" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endQuotation(java.util.Map) - */ - @Override - public void endQuotation(Map parameters) { - getPrinter().println("endQuotation" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginQuotationLine() - */ - @Override - public void beginQuotationLine() { - getPrinter().println("beginQuotationLine"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endQuotationLine() - */ - @Override - public void endQuotationLine() { - getPrinter().println("endQuotationLine"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTable(java.util.Map) - */ - @Override - public void beginTable(Map parameters) { - getPrinter().println("beginTable" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableCell(java.util.Map) - */ - @Override - public void beginTableCell(Map parameters) { - getPrinter().println("beginTableCell" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableHeadCell(java.util.Map) - */ - @Override - public void beginTableHeadCell(Map parameters) { - getPrinter().println("beginTableHeadCell" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableRow(java.util.Map) - */ - @Override - public void beginTableRow(Map parameters) { - getPrinter().println("beginTableRow" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endTable(java.util.Map) - */ - @Override - public void endTable(Map parameters) { - getPrinter().println("endTable" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endTableCell(java.util.Map) - */ - @Override - public void endTableCell(Map parameters) { - getPrinter().println("endTableCell" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endTableHeadCell(java.util.Map) - */ - @Override - public void endTableHeadCell(Map parameters) { - getPrinter().println("endTableHeadCell" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#endTableRow(java.util.Map) - */ - @Override - public void endTableRow(Map parameters) { - getPrinter().println("endTableRow" + serializeParameters(parameters)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onImage( - * org.xwiki.rendering.listener.reference.ResourceReference , boolean, java.util.Map) - * @since 2.5RC1 - */ - @Override - public void onImage(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - getPrinter() - .println("onImage [" + reference + "] [" + isFreeStandingURI + "]" - + serializeParameters(parameters)); - } - - public String getEscaped(String str) { - String printableStr; - - if (str == null) { - printableStr = null; - } else if (StringUtils.isAsciiPrintable(str)) { - printableStr = str; - } else { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (c > 126) { - buffer.append("(((").append((int) c).append(")))"); - } else { - buffer.append(c); - } - } - printableStr = buffer.toString(); - } - - return printableStr; - } - - private void printMacroData(String eventName, String name, Map parameters, - String content, - boolean isInline) { - StringBuffer parametersBuffer = new StringBuffer(); - for (Iterator paramsIt = parameters.keySet().iterator(); paramsIt.hasNext();) { - String paramName = paramsIt.next(); - parametersBuffer.append(paramName).append("=").append(parameters.get(paramName)); - if (paramsIt.hasNext()) { - parametersBuffer.append("|"); - } - } - - StringBuffer macroBuffer = new StringBuffer(); - - macroBuffer.append(eventName); - macroBuffer.append(isInline ? "Inline" : "Standalone"); - - macroBuffer.append(" ["); - macroBuffer.append(name); - macroBuffer.append("]"); - - macroBuffer.append(" ["); - macroBuffer.append(parametersBuffer); - macroBuffer.append("]"); - - if (content != null) { - macroBuffer.append(" ["); - macroBuffer.append(content); - macroBuffer.append("]"); - } - - getPrinter().println(macroBuffer.toString()); - } - - private String serializeParameters(Map parameters) { - StringBuffer parametersStr = new StringBuffer(); - for (Map.Entry entry : parameters.entrySet()) { - String value = entry.getValue(); - String key = entry.getKey(); - - if (key != null && value != null) { - parametersStr.append('[').append(getEscaped(entry.getKey())).append(']').append('=') - .append('[') - .append(getEscaped(entry.getValue())).append(']'); - } - } - - if (parametersStr.length() > 0) { - StringBuffer buffer = new StringBuffer(); - buffer.append(' ').append('['); - buffer.append(parametersStr); - buffer.append(']'); - return buffer.toString(); - } else { - return ""; - } - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextBlockRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextBlockRenderer.java deleted file mode 100644 index 5586010a1..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextBlockRenderer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.plain; - -import org.xwiki.component.annotation.Component; -import org.xwiki.component.annotation.Requirement; -import org.xwiki.rendering.internal.renderer.AbstractBlockRenderer; -import org.xwiki.rendering.renderer.PrintRendererFactory; - -/** - * Print only plain text information. For example it remove anything which need a specific syntax a - * simple plain text - * editor can't support like the style, link, image, etc. This renderer is mainly used to generate a - * simple as possible - * label like in a TOC. - * - * @version $Id$ - * @since 2.0M3 - */ -@Component("plain/1.0") -public class PlainTextBlockRenderer extends AbstractBlockRenderer { - - /** - * Used to create new plain/1.0 {@link org.xwiki.rendering.renderer.PrintRenderer}s. - */ - @Requirement("plain/1.0") - private PrintRendererFactory plainTextRendererFactory; - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.internal.renderer.AbstractBlockRenderer#getPrintRendererFactory() - */ - @Override - protected PrintRendererFactory getPrintRendererFactory() { - return this.plainTextRendererFactory; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextChainingRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextChainingRenderer.java deleted file mode 100644 index 5e95b13a0..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextChainingRenderer.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.plain; - -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.xwiki.rendering.listener.HeaderLevel; -import org.xwiki.rendering.listener.reference.ResourceReference; -import org.xwiki.rendering.listener.reference.ResourceType; -import org.xwiki.rendering.listener.ListType; -import org.xwiki.rendering.listener.chaining.BlockStateChainingListener; -import org.xwiki.rendering.listener.chaining.EmptyBlockChainingListener; -import org.xwiki.rendering.listener.chaining.ListenerChain; -import org.xwiki.rendering.renderer.reference.link.LinkLabelGenerator; -import org.xwiki.rendering.renderer.AbstractChainingPrintRenderer; - -/** - * Print only plain text information. For example it remove anything which need a specific syntax a - * simple plain text - * editor can't support like the style, link, image, etc. This renderer is mainly used to generate a - * simple as possible - * label like in a TOC. - * - * @version $Id$ - * @since 1.9M1 - */ -public class PlainTextChainingRenderer extends AbstractChainingPrintRenderer { - - /** - * New Line character. - */ - private static final String NL = "\n"; - - private boolean isFirstElementRendered; - - /** - * Generate link label. - */ - private LinkLabelGenerator linkLabelGenerator; - - /** - * The plain text renderer supports when no link label generator is set. - */ - public PlainTextChainingRenderer(ListenerChain listenerChain) { - this(null, listenerChain); - } - - public PlainTextChainingRenderer(LinkLabelGenerator linkLabelGenerator, - ListenerChain listenerChain) { - setListenerChain(listenerChain); - - this.linkLabelGenerator = linkLabelGenerator; - } - - // State - - private BlockStateChainingListener getBlockState() { - return (BlockStateChainingListener) getListenerChain() - .getListener(BlockStateChainingListener.class); - } - - protected EmptyBlockChainingListener getEmptyBlockState() { - return (EmptyBlockChainingListener) getListenerChain() - .getListener(EmptyBlockChainingListener.class); - } - - // Events - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginParagraph(java.util.Map) - */ - @Override - public void beginParagraph(Map parameters) { - printEmptyLine(); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onNewLine() - */ - @Override - public void onNewLine() { - getPrinter().print(NL); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.chaining.AbstractChainingListener#endLink( - * org.xwiki.rendering.listener.reference.ResourceReference , boolean, java.util.Map) - */ - @Override - public void endLink(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - if (getEmptyBlockState().isCurrentContainerBlockEmpty()) { - if (reference.getType().equals(ResourceType.DOCUMENT) && this.linkLabelGenerator != null) { - getPrinter().print(this.linkLabelGenerator.generate(reference)); - } else { - getPrinter().print(reference.getReference()); - } - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginHeader(org.xwiki.rendering.listener.HeaderLevel, - * String, java.util.Map) - */ - @Override - public void beginHeader(HeaderLevel level, String id, Map parameters) { - printEmptyLine(); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onWord(java.lang.String) - */ - @Override - public void onWord(String word) { - getPrinter().print(word); - } - - @Override - public void beginList(ListType listType, Map parameters) { - if (getBlockState().getListDepth() == 1) { - printEmptyLine(); - } else { - getPrinter().print(NL); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginListItem() - */ - @Override - public void beginListItem() { - if (getBlockState().getListItemIndex() > 0) { - getPrinter().print(NL); - } - - // TODO: maybe add some syntax here like a - or not - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onSpace() - */ - @Override - public void onSpace() { - getPrinter().print(" "); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onSpecialSymbol(char) - */ - @Override - public void onSpecialSymbol(char symbol) { - getPrinter().print(String.valueOf(symbol)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onHorizontalLine(java.util.Map) - */ - @Override - public void onHorizontalLine(Map parameters) { - printEmptyLine(); - getPrinter().print("----"); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onEmptyLines(int) - */ - @Override - public void onEmptyLines(int count) { - getPrinter().print(StringUtils.repeat(NL, count)); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onVerbatim(String, boolean, - * Map) - */ - @Override - public void onVerbatim(String protectedString, boolean isInline, Map parameters) { - getPrinter().print(protectedString); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.listener.Listener#beginDefinitionList(java.util.Map) - * @since 2.0RC1 - */ - @Override - public void beginDefinitionList(Map parameters) { - if (getBlockState().getDefinitionListDepth() == 1 && !getBlockState().isInList()) { - printEmptyLine(); - } else { - getPrinter().print(NL); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginDefinitionTerm() - */ - @Override - public void beginDefinitionTerm() { - if (getBlockState().getDefinitionListItemIndex() > 0) { - getPrinter().print(NL); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginDefinitionDescription() - */ - @Override - public void beginDefinitionDescription() { - if (getBlockState().getDefinitionListItemIndex() > 0) { - getPrinter().print(NL); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginQuotationLine() - */ - @Override - public void beginQuotationLine() { - if (getBlockState().getQuotationLineIndex() > 0) { - getPrinter().print(NL); - } else { - printEmptyLine(); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTable(java.util.Map) - */ - @Override - public void beginTable(Map parameters) { - printEmptyLine(); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableCell(java.util.Map) - */ - @Override - public void beginTableCell(Map parameters) { - if (getBlockState().getCellCol() > 0) { - getPrinter().print("\t"); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableHeadCell(java.util.Map) - */ - @Override - public void beginTableHeadCell(Map parameters) { - beginTableCell(parameters); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#beginTableRow(java.util.Map) - */ - @Override - public void beginTableRow(Map parameters) { - if (getBlockState().getCellRow() > 0) { - getPrinter().print(NL); - } - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.AbstractChainingPrintRenderer#onImage( - * org.xwiki.rendering.listener.reference.ResourceReference , boolean, java.util.Map) - * @since 2.5RC1 - */ - @Override - public void onImage(ResourceReference reference, boolean isFreeStandingURI, - Map parameters) { - // TODO: maybe something could be done here - } - - private void printEmptyLine() { - if (this.isFirstElementRendered) { - getPrinter().print(NL + NL); - } else { - this.isFirstElementRendered = true; - } - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRenderer.java deleted file mode 100644 index a1d12a089..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRenderer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.plain; - -import org.xwiki.component.annotation.Component; -import org.xwiki.component.annotation.InstantiationStrategy; -import org.xwiki.component.annotation.Requirement; -import org.xwiki.component.descriptor.ComponentInstantiationStrategy; -import org.xwiki.component.phase.Initializable; -import org.xwiki.component.phase.InitializationException; -import org.xwiki.rendering.listener.chaining.BlockStateChainingListener; -import org.xwiki.rendering.listener.chaining.EmptyBlockChainingListener; -import org.xwiki.rendering.listener.chaining.ListenerChain; -import org.xwiki.rendering.renderer.reference.link.LinkLabelGenerator; -import org.xwiki.rendering.renderer.AbstractChainingPrintRenderer; - -/** - * Print only plain text information. For example it remove anything which need a specific syntax a - * simple plain text - * editor can't support like the style, link, image, etc. This renderer is mainly used to generate a - * simple as possible - * label like in a TOC. - * - * @version $Id$ - * @since 2.0M3 - */ -@Component("plain/1.0") -@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) -public class PlainTextRenderer extends AbstractChainingPrintRenderer implements Initializable { - - @Requirement - private LinkLabelGenerator linkLabelGenerator; - - /** - * {@inheritDoc} - * - * @see Initializable#initialize() - * @since 2.0M3 - */ - public void initialize() throws InitializationException { - ListenerChain chain = new ListenerChain(); - setListenerChain(chain); - - // Construct the listener chain in the right order. Listeners early in the chain are called - // before listeners - // placed later in the chain. - chain.addListener(this); - chain.addListener(new BlockStateChainingListener(chain)); - chain.addListener(new EmptyBlockChainingListener(chain)); - chain.addListener(new PlainTextChainingRenderer(this.linkLabelGenerator, chain)); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRendererFactory.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRendererFactory.java deleted file mode 100644 index 08696b739..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/plain/PlainTextRendererFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.plain; - -import org.xwiki.component.annotation.Component; -import org.xwiki.rendering.syntax.Syntax; -import org.xwiki.rendering.internal.renderer.AbstractPrintRendererFactory; - -/** - * Create Plain Text Renderers. - * - * @version $Id$ - * @since 2.0M3 - */ -@Component("plain/1.0") -public class PlainTextRendererFactory extends AbstractPrintRendererFactory { - - /** - * {@inheritDoc} - * - * @see AbstractPrintRendererFactory#getSyntax() - */ - public Syntax getSyntax() { - return Syntax.PLAIN_1_0; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/WikiWriter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/WikiWriter.java deleted file mode 100644 index 12d603615..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/WikiWriter.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.printer; - -import java.io.IOException; -import java.io.Writer; - -import org.xwiki.rendering.renderer.printer.WikiPrinter; - -/** - * Bridge so that {@link WikiPrinter} can be used in a tools supporting {@link Writer} api. - * - * @version $Id$ - */ -public class WikiWriter extends Writer { - - public WikiWriter(WikiPrinter printer) { - super(printer); - } - - public void setWikiPrinter(WikiPrinter printer) { - this.lock = printer; - } - - public WikiPrinter getWikiPrinter() { - return (WikiPrinter) this.lock; - } - - /** - * {@inheritDoc} - * - * @see java.io.Writer#close() - */ - @Override - public void close() throws IOException { - // WikiPrinter does not support stream close - } - - /** - * {@inheritDoc} - * - * @see java.io.Writer#flush() - */ - @Override - public void flush() throws IOException { - // WikiPrinter does not support stream flush - } - - /** - * {@inheritDoc} - * - * @see java.io.Writer#write(char[], int, int) - */ - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - getWikiPrinter().print(new String(cbuf, off, len)); - } - - /** - * {@inheritDoc} - *

    - * Override it to improve speed a little. Otherwise the String is transformed in char table passed - * to the over - * methods which recreate a String. - * - * @see java.io.Writer#write(java.lang.String) - */ - @Override - public void write(String str) throws IOException { - getWikiPrinter().print(str); - } - -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/XHTMLWriter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/XHTMLWriter.java deleted file mode 100644 index 5be64c032..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/renderer/printer/XHTMLWriter.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.internal.renderer.printer; - -import java.io.UnsupportedEncodingException; -import java.io.Writer; - -import org.dom4j.io.OutputFormat; -import org.dom4j.io.XMLWriter; - -/** - * XHTMLWriter is an helper to configure XMLWriter to format a DOM4J tree as XHTML. - * - * @version $Id$ - */ -public class XHTMLWriter extends XMLWriter { - - protected static final OutputFormat DEFAULT_XHTML_FORMAT; - - static { - DEFAULT_XHTML_FORMAT = new OutputFormat(); - DEFAULT_XHTML_FORMAT.setXHTML(true); - } - - public XHTMLWriter(Writer writer) throws UnsupportedEncodingException { - super(writer, DEFAULT_XHTML_FORMAT); - - // escape all non US-ASCII to have as less encoding problems as possible - setMaximumAllowedCharacter(-1); - } - - /** - * Escapes a string to be used as an attribute value. Unlike the original method in - * {@link XMLWriter}, apostrophes - * are replaced by a numerical entity &#38;, since &apos; is not valid in HTML documents. - * - * @param text - * the attribute value to escape - * @return the text with all occurrences of special XML characters replaced by entity references. - */ - @Override - protected String escapeAttributeEntities(String text) { - return super.escapeAttributeEntities(text).replace("'", "&"); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/AbstractChainingPrintRenderer.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/AbstractChainingPrintRenderer.java deleted file mode 100644 index 718f4ac52..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/AbstractChainingPrintRenderer.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.renderer; - -import java.util.Stack; - -import org.xwiki.rendering.listener.chaining.AbstractChainingListener; -import org.xwiki.rendering.listener.chaining.ChainingListener; -import org.xwiki.rendering.renderer.printer.WikiPrinter; - -/** - * @version $Id$ - * @since 1.8RC1 - */ -public abstract class AbstractChainingPrintRenderer extends AbstractChainingListener - implements PrintRenderer { - - /** - * The printer stack. Can be used to print in a specific printer and then easily return to the - * previous one. - */ - private Stack printers = new Stack(); - - /** - * @return the main printer. - */ - public WikiPrinter getMainPrinter() { - return this.printers.firstElement(); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.PrintRenderer#getPrinter() - */ - public WikiPrinter getPrinter() { - return this.printers.peek(); - } - - /** - * {@inheritDoc} - * - * @see PrintRenderer#setPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) - * @since 2.0M3 - */ - public void setPrinter(WikiPrinter printer) { - pushPrinter(printer); - } - - /** - * Change the current {@link WikiPrinter} with the provided one. - * - * @param wikiPrinter - * the new {@link WikiPrinter} to use - */ - protected void pushPrinter(WikiPrinter wikiPrinter) { - this.printers.push(wikiPrinter); - - // Since we're setting a new printer to use, make sure that all print renderers in the chain - // have the new - // printer set. Only do this if we're on the top level Print Renderer. - if (getListenerChain().indexOf(getClass()) == 0) { - ChainingListener nextListener = this; - while ((nextListener = getListenerChain().getNextListener(nextListener.getClass())) != null) { - if (PrintRenderer.class.isAssignableFrom(nextListener.getClass())) { - ((PrintRenderer) nextListener).setPrinter(wikiPrinter); - } - } - } - } - - /** - * Removes the current {@link WikiPrinter} and instead sets the previous printer as active. - */ - protected void popPrinter() { - this.printers.pop(); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/DefaultWikiPrinter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/DefaultWikiPrinter.java deleted file mode 100644 index ae67e50e4..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/DefaultWikiPrinter.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.renderer.printer; - -/** - * Printer using a {@link StringBuffer} as the underlying output target. - * - * @version $Id$ - * @since 1.6M1 - */ -public class DefaultWikiPrinter implements WikiPrinter { - - /** - * The buffer where to put the provided {@link String}s. - */ - private StringBuffer buffer; - - /** - * The default constructor. It initialize a new empty {@link StringBuffer}. - */ - public DefaultWikiPrinter() { - this(new StringBuffer()); - } - - /** - * @param buffer - * the {@link StringBuffer} to where to put the provided {@link String}s. - */ - public DefaultWikiPrinter(StringBuffer buffer) { - this.buffer = buffer; - } - - /** - * @return the buffer containing the printed {@link String}s. - */ - public StringBuffer getBuffer() { - return this.buffer; - } - - /** - * This method is protected to allow classes extending this one to override what a new line is. - * - * @return a new line symbols - */ - protected String getEOL() { - return "\n"; - } - - /** - * {@inheritDoc} - * - * @see WikiPrinter#print(String) - */ - public void print(String text) { - getBuffer().append(text); - } - - /** - * {@inheritDoc} - * - * @see WikiPrinter#println(String) - */ - public void println(String text) { - getBuffer().append(text).append(getEOL()); - } - - /** - * {@inheritDoc} - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return getBuffer().toString(); - } - - /** - * Removes the buffer's content which allows the printer to be reused. - */ - public void clear() { - getBuffer().setLength(0); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/LookaheadWikiPrinter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/LookaheadWikiPrinter.java deleted file mode 100644 index e30df5107..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/LookaheadWikiPrinter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.renderer.printer; - -/** - * Wiki printer that allows deferring printing text and that instead can save it in some internal - * buffer. This allows - * accumulating some content before it's flushed. This feature is used for example in the XWiki - * Syntax Renderer to - * accumulate text so that it be reviewed and escaped before printed (indeed some text has some - * characters that need to - * be escaped or they'd have a wiki meaning otherwise). - * - * @version $Id$ - * @since 1.7 - */ -public class LookaheadWikiPrinter extends WrappingWikiPrinter { - - private StringBuffer buffer = new StringBuffer(); - - public LookaheadWikiPrinter(WikiPrinter printer) { - super(printer); - } - - protected void printInternal(String text) { - super.print(text); - } - - protected void printlnInternal(String text) { - super.println(text); - } - - public void print(String text) { - flush(); - printInternal(text); - } - - public void println(String text) { - flush(); - printlnInternal(text); - } - - public void printDelayed(String text) { - getBuffer().append(text); - } - - public void printlnDelayed(String text) { - getBuffer().append(text).append(getEOL()); - } - - public StringBuffer getBuffer() { - return this.buffer; - } - - public void flush() { - if (getBuffer().length() > 0) { - printInternal(getBuffer().toString()); - getBuffer().setLength(0); - } - } - - /** - * This method is protected to allow classes extending this one to define what a new line is. - * - * @return a new line symbols - */ - protected String getEOL() { - return "\n"; - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/WrappingWikiPrinter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/WrappingWikiPrinter.java deleted file mode 100644 index e87a58f4f..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/WrappingWikiPrinter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.renderer.printer; - -/** - * Wraps a wiki printer. - * - * @version $Id$ - * @since 1.7 - */ -public class WrappingWikiPrinter implements WikiPrinter { - - private WikiPrinter printer; - - public WrappingWikiPrinter(WikiPrinter printer) { - this.printer = printer; - } - - public void print(String text) { - getWrappedPrinter().print(text); - } - - public void println(String text) { - getWrappedPrinter().println(text); - } - - public WikiPrinter getWrappedPrinter() { - return this.printer; - } - - @Override - public String toString() { - return getWrappedPrinter().toString(); - } -} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/XHTMLWikiPrinter.java b/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/XHTMLWikiPrinter.java deleted file mode 100644 index eb5428ab5..000000000 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/XHTMLWikiPrinter.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.xwiki.rendering.renderer.printer; - -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.xml.sax.Attributes; - -/** - * Base toolkit class for all XHTML-based renderers. This printer handles whitespaces so that it - * prints " " when - * needed (i.e. when the spaces are at the beginning or at the end of an element's content or when - * there are more than 1 - * contiguous spaces, except for CDATA sections and inside PRE elements. It also knows how to handle - * XHTML comments). - * - * @version $Id$ - * @since 1.7M1 - */ -public class XHTMLWikiPrinter extends XMLWikiPrinter { - - private int spaceCount = 0; - - private boolean isInCData; - - private boolean isInPreserveElement; - - private boolean elementEnded; - - private boolean hasTextBeenPrinted; - - /** - * @param printer - * the object to which to write the XHTML output to - */ - public XHTMLWikiPrinter(WikiPrinter printer) { - super(printer); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXML(java.lang.String) - */ - @Override - public void printXML(String str) { - handleSpaceWhenInText(); - super.printXML(str); - this.hasTextBeenPrinted = true; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLElement(java.lang.String) - */ - @Override - public void printXMLElement(String name) { - handleSpaceWhenStartElement(); - super.printXMLElement(name); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLElement(java.lang.String, - * java.lang.String[][]) - */ - @Override - public void printXMLElement(String name, String[][] attributes) { - handleSpaceWhenStartElement(); - super.printXMLElement(name, attributes); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLElement(java.lang.String, - * java.util.Map) - */ - @Override - public void printXMLElement(String name, Map attributes) { - handleSpaceWhenStartElement(); - super.printXMLElement(name, attributes); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLStartElement(java.lang.String) - */ - @Override - public void printXMLStartElement(String name) { - handleSpaceWhenStartElement(); - super.printXMLStartElement(name); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLStartElement(java.lang.String, - * java.lang.String[][]) - */ - @Override - public void printXMLStartElement(String name, String[][] attributes) { - handleSpaceWhenStartElement(); - super.printXMLStartElement(name, attributes); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLStartElement(java.lang.String, - * java.util.Map) - */ - @Override - public void printXMLStartElement(String name, Map attributes) { - handleSpaceWhenStartElement(); - super.printXMLStartElement(name, attributes); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLStartElement(java.lang.String, - * org.xml.sax.Attributes) - */ - @Override - public void printXMLStartElement(String name, Attributes attributes) { - handleSpaceWhenStartElement(); - super.printXMLStartElement(name, attributes); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLEndElement(java.lang.String) - */ - @Override - public void printXMLEndElement(String name) { - handleSpaceWhenEndlement(); - super.printXMLEndElement(name); - this.elementEnded = true; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLComment(java.lang.String) - */ - @Override - public void printXMLComment(String content) { - printXMLComment(content, false); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLComment(java.lang.String, - * boolean) - */ - @Override - public void printXMLComment(String content, boolean escape) { - handleSpaceWhenStartElement(); - super.printXMLComment(content, escape); - this.elementEnded = true; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLStartCData() - */ - @Override - public void printXMLStartCData() { - handleSpaceWhenStartElement(); - super.printXMLStartCData(); - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printXMLEndCData() - */ - @Override - public void printXMLEndCData() { - handleSpaceWhenEndlement(); - super.printXMLEndCData(); - } - - /** - * This method should be used to print a space rather than calling printXML(" "). - */ - public void printSpace() { - this.spaceCount++; - } - - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.XMLWikiPrinter#printRaw(java.lang.String) - */ - @Override - public void printRaw(String raw) { - handleSpaceWhenStartElement(); - super.printRaw(raw); - this.elementEnded = true; - } - - private void handleSpaceWhenInText() { - if (this.elementEnded || this.hasTextBeenPrinted) { - handleSpaceWhenStartElement(); - } else { - handleSpaceWhenEndlement(); - } - } - - private void handleSpaceWhenStartElement() { - // Use case: something ... - // Use case: something @@ -128,10 +134,6 @@ org.xwiki.platform xwiki-core-bridge - - org.xwiki.platform - xwiki-core-xml - org.xwiki.platform xwiki-core-management diff --git a/celements-xwiki-xml/pom.xml b/celements-xwiki-xml/pom.xml new file mode 100644 index 000000000..f71e398be --- /dev/null +++ b/celements-xwiki-xml/pom.xml @@ -0,0 +1,159 @@ + + + + + + 4.0.0 + + com.celements + base-pom + 7.0-SNAPSHOT + + celements-xwiki-xml + 7.0-SNAPSHOT + + + com.celements + celements-commons + 7.0-SNAPSHOT + provided + + + com.celements + celements-component + 7.0-SNAPSHOT + provided + + + com.celements + celements-config-source-api + 7.0-SNAPSHOT + provided + + + com.celements + celements-servlet + 7.0-SNAPSHOT + provided + + + javax.servlet + javax.servlet-api + provided + + + + + org.springframework + spring-context + provided + + + org.springframework + spring-web + provided + + + + + com.google.guava + guava + + + + + org.apache.logging.log4j + log4j-1.2-api + runtime + + + org.apache.logging.log4j + log4j-api + runtime + + + org.apache.logging.log4j + log4j-core + runtime + + + org.apache.logging.log4j + log4j-slf4j-impl + runtime + + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + + + + + org.xwiki.platform + xwiki-core-script + + + + + com.celements + celements-base-tests + 7.0-SNAPSHOT + test + + + org.easymock + easymock + test + + + + + org.xwiki.platform + xwiki-core-shared-tests + test + + + jmock + jmock + test + + + org.jmock + jmock-legacy + test + + + jmock + jmock-cglib + test + + + + diff --git a/celements-xwiki-xml/src/main/java/org/xwiki/xml/ExtractHandler.java b/celements-xwiki-xml/src/main/java/org/xwiki/xml/ExtractHandler.java new file mode 100644 index 000000000..6f05cead1 --- /dev/null +++ b/celements-xwiki-xml/src/main/java/org/xwiki/xml/ExtractHandler.java @@ -0,0 +1,320 @@ +/* + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.xwiki.xml; + +import java.util.Stack; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + *

    + * Extracts a well-formed XML fragment by listening to SAX events. The result has the following + * semantic:
    + * xmlInput.dropAllTags().substring(start, length).unDropAssociatedTags() + *

    + *

    + * So basically we would create an instance like new ExtractHandler(0, 400) in order to + * obtain an XML + * fragment with its inner text length of at most 400 characters, starting at position (character) 0 + * in the source + * (input) XML's inner text. The ExtractHandler is used in feed plug-in to obtain a preview of an + * XML (HTML, to be more + * specific). Another use case could be to paginate an XML source (keeping pages well-formed). + *

    + *

    + * As an example, the result of applying an ExtractHandler(3, 13) to:
    + * <p>click <a href="realyLongURL" title="Here">here</a> to view the result</p> + *
    + * is:
    + * <p>ck <a href="realyLongURL" title="Here">here</a> to</p> + *

    + * + * @version $Id$ + * @since 1.6M2 + */ +public class ExtractHandler extends DefaultHandler { + + /** + * A simple utility bean for representing an XML tag. + */ + private static class XMLTag { + + /** + * Tag's qualified name. + */ + private String qName; + + /** + * Tag's attributes. + */ + private Attributes atts; + + /** + * Constructs a new XML tag with the given qualified name and attributes. + * + * @param qName + * Tag's qualified name. + * @param atts + * Tag's attributes. + */ + public XMLTag(String qName, Attributes atts) { + this.qName = qName; + this.atts = atts; + } + + /** + * @return Tag's qualified name. + */ + public String getQName() { + return qName; + } + + /** + * @return Tag's attributes. + */ + public Attributes getAtts() { + return atts; + } + } + + /** + * The number of characters, in text nodes, that have to be read before starting the extraction. + */ + private int lowerBound; + + /** + * The maximum number of characters that may be read during the parsing process. + */ + private int upperBound; + + /** + * The number of characters read so far. + */ + private int counter; + + /** + * The stack of open tags; when the lower bound is reached all the tags in the stack must be + * opened; when the upper + * bound is reached all the tags in the stack must be closed. + */ + private Stack openTags = new Stack(); + + /** + * The fragment that is extracted during the parsing process. + */ + private StringBuffer result; + + /** + * true if the extraction was successful. The parsing process throws an exception + * when the upper + * bound is reached; this flag is useful to distinguish between this exception and the others. + */ + private boolean finished; + + /** + * Creates a new instance. + * + * @param start + * The character index from where to start the extraction. + * @param length + * The number of plain text characters to extract. + * @throws SAXException + * if start is less than zero or length is less than or equal to zero. + */ + public ExtractHandler(int start, int length) throws SAXException { + super(); + if (start < 0) { + throw new SAXException("Start must be greater than or equal to 0"); + } + if (length <= 0) { + throw new SAXException("Length must be greater than 0"); + } + lowerBound = start; + upperBound = lowerBound + length; + } + + /** + * @return The extracted text. + */ + public String getResult() { + return result.toString(); + } + + /** + * @return true if the extraction process has succeeded; false if an exception occurred during the + * process. + */ + public boolean isFinished() { + return finished; + } + + /** + * Append an open tag with the given specification to the result buffer. + * + * @param qName + * Tag's qualified name. + * @param atts + * Tag's attributes. + */ + private void openTag(String qName, Attributes atts) { + result.append('<').append(qName); + for (int i = 0; i < atts.getLength(); i++) { + result.append(' ').append(atts.getQName(i)).append("=\"").append(atts.getValue(i)) + .append('\"'); + } + result.append('>'); + } + + /** + * Open all pending tags. + * + * @see #openTag(String, Attributes) + */ + private void openTags() { + for (XMLTag tag : openTags) { + openTag(tag.getQName(), tag.getAtts()); + } + } + + /** + * Close all pending tags. + * + * @see #closeTag(String) + */ + private void closeTags() { + while (!openTags.isEmpty()) { + closeTag(openTags.pop().getQName()); + } + } + + /** + * Append a closed tag with the given qualified name to the result buffer. + * + * @param qName + * Tag's qualified name. + */ + private void closeTag(String qName) { + result.append("'); + } + + /** + * @return true if the start point has been passed but the length limit hasn't been reached. + */ + private boolean isExtracting() { + return lowerBound <= counter && counter <= upperBound; + } + + /** + * {@inheritDoc} + * + * @see DefaultHandler#startDocument() + */ + public void startDocument() throws SAXException { + super.startDocument(); + counter = 0; + openTags.clear(); + result = new StringBuffer(); + finished = false; + } + + /** + * {@inheritDoc} + * + * @see DefaultHandler#startElement(String, String, String, Attributes) + */ + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) + throws SAXException { + openTags.push(new XMLTag(qName, atts)); + if (isExtracting()) { + openTag(qName, atts); + } + } + + /** + * {@inheritDoc} + * + * @see DefaultHandler#characters(char[], int, int) + */ + public void characters(char[] ch, int start, int length) throws SAXException { + int offset = lowerBound - counter; + if (offset > 0) { + if (offset > length) { + counter += length; + return; + } else { + counter = lowerBound; + openTags(); + characters(ch, start + offset, length - offset); + return; + } + } + int remainingLength = upperBound - counter; + if (remainingLength <= length) { + String content = new String(ch, start, remainingLength); + int spaceIndex = remainingLength; + if (remainingLength == length || ch[remainingLength] != ' ') { + spaceIndex = content.lastIndexOf(" "); + } + if (spaceIndex >= 0) { + counter += spaceIndex; + result.append(content.substring(0, spaceIndex)); + } else { + counter = upperBound; + result.append(content); + } + endDocument(); + throw new SAXException("Length limit reached"); + } else { + counter += length; + result.append(ch, start, length); + } + } + + /** + * {@inheritDoc} + * + * @see DefaultHandler#endElement(String, String, String) + */ + public void endElement(String namespaceURI, String localName, String qName) throws SAXException { + // We assume the XML fragment is well defined, and thus we shouldn't have a closed tag + // without its pair open tag. So we don't test for empty stack or tag match. + openTags.pop(); + if (isExtracting()) { + closeTag(qName); + } + } + + /** + * {@inheritDoc} + * + * @see DefaultHandler#endDocument() + */ + public void endDocument() throws SAXException { + super.endDocument(); + // Close open tags + if (isExtracting()) { + closeTags(); + } + // set finished flag to distinguish between "length limit reached" and other exceptions + finished = true; + } +} diff --git a/celements-xwiki-xml/src/main/java/org/xwiki/xml/XMLUtils.java b/celements-xwiki-xml/src/main/java/org/xwiki/xml/XMLUtils.java new file mode 100644 index 000000000..8015fd2d5 --- /dev/null +++ b/celements-xwiki-xml/src/main/java/org/xwiki/xml/XMLUtils.java @@ -0,0 +1,142 @@ +/* + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.xwiki.xml; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXResult; + +import org.w3c.dom.Node; + +/** + * XML Utility methods. + * + * @version $Id$ + * @since 1.6M1 + */ +public final class XMLUtils { + + /** + * Private constructor since this is a utility class that shouldn't be instantiated (all methods + * are static). + */ + private XMLUtils() { + // Nothing to do + } + + /** + * Extracts a well-formed XML fragment from the given DOM tree. + * + * @param node + * the root of the DOM tree where the extraction takes place + * @param start + * the index of the first character + * @param length + * the maximum number of characters in text nodes to include in the returned fragment + * @return a well-formed XML fragment starting at the given character index and having up to the + * specified length, + * summing only the characters in text nodes + * @since 1.6M2 + */ + public static String extractXML(Node node, int start, int length) { + ExtractHandler handler = null; + try { + handler = new ExtractHandler(start, length); + Transformer xformer = TransformerFactory.newInstance().newTransformer(); + xformer.transform(new DOMSource(node), new SAXResult(handler)); + return handler.getResult(); + } catch (Throwable t) { + if (handler != null && handler.isFinished()) { + return handler.getResult(); + } else { + throw new RuntimeException("Failed to extract XML", t); + } + } + } + + /** + * XML comment does not support some characters inside its content but there is no official + * escaping/unescaping for + * it so we made our own. + *

    + *

      + *
    • 1) Escape existing \
    • + *
    • 2) Escape --
    • + *
    • 3) Add "\" (unescaped as "") at the end if the last char is -
    • + *
    + * + * @param content + * the XML comment content to escape + * @return the escaped content. + * @since 1.9M2 + */ + public static String escapeXMLComment(String content) { + StringBuffer str = new StringBuffer(content.length()); + + char[] buff = content.toCharArray(); + char lastChar = 0; + for (char c : buff) { + if (c == '\\') { + str.append('\\'); + } else if (c == '-' && lastChar == '-') { + str.append('\\'); + } + + str.append(c); + lastChar = c; + } + + if (lastChar == '-') { + str.append('\\'); + } + + return str.toString(); + } + + /** + * XML comment does not support some characters inside its content but there is no official + * escaping/unescaping for + * it so we made our own. + * + * @param content + * the XML comment content to unescape + * @return the unescaped content. + * @see #escapeXMLComment(String) + * @since 1.9M2 + */ + public static String unescapeXMLComment(String content) { + StringBuffer str = new StringBuffer(content.length()); + + char[] buff = content.toCharArray(); + boolean escaped = false; + for (char c : buff) { + if (!escaped && c == '\\') { + escaped = true; + continue; + } + + str.append(c); + escaped = false; + } + + return str.toString(); + } +} diff --git a/celements-xwiki-xml/src/main/java/org/xwiki/xml/internal/XMLScriptService.java b/celements-xwiki-xml/src/main/java/org/xwiki/xml/internal/XMLScriptService.java new file mode 100644 index 000000000..474c58d05 --- /dev/null +++ b/celements-xwiki-xml/src/main/java/org/xwiki/xml/internal/XMLScriptService.java @@ -0,0 +1,450 @@ +/* + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.xwiki.xml.internal; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.regex.Pattern; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSSerializer; +import org.xwiki.script.service.ScriptService; +import org.springframework.stereotype.Component; + +/** + * Provides Scripting APIs for handling XML. + * + * @version $Id$ + * @since 2.7M1 + */ +@Component("xml") +public class XMLScriptService implements ScriptService { + + /** Logging helper object. */ + private static final Logger LOG = LoggerFactory.getLogger(XMLScriptService.class); + + /** + * Xerces configuration parameter for disabling fetching and checking XMLs against their DTD. + */ + private static final String DISABLE_DTD_PARAM = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; + + /** XML encoding of the "ampersand" character. */ + private static final String AMP = "&"; + + /** Regular expression recognizing XML-escaped "ampersand" characters. */ + private static final Pattern AMP_PATTERN = Pattern.compile("&(?:amp|#0*+38|#x0*+26);"); + + /** XML encoding of the "single quote" character. */ + private static final String APOS = "'"; + + /** Regular expression recognizing XML-escaped "single quote" characters. */ + private static final Pattern APOS_PATTERN = Pattern.compile("&(?:apos|#0*+39|#x0*+27);"); + + /** XML encoding of the "double quote" character. */ + private static final String QUOT = """; + + /** Regular expression recognizing XML-escaped "double quote" characters. */ + private static final Pattern QUOT_PATTERN = Pattern.compile("&(?:quot|#0*+34|#x0*+22);"); + + /** XML encoding of the "less than" character. */ + private static final String LT = "<"; + + /** Regular expression recognizing XML-escaped "less than" characters. */ + private static final Pattern LT_PATTERN = Pattern.compile("&(?:lt|#0*+60|#x0*+3[cC]);"); + + /** XML encoding of the "greater than" character. */ + private static final String GT = ">"; + + /** Regular expression recognizing XML-escaped "greater than" characters. */ + private static final Pattern GT_PATTERN = Pattern.compile("&(?:gt|#0*+62|#x0*+3[eE]);"); + + /** Helper object for manipulating DOM Level 3 Load and Save APIs. */ + private DOMImplementationLS lsImpl; + + /** + * Default component constructor. + */ + public XMLScriptService() { + try { + this.lsImpl = (DOMImplementationLS) DOMImplementationRegistry.newInstance() + .getDOMImplementation("LS 3.0"); + } catch (Exception ex) { + LOG.warn("Cannot initialize the XML Script Service", ex); + } + } + + /** + * Escapes all the XML special characters in a String using numerical XML entities. + * Specifically, + * escapes <, >, ", ' and &. + * + * @param content + * the text to escape, may be {@code null} + * @return a new escaped {@code String}, {@code null} if {@code null} input + */ + public static String escape(Object content) { + return escapeForAttributeValue(content); + } + + /** + * Escapes all the XML special characters in a String using numerical XML entities, + * so that the + * resulting string can safely be used as an XML attribute value. Specifically, escapes <, + * >, ", ' and &. + * + * @param content + * the text to escape, may be {@code null} + * @return a new escaped {@code String}, {@code null} if {@code null} input + */ + public static String escapeForAttributeValue(Object content) { + if (content == null) { + return null; + } + String str = String.valueOf(content); + StringBuilder result = new StringBuilder((int) (str.length() * 1.1)); + int length = str.length(); + char c; + for (int i = 0; i < length; ++i) { + c = str.charAt(i); + switch (c) { + case '&': + result.append(AMP); + break; + case '\'': + result.append(APOS); + break; + case '"': + result.append(QUOT); + break; + case '<': + result.append(LT); + break; + case '>': + result.append(GT); + break; + default: + result.append(c); + } + } + return result.toString(); + } + + /** + * Escapes the XML special characters in a String using numerical XML entities, so + * that the resulting + * string can safely be used as an XML text node. Specifically, escapes <, >, and &. + * + * @param content + * the text to escape, may be {@code null} + * @return a new escaped {@code String}, {@code null} if {@code null} input + */ + public static String escapeForElementContent(Object content) { + if (content == null) { + return null; + } + String str = String.valueOf(content); + StringBuilder result = new StringBuilder((int) (str.length() * 1.1)); + int length = str.length(); + char c; + for (int i = 0; i < length; ++i) { + c = str.charAt(i); + switch (c) { + case '&': + result.append(AMP); + break; + case '<': + result.append(LT); + break; + case '>': + result.append(GT); + break; + default: + result.append(c); + } + } + return result.toString(); + } + + /** + * Unescape encoded special XML characters. Only >, < &, " and ' are unescaped, since + * they are the only + * ones that affect the resulting markup. + * + * @param content + * the text to decode, may be {@code null} + * @return unescaped content, {@code null} if {@code null} input + */ + public static String unescape(Object content) { + if (content == null) { + return null; + } + String str = String.valueOf(content); + + str = APOS_PATTERN.matcher(str).replaceAll("'"); + str = QUOT_PATTERN.matcher(str).replaceAll("\""); + str = LT_PATTERN.matcher(str).replaceAll("<"); + str = GT_PATTERN.matcher(str).replaceAll(">"); + str = AMP_PATTERN.matcher(str).replaceAll("&"); + + return str; + } + + /** + * Construct a new (empty) DOM Document and return it. + * + * @return an empty DOM Document + */ + public Document createDOMDocument() { + try { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException ex) { + LOG.error("Cannot create DOM Documents", ex); + return null; + } + } + + /** + * Parse a DOM Document from a source. + * + * @param source + * the source input to parse + * @return the equivalent DOM Document, or {@code null} if the parsing failed. + */ + public Document parse(LSInput source) { + try { + LSParser p = this.lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + // Disable validation, since this takes a lot of time and causes unneeded network + // traffic + p.getDomConfig().setParameter("validate", false); + if (p.getDomConfig().canSetParameter(DISABLE_DTD_PARAM, false)) { + p.getDomConfig().setParameter(DISABLE_DTD_PARAM, false); + } + return p.parse(source); + } catch (Exception ex) { + LOG.warn("Cannot parse XML document: " + ex.getMessage()); + return null; + } + } + + /** + * Parse a {@code byte[]} into a DOM Document. + * + * @param content + * the content to parse + * @return a DOM Document corresponding to the input, {@code null} if the content can't be + * parsed successfully + */ + public Document parse(byte[] content) { + if (content == null) { + return null; + } + LSInput input = this.lsImpl.createLSInput(); + input.setByteStream(new ByteArrayInputStream(content)); + return parse(input); + } + + /** + * Parse a {@code String} into a DOM Document. + * + * @param content + * the content to parse + * @return a DOM Document corresponding to the input, {@code null} if the content can't be + * parsed successfully + */ + public Document parse(String content) { + if (content == null) { + return null; + } + LSInput input = this.lsImpl.createLSInput(); + input.setCharacterStream(new StringReader(content)); + return parse(input); + } + + /** + * Parse an {@code InputStream} into a DOM Document. + * + * @param stream + * the content input to parse + * @return a DOM Document corresponding to the input, {@code null} if the content can't be + * parsed successfully + */ + public Document parse(InputStream stream) { + if (stream == null) { + return null; + } + LSInput input = this.lsImpl.createLSInput(); + input.setByteStream(stream); + return parse(input); + } + + /** + * Serialize a DOM Node into a string, including the XML declaration at the start. + * + * @param node + * the node to export + * @return the serialized node, or an empty string if the serialization fails + */ + public String serialize(Node node) { + return serialize(node, true); + } + + /** + * Serialize a DOM Node into a string, with an optional XML declaration at the start. + * + * @param node + * the node to export + * @param withXmlDeclaration + * whether to output the XML declaration or not + * @return the serialized node, or an empty string if the serialization fails or the node is + * {@code null} + */ + public String serialize(Node node, boolean withXmlDeclaration) { + if (node == null) { + return ""; + } + if (node.getNodeType() == Node.DOCUMENT_TYPE_NODE) { + return ""; + } + try { + LSOutput output = this.lsImpl.createLSOutput(); + StringWriter result = new StringWriter(); + output.setCharacterStream(result); + LSSerializer serializer = this.lsImpl.createLSSerializer(); + serializer.getDomConfig().setParameter("xml-declaration", withXmlDeclaration); + serializer.setNewLine("\n"); + String encoding = "UTF-8"; + if (node instanceof Document) { + encoding = ((Document) node).getXmlEncoding(); + } else if (node.getOwnerDocument() != null) { + encoding = node.getOwnerDocument().getXmlEncoding(); + } + output.setEncoding(encoding); + serializer.write(node, output); + + String xmlString = result.toString(); + if (withXmlDeclaration && xmlString.startsWith("]*\\?>)(?!\\r?\\n)", "$1\n"); + } + if (xmlString.contains("]*>)(?!\\r?\\n)", "$1\n"); + } + return xmlString; + } catch (Exception ex) { + LOG.warn("Failed to serialize node to XML String", ex); + return ""; + } + } + + /** + * Apply an XSLT transformation to a Document. + * + * @param xml + * the document to transform + * @param xslt + * the stylesheet to apply + * @return the transformation result, or {@code null} if an error occurs or {@code null} xml or + * xslt input + */ + public String transform(Source xml, Source xslt) { + if (xml != null && xslt != null) { + try { + StringWriter output = new StringWriter(); + Result result = new StreamResult(output); + javax.xml.transform.TransformerFactory.newInstance().newTransformer(xslt) + .transform(xml, result); + return output.toString(); + } catch (Exception ex) { + LOG.warn("Failed to apply XSLT transformation: " + ex.getMessage()); + } + } + return null; + } + + /** + * Apply an XSLT transformation to a Document, both given as DOM Documents. + * + * @param xml + * the document to transform + * @param xslt + * the stylesheet to apply + * @return the transformation result, or {@code null} if an error occurs or {@code null} xml or + * xslt input + */ + public String transform(Document xml, Document xslt) { + if (xml == null || xslt == null) { + return null; + } + return transform(new DOMSource(xml), new DOMSource(xslt)); + } + + /** + * Apply an XSLT transformation to a Document, both given as byte arrays. + * + * @param xml + * the document to transform + * @param xslt + * the stylesheet to apply + * @return the transformation result, or {@code null} if an error occurs or {@code null} xml or + * xslt input + */ + public String transform(byte[] xml, byte[] xslt) { + if (xml == null || xslt == null) { + return null; + } + return transform(new StreamSource(new ByteArrayInputStream(xml)), + new StreamSource(new ByteArrayInputStream(xslt))); + } + + /** + * Apply an XSLT transformation to a Document, both given as strings. + * + * @param xml + * the document to transform + * @param xslt + * the stylesheet to apply + * @return the transformation result, or {@code null} if an error occurs or {@code null} xml or + * xslt input + */ + public String transform(String xml, String xslt) { + if (xml == null || xslt == null) { + return null; + } + return transform(new StreamSource(new StringReader(xml)), + new StreamSource(new StringReader(xslt))); + } +} diff --git a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/VoidWikiPrinter.java b/celements-xwiki-xml/src/test/java/org/xwiki/xml/XMLUtilsTest.java similarity index 51% rename from celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/VoidWikiPrinter.java rename to celements-xwiki-xml/src/test/java/org/xwiki/xml/XMLUtilsTest.java index 7a5d953aa..60d7d2cbd 100644 --- a/celements-xwiki-rendering-api/src/main/java/org/xwiki/rendering/renderer/printer/VoidWikiPrinter.java +++ b/celements-xwiki-xml/src/test/java/org/xwiki/xml/XMLUtilsTest.java @@ -16,41 +16,41 @@ * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + * */ -package org.xwiki.rendering.renderer.printer; +package org.xwiki.xml; + +import org.xwiki.test.AbstractXWikiComponentTestCase; /** - * A WikiPrinter implementation which does not do anything. + * Unit tests for {@link org.xwiki.xml.XMLUtils}. * * @version $Id$ + * @since 1.6M1 */ -public class VoidWikiPrinter implements WikiPrinter { - - /** - * Unique instance of {@link VoidWikiPrinter}. - */ - public static final VoidWikiPrinter VOIDWIKIPRINTER = new VoidWikiPrinter(); - - /** - * Use {@link #VOIDWIKIPRINTER}. - */ - private VoidWikiPrinter() {} +public class XMLUtilsTest extends AbstractXWikiComponentTestCase { /** * {@inheritDoc} * - * @see org.xwiki.rendering.renderer.printer.WikiPrinter#print(java.lang.String) + * @see org.xwiki.test.AbstractXWikiComponentTestCase#setUp() */ - public void print(String text) { - // Don't do anything + @Override + protected void setUp() throws Exception { + super.setUp(); } - /** - * {@inheritDoc} - * - * @see org.xwiki.rendering.renderer.printer.WikiPrinter#println(java.lang.String) - */ - public void println(String text) { - // Don't do anything + public void testEscapeXMLComment() { + assertEquals("-\\- ", XMLUtils.escapeXMLComment("-- ")); + assertEquals("-\\", XMLUtils.escapeXMLComment("-")); + assertEquals("-\\-\\-\\", XMLUtils.escapeXMLComment("---")); + assertEquals("- ", XMLUtils.escapeXMLComment("- ")); + } + + public void testUnescapeXMLComment() { + assertEquals("", XMLUtils.unescapeXMLComment("\\")); + assertEquals("\\", XMLUtils.unescapeXMLComment("\\\\")); + assertEquals("--", XMLUtils.unescapeXMLComment("\\-\\-")); + assertEquals("--", XMLUtils.unescapeXMLComment("\\-\\-\\")); } } diff --git a/celements-xwiki-xml/src/test/java/org/xwiki/xml/internal/XMLScriptServiceTest.java b/celements-xwiki-xml/src/test/java/org/xwiki/xml/internal/XMLScriptServiceTest.java new file mode 100644 index 000000000..4b8749ed1 --- /dev/null +++ b/celements-xwiki-xml/src/test/java/org/xwiki/xml/internal/XMLScriptServiceTest.java @@ -0,0 +1,492 @@ +/* + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.xwiki.xml.internal; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.transform.stream.StreamSource; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.ls.LSInput; +import org.xwiki.script.service.ScriptService; +import com.celements.common.test.AbstractBaseComponentTest; + +/** + * Unit tests for {@link XMLScriptService}. + * + * @version $Id$ + * @since 2.7RC1 + */ +public class XMLScriptServiceTest extends AbstractBaseComponentTest { + + private XMLScriptService xml; + + @Before + public void prepare_XMLScriptServiceTest() throws Exception { + this.xml = (XMLScriptService) getBeanFactory().getBean(XMLScriptService.class); + } + + @Test + public void testEscape() { + String escapedText = XMLScriptService.escape("a < a' && a' < a\" => a < a\""); + + Assert.assertFalse("Failed to escape <", escapedText.contains("<")); + Assert.assertFalse("Failed to escape >", escapedText.contains(">")); + Assert.assertFalse("Failed to escape '", escapedText.contains("'")); + Assert.assertFalse("Failed to escape \"", escapedText.contains("\"")); + Assert.assertFalse("Failed to escape &", escapedText.contains("&&")); + } + + @Test + public void testEscapeApos() { + Assert.assertFalse("' wrongly escaped to non-HTML '", + XMLScriptService.escape("'").equals("'")); + } + + @Test + public void testEscapeEmptyString() { + Assert.assertEquals("\"\" should be \"\"", "", XMLScriptService.escape("")); + } + + @Test + public void testEscapeWithNull() { + Assert.assertNull("null should be null", XMLScriptService.escape(null)); + } + + @Test + public void testEscapeNonAscii() { + Assert.assertTrue("Non-ASCII characters were escaped", + XMLScriptService.escape("\u0123").equals("\u0123")); + } + + @Test + public void testEscapeForAttributeValue() { + + String escapedText = XMLScriptService + .escapeForAttributeValue("a < a' && a' < a\" => a < a\""); + + Assert.assertFalse("Failed to escape <", escapedText.contains("<")); + Assert.assertFalse("Failed to escape >", escapedText.contains(">")); + Assert.assertFalse("Failed to escape '", escapedText.contains("'")); + Assert.assertFalse("Failed to escape \"", escapedText.contains("\"")); + Assert.assertFalse("Failed to escape &", escapedText.contains("&&")); + } + + @Test + public void testEscapeForAttributeValueApos() { + Assert.assertFalse("' wrongly escaped to non-HTML '", + XMLScriptService.escapeForAttributeValue("'") + .equals("'")); + } + + @Test + public void testEscapeForAttributeValueEmptyString() { + Assert.assertEquals("\"\" should be \"\"", "", + XMLScriptService.escapeForAttributeValue("")); + } + + @Test + public void testEscapeForAttributeValueWithNull() { + Assert.assertNull("null should be null", XMLScriptService.escapeForAttributeValue(null)); + } + + @Test + public void testEscapeForAttributeValueNonAscii() { + Assert.assertTrue("Non-ASCII characters were escaped", + XMLScriptService.escapeForAttributeValue("\u0123") + .equals("\u0123")); + } + + @Test + public void testEscapeForElementContent() { + + String escapedText = XMLScriptService + .escapeForElementContent("a < a' && a' < a\" => a < a\""); + + Assert.assertFalse("Failed to escape <", escapedText.contains("<")); + Assert.assertFalse("Failed to escape >", escapedText.contains(">")); + Assert.assertTrue("Wrongfully escaped '", escapedText.contains("'")); + Assert.assertTrue("Wrongfully escaped \"", escapedText.contains("\"")); + Assert.assertFalse("Failed to escape &", escapedText.contains("&&")); + } + + @Test + public void testEscapeForElementContentEmptyString() { + Assert.assertEquals("\"\" should be \"\"", "", + XMLScriptService.escapeForElementContent("")); + } + + @Test + public void testEscapeForElementContentWithNull() { + Assert.assertNull("null should be null", XMLScriptService.escapeForElementContent(null)); + } + + @Test + public void testEscapeForElementContentNonAscii() { + Assert.assertTrue("Non-ASCII characters were escaped", + XMLScriptService.escapeForElementContent("\u0123") + .equals("\u0123")); + } + + @Test + public void testUnescape() { + Assert.assertEquals("Failed to unescaped named entities", "&'\"<>", + XMLScriptService.unescape("&'"<>")); + Assert.assertEquals("Failed to unescaped decimal entities", "&'\"<>", + XMLScriptService.unescape("&'"<>")); + Assert.assertEquals("Failed to unescaped decimal entities with leading zeros", "&'\"<>", + XMLScriptService.unescape("&'"<>")); + Assert.assertEquals("Failed to unescaped hexadecimal entities", "&'\"<<>>", + XMLScriptService.unescape("&'"<<>>")); + Assert.assertEquals("Failed to unescaped hexadecimal entities with leading zeros", + "&'\"<<>>", + XMLScriptService + .unescape("&'"<<>>")); + } + + @Test + public void testUnescapeEmptyString() { + Assert.assertEquals("\"\" should be \"\"", "", XMLScriptService.unescape("")); + } + + @Test + public void testUnescapeWithNull() { + Assert.assertNull("null should be null", XMLScriptService.unescape(null)); + } + + @Test + public void testUnescapeOtherEscapes() { + Assert.assertEquals("Extra named entities were unescaped", "°", + XMLScriptService.unescape("°")); + Assert.assertEquals("Extra decimal entities were unescaped", "A", + XMLScriptService.unescape("A")); + Assert.assertEquals("Extra hexadecimal entities were unescaped", "", + XMLScriptService.unescape("")); + } + + @Test + public void testGetDomDocument() { + // Nothing much that we can test here... + Assert.assertNotNull(this.xml.createDOMDocument()); + } + + @Test + public void testParseString() { + Document result = this.xml + .parse("d"); + Assert.assertNotNull("Failed to parse content", result); + Assert.assertEquals("Incorrect root node", "a", result.getDocumentElement().getLocalName()); + } + + @Test + public void testParseByteArray() throws UnsupportedEncodingException { + Document result = this.xml.parse( + "d".getBytes("UTF-8")); + Assert.assertNotNull("Failed to parse content", result); + Assert.assertEquals("Incorrect root node", "a", result.getDocumentElement().getLocalName()); + } + + @Test + public void testParseInputStream() throws UnsupportedEncodingException { + Document result = this.xml.parse( + new ByteArrayInputStream("d" + .getBytes("UTF-8"))); + Assert.assertNotNull("Failed to parse content", result); + Assert.assertEquals("Incorrect root node", "a", result.getDocumentElement().getLocalName()); + } + + @Test + public void testParseWithDifferentEncoding() throws UnsupportedEncodingException { + Document result = this.xml + .parse("\u00E9" + .getBytes("ISO-8859-1")); + Assert.assertNotNull("Failed to parse content", result); + Assert.assertEquals("Incorrect root node", "a", result.getDocumentElement().getLocalName()); + Assert.assertEquals("Incorrect content", "\u00E9", + result.getDocumentElement().getTextContent()); + } + + @Test + public void testParseWithWrongEncoding() throws UnsupportedEncodingException { + Document result = this.xml.parse( + "\u00E9".getBytes("ISO-8859-1")); + Assert.assertNull("Content should be invalid with the specified encoding", result); + } + + @Test + public void testParseWithoutXMLDeclaration() { + Document result = this.xml.parse("\u00E9"); + Assert.assertNotNull("Failed to parse content", result); + Assert.assertEquals("Incorrect root node", "a", result.getDocumentElement().getLocalName()); + } + + @Test + public void testParseInvalidDocument() throws UnsupportedEncodingException { + Document result = this.xml.parse(""); + Assert.assertNull("Invalid content shouldn't be parsed", result); + } + + @Test + public void testParseNull() { + Document result = this.xml.parse((String) null); + Assert.assertNull("Null Document input shouldn't be parsed", result); + result = this.xml.parse((byte[]) null); + Assert.assertNull("Null byte[] input shouldn't be parsed", result); + result = this.xml.parse((ByteArrayInputStream) null); + Assert.assertNull("Null InputStream input shouldn't be parsed", result); + result = this.xml.parse((LSInput) null); + Assert.assertNull("Null LSInput input shouldn't be parsed", result); + } + + @Test + public void testParseAndSerialize() { + String content = "\n\u00E9"; + String result = this.xml.serialize(this.xml.parse(content)); + Assert.assertEquals("Not identical content after parse + serialize", content, result); + + content = "\n\u00E9"; + result = this.xml.serialize(this.xml.parse(content)); + Assert.assertEquals("Not identical content after parse + serialize", content, result); + + content = "\u00E9"; + result = this.xml.serialize(this.xml.parse(content), false); + Assert.assertEquals("Not identical content after parse + serialize", content, result); + } + + @Test + public void testSerialize() { + Document d = createSimpleDocument(); + String result = this.xml.serialize(d); + Assert.assertEquals("Wrong serialization", + "\n\u00E9", result); + } + + @Test + public void testSerializeDocumentElement() { + Document d = createSimpleDocument(); + String result = this.xml.serialize(d.getDocumentElement()); + Assert.assertEquals("Wrong serialization", + "\n\u00E9", result); + } + + @Test + public void testSerializeNode() { + Document d = createSimpleDocument(); + Element b = d.createElement("b"); + b.setTextContent("c"); + d.getDocumentElement().appendChild(b); + String result = this.xml + .serialize(d.getDocumentElement().getElementsByTagName("b").item(0)); + Assert.assertEquals("Wrong serialization", + "\nc", result); + } + + @Test + public void testSerializeNull() { + Assert.assertEquals("Wrong serialization for null document", "", this.xml.serialize(null)); + } + + public void testSerializeWithoutXmlDeclaration() { + Document d = createSimpleDocument(); + String result = this.xml.serialize(d.getDocumentElement(), false); + Assert.assertEquals("Wrong serialization", "\u00E9", result); + } + + @Test + public void testNewlineSerialization() { + Document d = this.xml.parse("a\nb\n"); + String result = this.xml.serialize(d, false); + Assert.assertEquals("Wrong newlines", "a\nb\n", result); + + d = this.xml.parse("a\r\nb\r\n"); + result = this.xml.serialize(d, false); + Assert.assertEquals("Wrong newlines", "a\nb\n", result); + + d = this.xml.parse("a\rb\r"); + result = this.xml.serialize(d, false); + Assert.assertEquals("Wrong newlines", "a\nb\n", result); + } + + @Test + public void testSerializationWithDoctype() { + Document d = this.xml.parse("" + + "" + + "a"); + String result = this.xml.serialize(d, true); + Assert.assertEquals("Failed Doctype", "\n" + + "\n" + + "a", result); + result = this.xml.serialize(d, false); + Assert.assertEquals("Failed Doctype", + "\n" + + "a", + result); + } + + @Test + public void testDoctypeSerialization() { + Document d = this.xml.parse("" + + "" + + "a"); + String result = this.xml.serialize(d.getDoctype(), true); + Assert.assertEquals("Doctype alone shouldn't be serialized", "", result); + } + + @Test + public void testSerializeToSmallerCharset() { + Document d = this.xml.parse("\u0345"); + String result = this.xml.serialize(d); + Assert.assertFalse("Non-latin1 character shouldn't be present in the output", + result.contains("\u0345")); + } + + @Test + public void testTransformDocument() { + Document d = this.xml.parse("d"); + Document s = this.xml.parse( + "" + + "" + + ""); + String result = this.xml.transform(d, s); + Assert.assertEquals("", result); + } + + @Test + public void testTransformByteArray() throws UnsupportedEncodingException { + byte[] d = "d".getBytes("UTF-8"); + byte[] s = ("" + + "" + + + "" + + "") + .getBytes("UTF-8"); + String result = this.xml.transform(d, s); + Assert.assertEquals("", result); + } + + @Test + public void testTransformString() throws UnsupportedEncodingException { + String d = "d"; + String s = "" + + "" + + + "" + + ""; + String result = this.xml.transform(d, s); + Assert.assertEquals("", result); + } + + @Test + public void testTransformWithNullInputs() { + StreamSource d = new StreamSource(new StringReader("d")); + StreamSource s = new StreamSource(new StringReader( + "" + + "")); + String result = this.xml.transform(null, s); + Assert.assertNull(null, result); + result = this.xml.transform(d, null); + Assert.assertNull(null, result); + result = this.xml.transform((StreamSource) null, (StreamSource) null); + Assert.assertNull(null, result); + } + + @Test + public void testTransformWithNullDocuments() { + Document d = this.xml.parse("d"); + Document s = this.xml.parse( + "" + + ""); + String result = this.xml.transform(null, s); + Assert.assertNull(null, result); + result = this.xml.transform(d, null); + Assert.assertNull(null, result); + result = this.xml.transform((Document) null, (Document) null); + Assert.assertNull(null, result); + } + + @Test + public void testTransformWithNullStrings() { + String d = "d"; + String s = "" + + + ""; + String result = this.xml.transform(null, s); + Assert.assertNull(null, result); + result = this.xml.transform(d, null); + Assert.assertNull(null, result); + result = this.xml.transform((String) null, (String) null); + Assert.assertNull(null, result); + } + + @Test + public void testTransformWithNullByteArrays() throws UnsupportedEncodingException { + byte[] d = "d".getBytes("UTF-8"); + byte[] s = ("" + + + "") + .getBytes(); + String result = this.xml.transform(null, s); + Assert.assertNull(null, result); + result = this.xml.transform(d, null); + Assert.assertNull(null, result); + result = this.xml.transform((byte[]) null, (byte[]) null); + Assert.assertNull(null, result); + } + + @Test + public void testTransformWithInvalidSheet() { + Document d = this.xml.parse("d"); + Document s = this.xml.parse( + "" + + ""); + String result = this.xml.transform(s, d); + Assert.assertEquals(null, result); + } + + @Test + public void testTransformToText() { + Document d = this.xml.parse("d"); + Document s = this.xml.parse( + "" + + "" + + ""); + String result = this.xml.transform(d, s); + Assert.assertEquals("c", result); + } + + private Document createSimpleDocument() { + Document d = this.xml.createDOMDocument(); + Element a = d.createElement("a"); + a.setTextContent("\u00E9"); + d.appendChild(a); + return d; + } +}