You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jspwiki.apache.org by ju...@apache.org on 2020/01/16 23:07:20 UTC

[jspwiki] branch master updated (53f18f1 -> ffee109)

This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git.


    from 53f18f1  jacoco report generation must be run after tests
     new e7ba61c  rename RenderingManager as DefaultRenderingManager and extract new interface RenderingManager from it
     new 06ee246  apply suggested fixes + formatting by intellij
     new 4c5940f  move RenderingManager#WYSIWYG_EDITOR_MODE constant to WikiContext#VAR_WYSIWYG_EDITOR_MODE
     new bee886f  small fix suggested by intellij
     new 13f2d0d  move RenderingManager#VAR_EXECUTE_PLUGINS constant to WikiContext
     new a2da4a8  format code
     new 5851edd  extract text nodes extraction routine from Dom to XmlUtils
     new 373f662  format code
     new f2c5378  move WikiEngine renderer-related property names to RenderingManager
     new 5fad1e7  Update ASF parent pom + plugin definitions to support, as far as possible, reproducible builds
     new 4e2ca71  fix bug from previous refactor: parsed WikiDocument containing title must have the associated WikiContext
     new 1683e30  JSPWIKI-120: move beautifyTitle and beautifyTitleNoBreak from WikiEngine to PageManager
     new 835e737  apply suggested intellij format
     new 9388271  apply suggested intellij format
     new a08cf8a  apply suggested intellij format
     new b5d0f0f  apply format & fixes suggested by intellij
     new 0f6c61a  code cleanup
     new 3729e43  JSPWIKI-120: moved textToHtml(..) methods from WikiEngine to RenderingManager
     new 6a83a53  JSPWIKI-120: move remaining textToHtml(..) method from WikiEngine to PageManager
     new e85155e  use new VariableManager#VAR_RUNFILTERS instead of old WikiEngine#PROP_RUNFILTERS on jsps
     new cc80037  JSPWIKI-120: moved getHTML methods from WikiEngine to PageManager
     new df2e164  refactor add*LinkHook( StringTransmutator ) common behaviour
     new d518941  apply further formatting
     new b39c263  moved MarkupParser#cleanLink( String, String ) to TextUtil.cleanString( String, String )
     new f166f1e  unit test 1.000 ?!
     new ffee109  2.11.0-M7-git-05

The 26 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 ChangeLog.md                                       |  16 +
 .../main/java/org/apache/wiki/LinkCollector.java   |   2 +-
 .../src/main/java/org/apache/wiki/Release.java     |  64 ++--
 .../src/main/java/org/apache/wiki/WikiContext.java |   9 +
 .../src/main/java/org/apache/wiki/WikiEngine.java  | 253 +-------------
 .../wiki/ajax/WikiAjaxDispatcherServlet.java       |   2 +-
 .../java/org/apache/wiki/auth/acl/AclImpl.java     | 120 +++----
 .../apache/wiki/auth/acl/DefaultAclManager.java    | 140 ++++----
 .../org/apache/wiki/event/PageEventFilter.java     |  96 ++----
 .../java/org/apache/wiki/event/WikiEventUtils.java |   4 +-
 .../java/org/apache/wiki/event/WikiPageEvent.java  |  18 +-
 .../apache/wiki/filters/DefaultFilterManager.java  | 182 ++++------
 .../org/apache/wiki/modules/WikiModuleInfo.java    |  74 ++---
 .../apache/wiki/parser/JSPWikiMarkupParser.java    | 141 +++-----
 .../apache/wiki/parser/LinkParsingOperations.java  |  36 +-
 .../java/org/apache/wiki/parser/MarkupParser.java  | 314 ++++++------------
 .../org/apache/wiki/parser/ParseException.java     |  12 +-
 .../java/org/apache/wiki/parser/PluginContent.java | 161 ++++-----
 .../org/apache/wiki/parser/VariableContent.java    |  56 ++--
 .../java/org/apache/wiki/parser/WikiDocument.java  |  41 +--
 .../apache/wiki/plugin/AbstractReferralPlugin.java |   2 +-
 .../main/java/org/apache/wiki/plugin/IfPlugin.java |   2 +-
 .../java/org/apache/wiki/plugin/InsertPage.java    |   2 +-
 .../org/apache/wiki/plugin/PageViewPlugin.java     |   4 +-
 .../apache/wiki/plugin/RecentChangesPlugin.java    |  93 +++---
 .../main/java/org/apache/wiki/plugin/Search.java   |  20 +-
 .../org/apache/wiki/plugin/TableOfContents.java    |   3 +-
 .../java/org/apache/wiki/plugin/WeblogPlugin.java  | 276 ++++++----------
 .../wiki/references/DefaultReferenceManager.java   |  15 +-
 .../org/apache/wiki/render/CleanTextRenderer.java  |  30 +-
 .../wiki/render/CustomXMLOutputProcessor.java      |   5 +-
 ...ngManager.java => DefaultRenderingManager.java} | 288 ++++++++++------
 .../org/apache/wiki/render/RenderingManager.java   | 361 ++++++++------------
 .../java/org/apache/wiki/render/XHTMLRenderer.java |   5 +-
 .../main/java/org/apache/wiki/rss/AtomFeed.java    |  46 +--
 .../java/org/apache/wiki/rss/RSSGenerator.java     |   6 +-
 .../apache/wiki/search/LuceneSearchProvider.java   | 264 ++++++---------
 .../java/org/apache/wiki/tags/InsertPageTag.java   |   2 +-
 .../java/org/apache/wiki/tags/PageNameTag.java     |  30 +-
 .../org/apache/wiki/tags/ParentPageNameTag.java    |  48 +--
 .../java/org/apache/wiki/tags/TranslateTag.java    |   2 +-
 .../apache/wiki/tasks/pages/SaveWikiPageTask.java  |  16 +-
 .../wiki/variables/DefaultVariableManager.java     |  65 +---
 .../org/apache/wiki/variables/VariableManager.java |  10 +-
 .../java/org/apache/wiki/workflow/Workflow.java    |  13 +-
 .../org/apache/wiki/xmlrpc/MetaWeblogHandler.java  |  86 ++---
 .../java/org/apache/wiki/xmlrpc/RPCHandler.java    |  91 +++--
 .../org/apache/wiki/xmlrpc/RPCHandlerUTF8.java     |   6 +-
 .../src/main/resources/ini/classmappings.xml       |   2 +-
 .../src/test/java/org/apache/wiki/TestEngine.java  |   2 +-
 .../test/java/org/apache/wiki/WikiEngineTest.java  |  58 +---
 .../apache/wiki/pages/DefaultPageManagerTest.java  |   4 +-
 .../wiki/parser/JSPWikiMarkupParserTest.java       |  24 +-
 .../wiki/plugin/DefaultPluginManagerTest.java      |   2 +-
 .../java/org/apache/wiki/plugin/GroupsTest.java    |   2 +-
 .../java/org/apache/wiki/plugin/IfPluginTest.java  |  14 +-
 .../org/apache/wiki/plugin/InsertPageTest.java     |  42 +--
 .../org/apache/wiki/plugin/PageViewPluginTest.java |  36 +-
 .../wiki/plugin/UndefinedPagesPluginTest.java      |  58 ++--
 .../apache/wiki/render/RenderingManagerTest.java   |  55 +++
 .../wiki/render/WysiwygEditingRendererTest.java    |  43 +--
 .../apache/wiki/stress/MassiveRepositoryTest.java  |   2 +-
 .../InterWikiLinkAttributeProviderState.java       |  10 +-
 .../WysiwygEditingAttributeProviderState.java      |  22 +-
 .../AccessRuleLinkNodePostProcessorState.java      |   5 +-
 .../InterWikiLinkNodePostProcessorState.java       |   5 +-
 .../JSPWikiLinkNodePostProcessor.java              |   8 +-
 .../MetadataLinkNodePostProcessorState.java        |   7 +-
 .../NodePostProcessorStateCommonOperations.java    |   5 +-
 .../PluginLinkNodePostProcessorState.java          |   5 +-
 .../VariableLinkNodePostProcessorState.java        |   5 +-
 .../markdown/renderer/JSPWikiLinkRenderer.java     |  15 +-
 .../wiki/parser/markdown/MarkdownDocument.java     |   2 +-
 .../wiki/parser/markdown/MarkdownParser.java       |  13 +-
 .../apache/wiki/render/MarkdownRendererTest.java   | 126 +++----
 .../main/java/org/apache/wiki/util/TextUtil.java   | 368 +++++++++++----------
 .../main/java/org/apache/wiki/util/XmlUtil.java    |  73 ++--
 .../java/org/apache/wiki/util/TextUtilTest.java    |   7 +
 .../java/org/apache/wiki/util/XmlUtilTest.java     |  19 +-
 .../main/webapp/templates/210/editors/CKeditor.jsp |  14 +-
 .../src/main/webapp/templates/210/editors/FCK.jsp  |  13 +-
 .../main/webapp/templates/210/editors/TinyMCE.jsp  |  23 +-
 .../webapp/templates/default/editors/CKeditor.jsp  |  16 +-
 .../webapp/templates/default/editors/TinyMCE.jsp   |  18 +-
 .../webapp/templates/default/editors/wysiwyg.jsp   |  17 +-
 pom.xml                                            |  31 +-
 86 files changed, 1909 insertions(+), 2794 deletions(-)
 copy jspwiki-main/src/main/java/org/apache/wiki/render/{RenderingManager.java => DefaultRenderingManager.java} (64%)


[jspwiki] 16/26: apply format & fixes suggested by intellij

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit b5d0f0fb50828cf06936275f21e70b1f05bd266b
Author: juanpablo <ju...@apache.org>
AuthorDate: Tue Jan 14 23:43:51 2020 +0100

    apply format & fixes suggested by intellij
---
 .../apache/wiki/filters/DefaultFilterManager.java  | 182 +++++++--------------
 .../org/apache/wiki/modules/WikiModuleInfo.java    |  74 ++++-----
 2 files changed, 90 insertions(+), 166 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java b/jspwiki-main/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
index c6695a3..6409ee0 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/filters/DefaultFilterManager.java
@@ -40,15 +40,13 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.util.Collection;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 
 
 /**
- *  Manages the page filters.  Page filters are components that can be executed
- *  at certain places:
+ *  Manages the page filters.  Page filters are components that can be executed at certain places:
  *  <ul>
  *    <li>Before the page is translated into HTML.
  *    <li>After the page has been translated into HTML.
@@ -56,12 +54,10 @@ import java.util.Properties;
  *    <li>After the page has been saved.
  *  </ul>
  *
- *  Using page filters allows you to modify the page data on-the-fly, and do things like
- *  adding your own custom WikiMarkup.
+ *  Using page filters allows you to modify the page data on-the-fly, and do things like adding your own custom WikiMarkup.
  *
  *  <p>
- *  The initial page filter configuration is kept in a file called "filters.xml".  The
- *  format is really very simple:
+ *  The initial page filter configuration is kept in a file called "filters.xml".  The format is really very simple:
  *  <pre>
  *  <?xml version="1.0"?>
  *  &lt;pagefilters>
@@ -87,14 +83,13 @@ import java.util.Properties;
  *  &lt;/pagefilters>
  *  </pre>
  *
- *  The &lt;filter> -sections define the filters.  For more information, please see
- *  the PageFilterConfiguration page in the JSPWiki distribution.
+ *  The &lt;filter> -sections define the filters.  For more information, please see the PageFilterConfiguration page in the JSPWiki distribution.
  */
 public class DefaultFilterManager extends ModuleManager implements FilterManager {
 
-    private PriorityList< PageFilter > m_pageFilters = new PriorityList< PageFilter >();
+    private PriorityList< PageFilter > m_pageFilters = new PriorityList<>();
 
-    private Map< String, PageFilterInfo > m_filterClassMap = new HashMap< String, PageFilterInfo >();
+    private Map< String, PageFilterInfo > m_filterClassMap = new HashMap<>();
 
     private static final Logger log = Logger.getLogger(DefaultFilterManager.class);
 
@@ -105,78 +100,54 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *  @param props Properties to initialize the FilterManager with
      *  @throws WikiException If something goes wrong.
      */
-    public DefaultFilterManager( WikiEngine engine, Properties props )
-        throws WikiException
-    {
+    public DefaultFilterManager( final WikiEngine engine, final Properties props ) throws WikiException {
         super( engine );
         initialize( props );
     }
 
     /**
-     *  Adds a page filter to the queue.  The priority defines in which
-     *  order the page filters are run, the highest priority filters go
+     *  Adds a page filter to the queue.  The priority defines in which order the page filters are run, the highest priority filters go
      *  in the queue first.
      *  <p>
-     *  In case two filters have the same priority, their execution order
-     *  is the insertion order.
+     *  In case two filters have the same priority, their execution order is the insertion order.
      *
      *  @since 2.1.44.
      *  @param f PageFilter to add
      *  @param priority The priority in which position to add it in.
      *  @throws IllegalArgumentException If the PageFilter is null or invalid.
      */
-    public void addPageFilter( PageFilter f, int priority ) throws IllegalArgumentException
-    {
-        if( f == null )
-        {
+    public void addPageFilter( final PageFilter f, final int priority ) throws IllegalArgumentException {
+        if( f == null ) {
             throw new IllegalArgumentException("Attempt to provide a null filter - this should never happen.  Please check your configuration (or if you're a developer, check your own code.)");
         }
 
         m_pageFilters.add( f, priority );
     }
 
-    private void initPageFilter( String className, Properties props )
-    {
-        try
-        {
-            PageFilterInfo info = m_filterClassMap.get( className );
-
-            if( info != null && !checkCompatibility(info) )
-            {
-                String msg = "Filter '"+info.getName()+"' not compatible with this version of JSPWiki";
-                log.warn(msg);
+    private void initPageFilter( final String className, final Properties props ) {
+        try {
+            final PageFilterInfo info = m_filterClassMap.get( className );
+            if( info != null && !checkCompatibility( info ) ) {
+                log.warn( "Filter '" + info.getName() + "' not compatible with this version of JSPWiki" );
                 return;
             }
 
-            int priority = 0; // FIXME: Currently fixed.
-
-            Class< ? > cl = ClassUtil.findClass( "org.apache.wiki.filters", className );
-
-            PageFilter filter = (PageFilter)cl.newInstance();
-
+            final int priority = 0; // FIXME: Currently fixed.
+            final Class< ? > cl = ClassUtil.findClass( "org.apache.wiki.filters", className );
+            final PageFilter filter = (PageFilter)cl.newInstance();
             filter.initialize( m_engine, props );
 
             addPageFilter( filter, priority );
             log.info("Added page filter "+cl.getName()+" with priority "+priority);
-        }
-        catch( ClassNotFoundException e )
-        {
+        } catch( final ClassNotFoundException e ) {
             log.error("Unable to find the filter class: "+className);
-        }
-        catch( InstantiationException e )
-        {
+        } catch( final InstantiationException e ) {
             log.error("Cannot create filter class: "+className);
-        }
-        catch( IllegalAccessException e )
-        {
+        } catch( final IllegalAccessException e ) {
             log.error("You are not allowed to access class: "+className);
-        }
-        catch( ClassCastException e )
-        {
+        } catch( final ClassCastException e ) {
             log.error("Suggested class is not a PageFilter: "+className);
-        }
-        catch( FilterException e )
-        {
+        } catch( final FilterException e ) {
             log.error("Filter "+className+" failed to initialize itself.", e);
         }
     }
@@ -188,9 +159,9 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *  @param props The list of properties.  Typically jspwiki.properties
      *  @throws WikiException If something goes wrong.
      */
-    protected void initialize( Properties props ) throws WikiException {
+    protected void initialize( final Properties props ) throws WikiException {
         InputStream xmlStream = null;
-        String xmlFile = props.getProperty( PROP_FILTERXML ) ;
+        final String xmlFile = props.getProperty( PROP_FILTERXML ) ;
 
         try {
             registerFilters();
@@ -221,14 +192,12 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
             }
 
             if( xmlStream == null ) {
-                log.info( "Cannot find property file for filters (this is okay, expected to find it as: '" +
-                           ( xmlFile == null ? DEFAULT_XMLFILE : xmlFile ) +
-                          "')" );
+                log.info( "Cannot find property file for filters (this is okay, expected to find it as: '" + DEFAULT_XMLFILE + "')" );
                 return;
             }
 
             parseConfigFile( xmlStream );
-        } catch( IOException e ) {
+        } catch( final IOException e ) {
             log.error("Unable to read property file", e);
         } finally {
             try {
@@ -246,16 +215,13 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *
      * @param xmlStream stream to parse
      */
-    private void parseConfigFile( InputStream xmlStream ) {
-    	List< Element > pageFilters = XmlUtil.parse( xmlStream, "/pagefilters/filter" );
-        for( Iterator< Element > i = pageFilters.iterator(); i.hasNext(); ) {
-            Element f = i.next();
-            String filterClass = f.getChildText( "class" );
-            Properties props = new Properties();
-
-            List< Element > params = f.getChildren( "param" );
-            for( Iterator< Element > par = params.iterator(); par.hasNext(); ) {
-                Element p = par.next();
+    private void parseConfigFile( final InputStream xmlStream ) {
+    	final List< Element > pageFilters = XmlUtil.parse( xmlStream, "/pagefilters/filter" );
+        for( final Element f : pageFilters ) {
+            final String filterClass = f.getChildText( "class" );
+            final Properties props = new Properties();
+            final List<Element> params = f.getChildren( "param" );
+            for( final Element p : params ) {
                 props.setProperty( p.getChildText( "name" ), p.getChildText( "value" ) );
             }
 
@@ -274,13 +240,9 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *
      *  @see PageFilter#preTranslate(WikiContext, String)
      */
-    public String doPreTranslateFiltering( WikiContext context, String pageData )
-        throws FilterException
-    {
+    public String doPreTranslateFiltering( final WikiContext context, String pageData ) throws FilterException {
         fireEvent( WikiPageEvent.PRE_TRANSLATE_BEGIN, context );
-
-        for( PageFilter f : m_pageFilters )
-        {
+        for( final PageFilter f : m_pageFilters ) {
             pageData = f.preTranslate( context, pageData );
         }
 
@@ -298,13 +260,9 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *  @return The modified HTML
      *  @see PageFilter#postTranslate(WikiContext, String)
      */
-    public String doPostTranslateFiltering( WikiContext context, String htmlData )
-        throws FilterException
-    {
+    public String doPostTranslateFiltering( final WikiContext context, String htmlData ) throws FilterException {
         fireEvent( WikiPageEvent.POST_TRANSLATE_BEGIN, context );
-
-        for( PageFilter f : m_pageFilters )
-        {
+        for( final PageFilter f : m_pageFilters ) {
             htmlData = f.postTranslate( context, htmlData );
         }
 
@@ -322,13 +280,9 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *  @return The modified WikiMarkup
      *  @see PageFilter#preSave(WikiContext, String)
      */
-    public String doPreSaveFiltering( WikiContext context, String pageData )
-        throws FilterException
-    {
+    public String doPreSaveFiltering( final WikiContext context, String pageData ) throws FilterException {
         fireEvent( WikiPageEvent.PRE_SAVE_BEGIN, context );
-
-        for( PageFilter f : m_pageFilters )
-        {
+        for( final PageFilter f : m_pageFilters ) {
             pageData = f.preSave( context, pageData );
         }
 
@@ -346,13 +300,9 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *
      *  @see PageFilter#postSave(WikiContext, String)
      */
-    public void doPostSaveFiltering( WikiContext context, String pageData )
-        throws FilterException
-    {
+    public void doPostSaveFiltering( final WikiContext context, final String pageData ) throws FilterException {
         fireEvent( WikiPageEvent.POST_SAVE_BEGIN, context );
-
-        for( PageFilter f : m_pageFilters )
-        {
+        for( final PageFilter f : m_pageFilters ) {
             // log.info("POSTSAVE: "+f.toString() );
             f.postSave( context, pageData );
         }
@@ -376,10 +326,8 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      * Notifies PageFilters to clean up their ressources.
      *
      */
-    public void destroy()
-    {
-        for( PageFilter f : m_pageFilters )
-        {
+    public void destroy() {
+        for( final PageFilter f : m_pageFilters ) {
             f.destroy( m_engine );
         }
     }
@@ -387,19 +335,15 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
     // events processing .......................................................
 
     /**
-     *  Fires a WikiPageEvent of the provided type and WikiContext.
-     *  Invalid WikiPageEvent types are ignored.
+     *  Fires a WikiPageEvent of the provided type and WikiContext. Invalid WikiPageEvent types are ignored.
      *
      * @see org.apache.wiki.event.WikiPageEvent
      * @param type      the WikiPageEvent type to be fired.
      * @param context   the WikiContext of the event.
      */
-    public void fireEvent( int type, WikiContext context )
-    {
-        if ( WikiEventManager.isListening(this) && WikiPageEvent.isValidType(type) )
-        {
-            WikiEventManager.fireEvent(this,
-                    new WikiPageEvent(m_engine,type,context.getPage().getName()) );
+    public void fireEvent( final int type, final WikiContext context ) {
+        if( WikiEventManager.isListening(this ) && WikiPageEvent.isValidType( type ) )  {
+            WikiEventManager.fireEvent(this, new WikiPageEvent( m_engine, type, context.getPage().getName() ) );
         }
     }
 
@@ -411,35 +355,33 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
         return modules( m_filterClassMap.values().iterator() );
     }
 
-
     /**
      *  {@inheritDoc}
      */
     @Override
-    public PageFilterInfo getModuleInfo(String moduleName) {
+    public PageFilterInfo getModuleInfo( final String moduleName ) {
         return m_filterClassMap.get(moduleName);
     }
 
     private void registerFilters() {
         log.info( "Registering filters" );
-        List< Element > filters = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/filter" );
+        final List< Element > filters = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/filter" );
 
         //
         // Register all filters which have created a resource containing its properties.
         //
         // Get all resources of all plugins.
         //
-        for( Iterator< Element > i = filters.iterator(); i.hasNext(); ) {
-            Element pluginEl = i.next();
-            String className = pluginEl.getAttributeValue( "class" );
-            PageFilterInfo filterInfo = PageFilterInfo.newInstance( className, pluginEl );
+        for( final Element pluginEl : filters ) {
+            final String className = pluginEl.getAttributeValue( "class" );
+            final PageFilterInfo filterInfo = PageFilterInfo.newInstance( className, pluginEl );
             if( filterInfo != null ) {
                 registerFilter( filterInfo );
             }
         }
     }
 
-    private void registerFilter(PageFilterInfo pluginInfo) {
+    private void registerFilter( final PageFilterInfo pluginInfo ) {
         m_filterClassMap.put( pluginInfo.getName(), pluginInfo );
     }
 
@@ -448,17 +390,17 @@ public class DefaultFilterManager extends ModuleManager implements FilterManager
      *
      *  @since 2.6.1
      */
-    private static final class PageFilterInfo extends WikiModuleInfo
-    {
-        private PageFilterInfo( String name )
+    private static final class PageFilterInfo extends WikiModuleInfo {
+        private PageFilterInfo( final String name )
         {
             super(name);
         }
 
-        protected static PageFilterInfo newInstance(String className, Element pluginEl)
-        {
-            if( className == null || className.length() == 0 ) return null;
-            PageFilterInfo info = new PageFilterInfo( className );
+        protected static PageFilterInfo newInstance( final String className, final Element pluginEl ) {
+            if( className == null || className.length() == 0 ) {
+                return null;
+            }
+            final PageFilterInfo info = new PageFilterInfo( className );
 
             info.initializeFromXML( pluginEl );
             return info;
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/modules/WikiModuleInfo.java b/jspwiki-main/src/main/java/org/apache/wiki/modules/WikiModuleInfo.java
index 86ab58a..e9cc051 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/modules/WikiModuleInfo.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/modules/WikiModuleInfo.java
@@ -18,24 +18,20 @@
  */
 package org.apache.wiki.modules;
 
+import org.apache.wiki.util.FileUtil;
+import org.jdom2.Element;
+
 import java.io.BufferedInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.net.URL;
 
-import org.jdom2.Element;
-
-import org.apache.wiki.util.FileUtil;
-
 /**
- *  A WikiModule describes whatever JSPWiki plugin there is: it can be a plugin,
- *  an editor, a filter, etc.
+ *  A WikiModule describes whatever JSPWiki plugin there is: it can be a plugin, an editor, a filter, etc.
  *
  *  @since 2.4
  */
-public class WikiModuleInfo
-    implements Comparable<WikiModuleInfo>
-{
+public class WikiModuleInfo implements Comparable< WikiModuleInfo > {
     protected String m_name;
     protected String m_description;
     protected String m_moduleUrl;
@@ -57,22 +53,20 @@ public class WikiModuleInfo
      *  
      *  @param name The name of the module.
      */
-    public WikiModuleInfo( String name ) {
+    public WikiModuleInfo( final String name ) {
         m_name = name;
     }
     
     /**
-     *  The WikiModuleInfo is equal to another WikiModuleInfo, if the name is equal.  All
-     *  objects are unique across JSPWiki.
+     *  The WikiModuleInfo is equal to another WikiModuleInfo, if the name is equal.  All objects are unique across JSPWiki.
      *  
      *  @param obj {@inheritDoc}
      *  @return {@inheritDoc}
      */
     @Override
-    public boolean equals(Object obj) {
-        if( obj instanceof WikiModuleInfo )
-        {
-            return ((WikiModuleInfo)obj).m_name.equals( m_name );
+    public boolean equals( final Object obj) {
+        if( obj instanceof WikiModuleInfo ) {
+            return ( ( WikiModuleInfo )obj ).m_name.equals( m_name );
         }
         
         return false;
@@ -87,12 +81,11 @@ public class WikiModuleInfo
     }
 
     /**
-     *  Initializes the ModuleInfo from some standard XML elements
-     *  which are under the given element.
+     *  Initializes the ModuleInfo from some standard XML elements which are under the given element.
      *  
      *  @param el The element to parse.
      */
-    protected void initializeFromXML( Element el ) {
+    protected void initializeFromXML( final Element el ) {
     	m_description        = el.getChildText("description");
     	m_moduleUrl          = el.getChildText("url");
     	m_moduleVersion      = el.getChildText("version");
@@ -116,9 +109,8 @@ public class WikiModuleInfo
     }
     
     /**
-     *  Returns the common name for this particular module.  Note that
-     *  this is not the class name, nor is it an alias.  For different modules
-     *  the name may have different meanings.
+     *  Returns the common name for this particular module.  Note that this is not the class name, nor is it an alias.
+     *  For different modules the name may have different meanings.
      *  <p>
      *  Every module defines a name, so this method should never return null.
      *  
@@ -223,11 +215,8 @@ public class WikiModuleInfo
      *  
      *  @throws IOException if the JAR file or the resource cannot be read
      */
-    protected String getTextResource(String resourceLocation) 
-        throws IOException
-    {
-        if(m_resource == null)
-        {
+    protected String getTextResource( final String resourceLocation ) throws IOException {
+        if( m_resource == null ) {
             return "";
         }
     
@@ -236,34 +225,27 @@ public class WikiModuleInfo
         //   could have the same name of the resourceLocation!
         //   (2 plugins could have their stylesheet-files in 'ini/jspwiki.css')
     
-        // So try to construct a resource that loads this resource from the
-        //   same jar-file.
+        // So try to construct a resource that loads this resource from the same jar-file.
         String spec = m_resource.toString();
     
-        // Replace the 'PLUGIN_RESOURCE_LOCATION' with the requested
-        //   resourceLocation.
-        int length = ModuleManager.PLUGIN_RESOURCE_LOCATION.length();
-        spec = spec.substring(0, spec.length() - length) + resourceLocation;
-    
-        URL url = new URL(spec);
-        BufferedInputStream   in  = new BufferedInputStream(url.openStream());
-        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
-        
-        FileUtil.copyContents( in, out );
+        // Replace the 'PLUGIN_RESOURCE_LOCATION' with the requested resourceLocation.
+        final int length = ModuleManager.PLUGIN_RESOURCE_LOCATION.length();
+        spec = spec.substring( 0, spec.length() - length ) + resourceLocation;
     
-        in.close();
-        String text = out.toString();
-        out.close();
-        
-        return text;
+        final URL url = new URL( spec );
+        try( final BufferedInputStream in = new BufferedInputStream( url.openStream() );
+             final ByteArrayOutputStream out = new ByteArrayOutputStream(1024) ) {
+            FileUtil.copyContents( in, out );
+            return out.toString();
+        }
     }
 
     /**
      *  {@inheritDoc}
      */
-    public int compareTo(WikiModuleInfo arg0)
+    public int compareTo( final WikiModuleInfo mod )
     {
-        return m_name.compareTo( arg0.getName() );
+        return m_name.compareTo( mod.getName() );
     }
 
 }


[jspwiki] 20/26: use new VariableManager#VAR_RUNFILTERS instead of old WikiEngine#PROP_RUNFILTERS on jsps

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit e85155ee9d79b175edd93ac40c6840111f1c14ea
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 00:05:42 2020 +0100

    use new VariableManager#VAR_RUNFILTERS instead of old WikiEngine#PROP_RUNFILTERS on jsps
---
 .../src/main/webapp/templates/210/editors/CKeditor.jsp        | 10 +++++-----
 jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp     |  9 +++++----
 jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp | 11 +++++------
 .../src/main/webapp/templates/default/editors/CKeditor.jsp    | 11 +++++------
 .../src/main/webapp/templates/default/editors/TinyMCE.jsp     | 11 +++++------
 .../src/main/webapp/templates/default/editors/wysiwyg.jsp     | 11 +++++------
 6 files changed, 30 insertions(+), 33 deletions(-)

diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
index d7ab340..08c287e 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
@@ -19,17 +19,17 @@
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.text.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
-
 <%@ page import="org.apache.wiki.util.TextUtil" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.text.*" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 <fmt:setLocale value="${prefs.Language}" />
@@ -51,7 +51,7 @@
     */
 
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -110,7 +110,7 @@
    // after the XHTML for CKeditor has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
 
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*not used
diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
index 470d060..4db5005 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
@@ -20,15 +20,16 @@
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.text.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
 <%@ page import="org.apache.wiki.util.TextUtil" %>
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.text.*" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 <fmt:setLocale value="${prefs.Language}" />
@@ -39,7 +40,7 @@
 <%  WikiContext context = WikiContext.findContext( pageContext );
     WikiEngine engine = context.getEngine();
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -86,7 +87,7 @@
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for FCK has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    String templateDir = (String)engine.getWikiProperties().get( WikiEngine.PROP_TEMPLATEDIR );
diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
index 45c4335..0372792 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
@@ -19,17 +19,16 @@
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.text.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
-
 <%@ page import="org.apache.wiki.util.TextUtil" %>
-
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.text.*" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 <fmt:setLocale value="${prefs.Language}" />
@@ -51,7 +50,7 @@
     */
 
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -106,7 +105,7 @@
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for TinyMCE has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*not used
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
index 9fa10da..c292043 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
@@ -18,17 +18,16 @@
 --%>
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.lang3.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
-
 <%@ page import="org.apache.wiki.util.TextUtil" %>
-
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.lang3.*" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
@@ -52,7 +51,7 @@
     */
 
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -115,7 +114,7 @@
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for CKeditor has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*FFS not used
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
index 5e46921..106f3d9 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
@@ -19,17 +19,16 @@
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.lang3.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
-
 <%@ page import="org.apache.wiki.util.TextUtil" %>
-
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.lang3.*" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
@@ -49,7 +48,7 @@
     WikiEngine engine = context.getEngine();
 
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -116,7 +115,7 @@
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for TinyMCE has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*FSS not used
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
index 7c2db80..2849bf3 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
@@ -19,17 +19,16 @@
 <%@ page language="java" pageEncoding="UTF-8"%>
 <%@ taglib uri="http://jspwiki.apache.org/tags" prefix="wiki" %>
 <%@ page import="java.util.Properties"%>
+<%@ page import="org.apache.commons.lang3.*" %>
 <%@ page import="org.apache.wiki.*" %>
 <%@ page import="org.apache.wiki.auth.*" %>
 <%@ page import="org.apache.wiki.auth.permissions.*" %>
+<%@ page import="org.apache.wiki.filters.*" %>
 <%@ page import="org.apache.wiki.render.*" %>
 <%@ page import="org.apache.wiki.parser.JSPWikiMarkupParser" %>
 <%@ page import="org.apache.wiki.ui.*" %>
-
 <%@ page import="org.apache.wiki.util.TextUtil" %>
-
-<%@ page import="org.apache.wiki.filters.*" %>
-<%@ page import="org.apache.commons.lang3.*" %>
+<%@ page import="org.apache.wiki.variables.VariableManager" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
@@ -45,7 +44,7 @@
     WikiEngine engine = context.getEngine();
 
     context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
-    context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
+    context.setVariable( VariableManager.VAR_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
     String originalCCLOption = (String)wikiPage.getAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS );
@@ -107,7 +106,7 @@
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for wysiwyg editor has been rendered.
    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-   context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
+   context.setVariable( VariableManager.VAR_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*not used


[jspwiki] 15/26: apply suggested intellij format

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit a08cf8ab37a26feff02f8247b97a25a4adcc1144
Author: juanpablo <ju...@apache.org>
AuthorDate: Tue Jan 14 00:44:54 2020 +0100

    apply suggested intellij format
---
 .../org/apache/wiki/event/PageEventFilter.java     | 96 ++++++++--------------
 .../java/org/apache/wiki/event/WikiEventUtils.java |  4 +-
 .../java/org/apache/wiki/event/WikiPageEvent.java  | 18 ++--
 .../main/java/org/apache/wiki/rss/AtomFeed.java    | 46 ++++-------
 4 files changed, 61 insertions(+), 103 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/event/PageEventFilter.java b/jspwiki-main/src/main/java/org/apache/wiki/event/PageEventFilter.java
index ff26c5a..d957466 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/event/PageEventFilter.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/event/PageEventFilter.java
@@ -28,10 +28,8 @@ import java.util.Properties;
 /**
   * Fires WikiPageEvents for page events.
   * <p>
-  * Adding a PageEventFilter to the FilterManager will automatically
-  * attach an event delegate with the WikiEventManager to provide for
-  * firing and listener management. All that remains is then adding
-  * the listener to the filter via the WikiEventManager. This is quite
+  * Adding a PageEventFilter to the FilterManager will automatically attach an event delegate with the WikiEventManager to provide for
+  * firing and listener management. All that remains is then adding the listener to the filter via the WikiEventManager. This is quite
   * simple:
   * </p>
   * <pre>
@@ -41,48 +39,38 @@ import java.util.Properties;
   *    WikiEventManager.addWikiEventListener(filter,listener);
   * </pre>
   * <p>
-  * This class provides convenience methods for adding and removing
-  * WikiEventListeners.
+  * This class provides convenience methods for adding and removing WikiEventListeners.
   * </p>
   *
   * @see org.apache.wiki.event.WikiEventManager
   */
-public class PageEventFilter extends BasicPageFilter
-{
+public class PageEventFilter extends BasicPageFilter {
 
     /**
-      * Called whenever a new PageFilter is instantiated and reset.
-      */
-    public void initialize( Properties properties )
-            throws FilterException
-    {
+     * Called whenever a new PageFilter is instantiated and reset.
+     */
+    public void initialize( final Properties properties ) throws FilterException {
         //
     }
 
     /**
-      * This method is called whenever a page has been loaded from the provider,
-      * but not yet been sent through the TranslatorReader.  Note that you cannot
-      * do HTML translation here, because TranslatorReader is likely to escape it.
-      *
-      * @param wikiContext The current wikicontext.
-      * @param content     WikiMarkup.
-      */
-    public String preTranslate( WikiContext wikiContext, String content )
-            throws FilterException
-    {
+     * This method is called whenever a page has been loaded from the provider, but not yet been sent through the TranslatorReader.
+     * Note that you cannot do HTML translation here, because TranslatorReader is likely to escape it.
+     *
+     * @param wikiContext The current wikicontext.
+     * @param content WikiMarkup.
+     */
+    public String preTranslate( final WikiContext wikiContext, final String content ) {
         fireEvent( WikiPageEvent.PRE_TRANSLATE, wikiContext );
         return content;
     }
 
 
     /**
-      * This method is called after a page has been fed through the TranslatorReader,
-      * so anything you are seeing here is translated content.  If you want to
-      * do any of your own WikiMarkup2HTML translation, do it here.
-      */
-    public String postTranslate( WikiContext wikiContext, String htmlContent )
-            throws FilterException
-    {
+     * This method is called after a page has been fed through the TranslatorReader, so anything you are seeing here is translated content.
+     * If you want to do any of your own WikiMarkup2HTML translation, do it here.
+     */
+    public String postTranslate( final WikiContext wikiContext, final String htmlContent ) {
         fireEvent( WikiPageEvent.POST_TRANSLATE, wikiContext );
         return htmlContent;
     }
@@ -91,74 +79,56 @@ public class PageEventFilter extends BasicPageFilter
     /**
       * This method is called before the page has been saved to the PageProvider.
       */
-    public String preSave( WikiContext wikiContext, String content )
-            throws FilterException
-    {
+    public String preSave( final WikiContext wikiContext, final String content ) {
         fireEvent( WikiPageEvent.PRE_SAVE, wikiContext );
         return content;
     }
 
 
     /**
-      * This method is called after the page has been successfully saved.
-      * If the saving fails for any reason, then this method will not
+      * This method is called after the page has been successfully saved. If the saving fails for any reason, then this method will not
       * be called.
       * <p>
-      * Since the result is discarded from this method, this is only useful
-      * for things like counters, etc.
+      * Since the result is discarded from this method, this is only useful for things like counters, etc.
       */
-    public void postSave( WikiContext wikiContext, String content )
-            throws FilterException
-    {
+    public void postSave( final WikiContext wikiContext, final String content ) {
         fireEvent( WikiPageEvent.POST_SAVE, wikiContext );
     }
 
 
     // events processing .......................................................
 
-
     /**
-     *  Registers a WikiEventListener with this instance.
-     *  This is a convenience method.
+     *  Registers a WikiEventListener with this instance. This is a convenience method.
      *
      * @param listener the event listener
      */
-    public final synchronized void addWikiEventListener( WikiEventListener listener )
-    {
+    public final synchronized void addWikiEventListener( final WikiEventListener listener ) {
         WikiEventManager.addWikiEventListener( this, listener );
     }
 
     /**
-     *  Un-registers a WikiEventListener with this instance.
-     *  This is a convenience method.
+     *  Un-registers a WikiEventListener with this instance. This is a convenience method.
      *
      * @param listener the event listener
      */
-    public final synchronized void removeWikiEventListener( WikiEventListener listener )
-    {
+    public final synchronized void removeWikiEventListener( final WikiEventListener listener ) {
         WikiEventManager.removeWikiEventListener( this, listener );
     }
 
     /**
-     *  Fires a WikiPageEvent of the provided type and page name
-     *  to all registered listeners. Only <tt>PAGE_LOCK</tt> and
-     *  <tt>PAGE_UNLOCK</tt> event types will fire an event; other
-     *  event types are ignored.
+     *  Fires a WikiPageEvent of the provided type and page name to all registered listeners. Only <tt>PAGE_LOCK</tt> and
+     *  <tt>PAGE_UNLOCK</tt> event types will fire an event; other event types are ignored.
      *
      * @see org.apache.wiki.event.WikiPageEvent
      * @param type      the WikiPageEvent type to be fired.
      * @param context   the WikiContext of the event.
      */
-    protected final void fireEvent( int type, WikiContext context )
-    {
-        if ( WikiEventManager.isListening(this) && WikiPageEvent.isValidType(type) )
-        {
-            WikiPageEvent event = new WikiPageEvent(
-                    context.getEngine(),
-                    type,
-                    context.getPage().getName());
-            WikiEventManager.fireEvent(this,event);
+    protected final void fireEvent( final int type, final WikiContext context ) {
+        if( WikiEventManager.isListening(this ) && WikiPageEvent.isValidType( type ) ) {
+            final WikiPageEvent event = new WikiPageEvent( context.getEngine(), type, context.getPage().getName() );
+            WikiEventManager.fireEvent(this, event );
         }
     }
 
-} // end org.apache.wiki.event.PageEventFilter
+}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/event/WikiEventUtils.java b/jspwiki-main/src/main/java/org/apache/wiki/event/WikiEventUtils.java
index bec5569..31cfd6b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/event/WikiEventUtils.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/event/WikiEventUtils.java
@@ -20,7 +20,6 @@
 package org.apache.wiki.event;
 
 import org.apache.wiki.WikiEngine;
-import org.apache.wiki.api.engine.FilterManager;
 
 /**
  *  A utility class that adds some JSPWiki-specific functionality to the
@@ -138,8 +137,7 @@ public class WikiEventUtils
                    || type == WikiPageEvent.POST_SAVE_END )
             {
                 // attach to FilterManager
-                FilterManager fm = ((WikiEngine)client).getFilterManager();
-                WikiEventManager.addWikiEventListener( fm, listener );
+                WikiEventManager.addWikiEventListener( ((WikiEngine)client).getFilterManager(), listener );
             }
             else //if (  type == WikiPageEvent.PRE_TRANSLATE
                  // || type == WikiPageEvent.POST_TRANSLATE
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/event/WikiPageEvent.java b/jspwiki-main/src/main/java/org/apache/wiki/event/WikiPageEvent.java
index 034a1ad..07825de 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/event/WikiPageEvent.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/event/WikiPageEvent.java
@@ -68,7 +68,7 @@ package org.apache.wiki.event;
   * Other WikiPageEvents include both <i>phase boundary</i> and <i>in-phase</i>
   * events for saving, pre- and post-translating content. These are very noisy 
   * event types, but are not fired unless a listener is available. They are
-  * generated by the {@link org.apache.wiki.filters.FilterManager}, 
+  * generated by the {@link org.apache.wiki.api.engine.FilterManager},
   * {@link org.apache.wiki.event.PageEventFilter}, and potentially other 
   * implementing classes.
   * </p>
@@ -104,7 +104,7 @@ public class WikiPageEvent extends WikiEvent
     // PRE_TRANSLATE .........
 
     /** Indicates the beginning of all wiki pre-translate page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int PRE_TRANSLATE_BEGIN  = 12;
 
     /** Indicates a wiki pre-translate page event. This is based on events
@@ -112,13 +112,13 @@ public class WikiPageEvent extends WikiEvent
     public static final int PRE_TRANSLATE        = 13;
 
     /** Indicates the end of all wiki pre-translate page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int PRE_TRANSLATE_END    = 14;
 
     // POST_TRANSLATE ........
 
     /** Indicates the beginning of all wiki post-translate page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int POST_TRANSLATE_BEGIN = 15;
 
     /** Indicates a wiki post-translate page event. This is based on events
@@ -126,13 +126,13 @@ public class WikiPageEvent extends WikiEvent
     public static final int POST_TRANSLATE       = 16;
 
     /** Indicates the end of all wiki post-translate page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int POST_TRANSLATE_END   = 17;
 
     // PRE_SAVE ..............
 
     /** Indicates the beginning of all wiki pre-save page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int PRE_SAVE_BEGIN       = 18;
 
     /** Indicates a wiki pre-save page event. This is based on events
@@ -140,13 +140,13 @@ public class WikiPageEvent extends WikiEvent
     public static final int PRE_SAVE             = 19;
 
     /** Indicates the end of all wiki pre-save page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int PRE_SAVE_END         = 20;
 
     // POST_SAVE .............
 
     /** Indicates the beginning of all wiki post-save page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int POST_SAVE_BEGIN      = 21;
 
     /** Indicates a wiki post-save page event. This is based on events
@@ -154,7 +154,7 @@ public class WikiPageEvent extends WikiEvent
     public static final int POST_SAVE            = 22;
 
     /** Indicates the end of all wiki post-save page events. This is based
-      * on events generated by {@link org.apache.wiki.filters.FilterManager}. */
+      * on events generated by {@link org.apache.wiki.api.engine.FilterManager}. */
     public static final int POST_SAVE_END        = 23;
 
     // PAGE REQUESTS .........
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/rss/AtomFeed.java b/jspwiki-main/src/main/java/org/apache/wiki/rss/AtomFeed.java
index cd0f213..3548c21 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/rss/AtomFeed.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/rss/AtomFeed.java
@@ -80,7 +80,7 @@ public class AtomFeed extends Feed
 
     private Collection<Element> getItems()
     {
-        ArrayList<Element> list = new ArrayList<Element>();
+        ArrayList<Element> list = new ArrayList<>();
 
         WikiEngine engine = m_wikiContext.getEngine();
         ServletContext servletContext = null;
@@ -88,60 +88,50 @@ public class AtomFeed extends Feed
         if( m_wikiContext.getHttpRequest() != null )
             servletContext = m_wikiContext.getHttpRequest().getSession().getServletContext();
 
-        for( Iterator< Entry > i = m_entries.iterator(); i.hasNext(); )
-        {
-            Entry e = i.next();
-
+        for( Entry e : m_entries ) {
             WikiPage p = e.getPage();
 
-            Element entryEl = getElement("entry");
+            Element entryEl = getElement( "entry" );
 
             //
             //  Mandatory elements
             //
 
-            entryEl.addContent( getElement("id").setText( getEntryID(e)) );
-            entryEl.addContent( getElement("title").setAttribute("type","html").setText( e.getTitle() ));
-            entryEl.addContent( getElement("updated").setText( DateFormatUtils.formatUTC(p.getLastModified(),
-                                                                                         RFC3339FORMAT )));
+            entryEl.addContent( getElement( "id" ).setText( getEntryID( e ) ) );
+            entryEl.addContent( getElement( "title" ).setAttribute( "type", "html" ).setText( e.getTitle() ) );
+            entryEl.addContent( getElement( "updated" ).setText( DateFormatUtils.formatUTC( p.getLastModified(), RFC3339FORMAT ) ) );
             //
             //  Optional elements
             //
 
-            entryEl.addContent( getElement("author").addContent( getElement("name").setText( e.getAuthor() )));
-            entryEl.addContent( getElement("link").setAttribute("rel","alternate").setAttribute("href",e.getURL()));
-            entryEl.addContent( getElement("content").setAttribute("type","html").setText( e.getContent() ));
+            entryEl.addContent( getElement( "author" ).addContent( getElement( "name" ).setText( e.getAuthor() ) ) );
+            entryEl.addContent( getElement( "link" ).setAttribute( "rel", "alternate" ).setAttribute( "href", e.getURL() ) );
+            entryEl.addContent( getElement( "content" ).setAttribute( "type", "html" ).setText( e.getContent() ) );
 
             //
             //  Check for enclosures
             //
 
-            if( engine.getAttachmentManager().hasAttachments(p) && servletContext != null )
-            {
-                try
-                {
-                    List< Attachment > c = engine.getAttachmentManager().listAttachments(p);
+            if( engine.getAttachmentManager().hasAttachments( p ) && servletContext != null ) {
+                try {
+                    List<Attachment> c = engine.getAttachmentManager().listAttachments( p );
 
-                    for( Iterator< Attachment > a = c.iterator(); a.hasNext(); )
-                    {
+                    for( Iterator<Attachment> a = c.iterator(); a.hasNext(); ) {
                         Attachment att = a.next();
 
-                        Element attEl = getElement("link");
-                        attEl.setAttribute( "rel","enclosure" );
-                        attEl.setAttribute( "href", engine.getURL(WikiContext.ATTACH, att.getName(), null, true ) );
-                        attEl.setAttribute( "length", Long.toString(att.getSize()) );
+                        Element attEl = getElement( "link" );
+                        attEl.setAttribute( "rel", "enclosure" );
+                        attEl.setAttribute( "href", engine.getURL( WikiContext.ATTACH, att.getName(), null, true ) );
+                        attEl.setAttribute( "length", Long.toString( att.getSize() ) );
                         attEl.setAttribute( "type", getMimeType( servletContext, att.getFileName() ) );
 
                         entryEl.addContent( attEl );
                     }
-                }
-                catch( ProviderException ex )
-                {
+                } catch( ProviderException ex ) {
                     // FIXME: log.info("Can't get attachment data",ex);
                 }
             }
 
-
             list.add( entryEl );
         }
 


[jspwiki] 14/26: apply suggested intellij format

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 93882715e6f8c1ea95009ecfef345f1fdfe161ab
Author: juanpablo <ju...@apache.org>
AuthorDate: Tue Jan 14 00:28:21 2020 +0100

    apply suggested intellij format
---
 .../wiki/ajax/WikiAjaxDispatcherServlet.java       |   2 +-
 .../java/org/apache/wiki/auth/acl/AclImpl.java     | 120 +++++++++------------
 .../apache/wiki/parser/LinkParsingOperations.java  |  36 +++----
 .../org/apache/wiki/parser/ParseException.java     |  12 +--
 .../wiki/render/DefaultRenderingManager.java       |  19 ++--
 .../org/apache/wiki/render/RenderingManager.java   |   4 +-
 6 files changed, 82 insertions(+), 111 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ajax/WikiAjaxDispatcherServlet.java b/jspwiki-main/src/main/java/org/apache/wiki/ajax/WikiAjaxDispatcherServlet.java
index 5c06d50..88bcbf1 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ajax/WikiAjaxDispatcherServlet.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ajax/WikiAjaxDispatcherServlet.java
@@ -135,7 +135,7 @@ public class WikiAjaxDispatcherServlet extends HttpServlet {
                     log.debug("actionName="+actionName);
                     final Object params = req.getParameter("params");
                     log.debug("params="+params);
-                    List<String> paramValues = new ArrayList<String>();
+                    List<String> paramValues = new ArrayList<>();
                     if (params instanceof String) {
                         final String paramString = (String)params;
                         if (StringUtils.isNotBlank(paramString)) {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java
index fb63e93..0a5d0ab 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java
@@ -32,7 +32,7 @@ import java.util.Vector;
 public class AclImpl implements Acl, Serializable
 {
     private static final long serialVersionUID = 1L;
-    private final Vector<AclEntry> m_entries = new Vector<AclEntry>();
+    private final Vector<AclEntry> m_entries = new Vector<>();
 
     /**
      * Constructs a new AclImpl instance.
@@ -42,53 +42,44 @@ public class AclImpl implements Acl, Serializable
     }
     
     /**
-     * Returns all Principal objects assigned a given Permission in the access
-     * control list. The Principals returned are those that have been granted
-     * either the supplied permission, or a permission implied by the supplied
-     * permission. Principals are not "expanded" if they are a role or group.
+     * Returns all Principal objects assigned a given Permission in the access control list. The Principals returned are those that have
+     * been granted either the supplied permission, or a permission implied by the supplied permission. Principals are not "expanded" if
+     * they are a role or group.
+     *
      * @param permission the permission to search for
      * @return an array of Principals possessing the permission
      */
-    public Principal[] findPrincipals( Permission permission )
-    {
-        Vector<Principal> principals = new Vector<Principal>();
-        Enumeration<AclEntry> entries = entries();
+    public Principal[] findPrincipals( final Permission permission ) {
+        final Vector< Principal > principals = new Vector<>();
+        final Enumeration< AclEntry > entries = entries();
         
-        while (entries.hasMoreElements()) 
-        {
-            AclEntry entry = entries.nextElement();
-            Enumeration<Permission> permissions = entry.permissions();
-            while ( permissions.hasMoreElements() ) 
-            {
-                Permission perm = permissions.nextElement();
-                if ( perm.implies( permission ) ) 
-                {
+        while( entries.hasMoreElements() ) {
+            final AclEntry entry = entries.nextElement();
+            final Enumeration< Permission > permissions = entry.permissions();
+            while( permissions.hasMoreElements() ) {
+                final Permission perm = permissions.nextElement();
+                if ( perm.implies( permission ) ) {
                     principals.add( entry.getPrincipal() );
                 }
             }
         }
-        return principals.toArray( new Principal[principals.size()] );
+        return principals.toArray( new Principal[ principals.size() ] );
     }
   
-    private boolean hasEntry( AclEntry entry )
-    {
-        if( entry == null )
-        {
+    private boolean hasEntry( final AclEntry entry ) {
+        if( entry == null ) {
             return false;
         }
 
-        for( AclEntry e : m_entries )
-        {
-            Principal ep     = e.getPrincipal();
-            Principal entryp = entry.getPrincipal();
+        for( final AclEntry e : m_entries ) {
+            final Principal ep     = e.getPrincipal();
+            final Principal entryp = entry.getPrincipal();
 
-            if( ep == null || entryp == null )
-            {
+            if( ep == null || entryp == null ) {
                 throw new IllegalArgumentException( "Entry is null; check code, please (entry="+entry+"; e="+e+")" );
             }
             
-            if( ep.getName().equals( entryp.getName() ) )
-            {
+            if( ep.getName().equals( entryp.getName() ) ) {
                 return true;
             }
         }
@@ -97,24 +88,20 @@ public class AclImpl implements Acl, Serializable
     }
 
     /**
-     * Adds an ACL entry to this ACL. An entry associates a principal (e.g., an
-     * individual or a group) with a set of permissions. Each principal can have
-     * at most one positive ACL entry, specifying permissions to be granted to
-     * the principal. If there is already an ACL entry already in the ACL, false
-     * is returned.
+     * Adds an ACL entry to this ACL. An entry associates a principal (e.g., an individual or a group) with a set of permissions. Each
+     * principal can have at most one positive ACL entry, specifying permissions to be granted to the principal. If there is already an
+     * ACL entry already in the ACL, false is returned.
+     *
      * @param entry - the ACL entry to be added to this ACL
-     * @return true on success, false if an entry of the same type (positive or
-     *         negative) for the same principal is already present in this ACL
+     * @return true on success, false if an entry of the same type (positive or negative) for the same principal is already present in
+     * this ACL
      */
-    public synchronized boolean addEntry( AclEntry entry )
-    {
-        if( entry.getPrincipal() == null )
-        {
+    public synchronized boolean addEntry( final AclEntry entry ) {
+        if( entry.getPrincipal() == null ) {
             throw new IllegalArgumentException( "Entry principal cannot be null" );
         }
 
-        if( hasEntry( entry ) )
-        {
+        if( hasEntry( entry ) ) {
             return false;
         }
         
@@ -128,7 +115,7 @@ public class AclImpl implements Acl, Serializable
      * @param entry the ACL entry to be removed from this ACL
      * @return true on success, false if the entry is not part of this ACL
      */
-    public synchronized boolean removeEntry( AclEntry entry )
+    public synchronized boolean removeEntry( final AclEntry entry )
     {
         return m_entries.remove( entry );
     }
@@ -144,17 +131,14 @@ public class AclImpl implements Acl, Serializable
     }
 
     /**
-     * Returns an AclEntry for a supplied Principal, or <code>null</code> if
-     * the Principal does not have a matching AclEntry.
+     * Returns an AclEntry for a supplied Principal, or <code>null</code> if the Principal does not have a matching AclEntry.
+     *
      * @param principal the principal to search for
      * @return the AclEntry associated with the principal, or <code>null</code>
      */
-    public AclEntry getEntry( Principal principal )
-    {
-        for( AclEntry entry : m_entries )
-        {
-            if( entry.getPrincipal().getName().equals( principal.getName() ) )
-            {
+    public AclEntry getEntry( final Principal principal ) {
+        for( final AclEntry entry : m_entries ) {
+            if( entry.getPrincipal().getName().equals( principal.getName() ) ) {
                 return entry;
             }
         }
@@ -164,25 +148,21 @@ public class AclImpl implements Acl, Serializable
 
     /**
      * Returns a string representation of the contents of this Acl.
+     *
      * @return the string representation
      */
-    public String toString()
-    {
-    	StringBuilder sb = new StringBuilder();
-
-        for( AclEntry entry : m_entries )
-        {
-            Principal pal = entry.getPrincipal();
-
-            if( pal != null )
-                sb.append( "  user = "+pal.getName()+": " );
-            else
+    public String toString() {
+    	final StringBuilder sb = new StringBuilder();
+        for( final AclEntry entry : m_entries ) {
+            final Principal pal = entry.getPrincipal();
+            if( pal != null ) {
+                sb.append( "  user = " ).append( pal.getName() ).append( ": " );
+            } else {
                 sb.append( "  user = null: " );
-
+            }
             sb.append( "(" );
-            for( Enumeration<Permission> perms = entry.permissions(); perms.hasMoreElements(); )
-            {
-                Permission perm = perms.nextElement();
+            for( final Enumeration< Permission > perms = entry.permissions(); perms.hasMoreElements(); ) {
+                final Permission perm = perms.nextElement();
                 sb.append( perm.toString() );
             }
             sb.append( ")\n" );
@@ -193,11 +173,11 @@ public class AclImpl implements Acl, Serializable
 
     /**
      * Returns <code>true</code>, if this Acl is empty.
+     *
      * @return the result
      * @since 2.4.68
      */
-    public boolean isEmpty()
-    {
+    public boolean isEmpty() {
         return m_entries.isEmpty();
     }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/LinkParsingOperations.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/LinkParsingOperations.java
index 0e67464..58fd889 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/LinkParsingOperations.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/LinkParsingOperations.java
@@ -18,16 +18,16 @@
  */
 package org.apache.wiki.parser;
 
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-
 import org.apache.log4j.Logger;
 import org.apache.oro.text.regex.Pattern;
 import org.apache.oro.text.regex.Perl5Matcher;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.api.exceptions.ProviderException;
 
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+
 
 /**
  * Link parsing operations.
@@ -111,7 +111,7 @@ public class LinkParsingOperations {
      * @param link The link text
      * @return {@code true}, if this represents a variable link.
      */
-    public boolean isVariableLink( String link ) {
+    public boolean isVariableLink( final String link ) {
         return link.startsWith( "{$" );
     }
 
@@ -141,16 +141,10 @@ public class LinkParsingOperations {
      * @return true, if this is a link outside of this wiki.
      */
     public boolean isExternalLink( final String page ) {
-        int idx = Arrays.binarySearch( EXTERNAL_LINKS, page, new StartingComparator() );
+        final int idx = Arrays.binarySearch( EXTERNAL_LINKS, page, new StartingComparator() );
 
-        //
         // We need to check here once again; otherwise we might get a match for something like "h".
-        //
-        if( idx >= 0 && page.startsWith( EXTERNAL_LINKS[ idx ] ) ) {
-            return true;
-        }
-
-        return false;
+        return idx >= 0 && page.startsWith( EXTERNAL_LINKS[ idx ] );
     }
 
     /**
@@ -160,10 +154,10 @@ public class LinkParsingOperations {
     public boolean isImageLink( String link ) {
         if( wikiContext.getEngine().getRenderingManager().getParser( wikiContext, link ).isImageInlining() ) {
             link = link.toLowerCase();
-            List< Pattern > inlineImagePatterns = wikiContext.getEngine().getRenderingManager()
-            		                                         .getParser( wikiContext, link ).getInlineImagePatterns();
+            final List< Pattern > inlineImagePatterns = wikiContext.getEngine().getRenderingManager()
+            	                                                   .getParser( wikiContext, link ).getInlineImagePatterns();
 
-            for( Pattern p : inlineImagePatterns ) {
+            for( final Pattern p : inlineImagePatterns ) {
                 if( new Perl5Matcher().matches( link, p ) ) {
                     return true;
                 }
@@ -185,7 +179,7 @@ public class LinkParsingOperations {
         }
         try {
             return wikiContext.getEngine().getFinalPageName( page ) != null;
-        } catch( ProviderException e ) {
+        } catch( final ProviderException e ) {
             log.warn( "TranslatorReader got a faulty page name [" + page + "]!", e );
             return false;
         }
@@ -203,23 +197,21 @@ public class LinkParsingOperations {
         }
         try {
             return wikiContext.getEngine().getFinalPageName( page );
-        } catch( ProviderException e ) {
+        } catch( final ProviderException e ) {
             log.warn( "TranslatorReader got a faulty page name [" + page + "]!", e );
             return null;
         }
     }
 
     /**
-     * Compares two Strings, and if one starts with the other, then returns null. Otherwise just like the normal Comparator for strings.
-     *
-     * @since
+     * Compares two Strings, and if one starts with the other, then returns 0. Otherwise just like the normal Comparator for strings.
      */
     private static class StartingComparator implements Comparator< String > {
 
         /**
          * {@inheritDoc}
          *
-         * @see Comparator#compare(String, String)
+         * @see Comparator#compare(Object, Object)
          */
         @Override
         public int compare( final String s1, final String s2 ) {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/ParseException.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/ParseException.java
index 6c37824..87f2213 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/ParseException.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/ParseException.java
@@ -21,12 +21,10 @@ package org.apache.wiki.parser;
 import org.apache.wiki.api.exceptions.WikiException;
 
 /**
- *  This is an exception which gets thrown whenever the parser cannot
- *  parse the parsing things.
- *
+ *  This is an exception which gets thrown whenever the parser cannot parse the parsing things.
  */
-public class ParseException extends WikiException
-{
+public class ParseException extends WikiException {
+
     private static final long serialVersionUID = 1L;
 
     /**
@@ -34,9 +32,9 @@ public class ParseException extends WikiException
      *
      *  @param msg the message exception.
      */
-    public ParseException(String msg)
+    public ParseException( final String msg )
     {
-        super(msg);
+        super( msg );
     }
 
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index d34405a..4aa40dc 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -60,14 +60,6 @@ public class DefaultRenderingManager implements RenderingManager {
 
     private static final Logger log = Logger.getLogger( DefaultRenderingManager.class );
 
-    private final int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
-    private final CacheManager m_cacheManager = CacheManager.getInstance();
-
-    private WikiEngine m_engine;
-    private boolean m_useCache = true;
-    /** If true, all titles will be cleaned. */
-    private boolean m_beautifyTitle = false;
-
     /** The capacity of the caches, if you want something else, tweak ehcache.xml. */
     private static final int    DEFAULT_CACHESIZE     = 1_000;
     private static final String VERSION_DELIMITER     = "::";
@@ -79,6 +71,15 @@ public class DefaultRenderingManager implements RenderingManager {
     /** The name of the default WYSIWYG renderer. */
     private static final String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
 
+    private WikiEngine m_engine;
+
+    private boolean m_useCache = true;
+    private final CacheManager m_cacheManager = CacheManager.getInstance();
+    private final int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
+
+    /** If true, all titles will be cleaned. */
+    private boolean m_beautifyTitle = false;
+
     /** Stores the WikiDocuments that have been cached. */
     private Cache m_documentCache;
 
@@ -99,8 +100,8 @@ public class DefaultRenderingManager implements RenderingManager {
         }
         log.info( "Using " + m_markupParserClass + " as markup parser." );
 
-        m_useCache = "true".equals( properties.getProperty( PageManager.PROP_USECACHE ) );
         m_beautifyTitle  = TextUtil.getBooleanProperty( properties, PROP_BEAUTIFYTITLE, m_beautifyTitle );
+        m_useCache = "true".equals( properties.getProperty( PageManager.PROP_USECACHE ) );
 
         if( m_useCache ) {
             final String documentCacheName = engine.getApplicationName() + "." + DOCUMENTCACHE_NAME;
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index 36fef32..b46e628 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -77,7 +77,7 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
      *  @return A beautified title (or, if beautification is off, returns the title without modification)
      *  @since 1.7.11, moved to PageManager on 2.11.0
      */
-    String beautifyTitle( final String title );
+    String beautifyTitle( String title );
 
     /**
      *  Beautifies the title of the page by appending non-breaking spaces in suitable places.  This is really suitable only for HTML output,
@@ -87,7 +87,7 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
      *  @return A beautified title.
      *  @since 2.1.127
      */
-    String beautifyTitleNoBreak( final String title );
+    String beautifyTitleNoBreak( String title );
 
     /**
      *  Returns the wiki Parser


[jspwiki] 25/26: unit test 1.000 ?!

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit f166f1ecaf38a0f671c03ee4dffc20d343b9c2a7
Author: juanpablo <ju...@apache.org>
AuthorDate: Fri Jan 17 00:05:57 2020 +0100

    unit test 1.000 ?!
---
 jspwiki-util/src/test/java/org/apache/wiki/util/TextUtilTest.java | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/jspwiki-util/src/test/java/org/apache/wiki/util/TextUtilTest.java b/jspwiki-util/src/test/java/org/apache/wiki/util/TextUtilTest.java
index f3d6375..3f98af0 100644
--- a/jspwiki-util/src/test/java/org/apache/wiki/util/TextUtilTest.java
+++ b/jspwiki-util/src/test/java/org/apache/wiki/util/TextUtilTest.java
@@ -330,4 +330,11 @@ public class TextUtilTest {
         Assertions.assertThrows( NoSuchElementException.class, () -> TextUtil.getRequiredProperty( props, "ber" ) );
     }
 
+    @Test
+    public void testCleanString() {
+        Assertions.assertNull( TextUtil.cleanString( null, TextUtil.PUNCTUATION_CHARS_ALLOWED ) );
+        Assertions.assertEquals( " This is a link ", TextUtil.cleanString( " [ This is a link ] ", TextUtil.PUNCTUATION_CHARS_ALLOWED ) );
+        Assertions.assertEquals( "ThisIsALink", TextUtil.cleanString( " [ This is a link ] ", TextUtil.LEGACY_CHARS_ALLOWED ) );
+    }
+
 }


[jspwiki] 03/26: move RenderingManager#WYSIWYG_EDITOR_MODE constant to WikiContext#VAR_WYSIWYG_EDITOR_MODE

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 4c5940f9fae59652eb6d30c306bc752fd5df2d11
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Jan 11 21:38:46 2020 +0100

    move RenderingManager#WYSIWYG_EDITOR_MODE constant to WikiContext#VAR_WYSIWYG_EDITOR_MODE
---
 .../src/main/java/org/apache/wiki/WikiContext.java |   3 +
 .../apache/wiki/parser/JSPWikiMarkupParser.java    |  43 +++---
 .../java/org/apache/wiki/parser/PluginContent.java | 151 ++++++++++-----------
 .../org/apache/wiki/parser/VariableContent.java    |  56 +++-----
 .../wiki/render/DefaultRenderingManager.java       |   2 +-
 .../org/apache/wiki/render/RenderingManager.java   |  32 ++---
 .../wiki/variables/DefaultVariableManager.java     |  65 ++-------
 .../org/apache/wiki/variables/VariableManager.java |   7 +-
 .../InterWikiLinkAttributeProviderState.java       |   8 +-
 .../WysiwygEditingAttributeProviderState.java      |   8 +-
 .../AccessRuleLinkNodePostProcessorState.java      |   3 +-
 .../InterWikiLinkNodePostProcessorState.java       |   3 +-
 .../MetadataLinkNodePostProcessorState.java        |   3 +-
 .../NodePostProcessorStateCommonOperations.java    |   3 +-
 .../PluginLinkNodePostProcessorState.java          |   3 +-
 .../VariableLinkNodePostProcessorState.java        |   3 +-
 .../main/webapp/templates/210/editors/CKeditor.jsp |   4 +-
 .../src/main/webapp/templates/210/editors/FCK.jsp  |   4 +-
 .../main/webapp/templates/210/editors/TinyMCE.jsp  |  12 +-
 .../webapp/templates/default/editors/CKeditor.jsp  |   5 +-
 .../webapp/templates/default/editors/TinyMCE.jsp   |   7 +-
 .../webapp/templates/default/editors/wysiwyg.jsp   |   6 +-
 22 files changed, 162 insertions(+), 269 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
index 4f4f42c..ace5764 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
@@ -71,6 +71,9 @@ public class WikiContext implements Cloneable, Command {
 
     public static final String ATTR_CONTEXT = "jspwiki.context";
 
+    /** Name of the variable which is set to Boolean.TRUE or Boolean.FALSE depending on whether WYSIWYG is currently in effect. */
+    public static final String VAR_WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
+
     /** User is administering JSPWiki (Install, SecurityConfig). */
     public static final String INSTALL = WikiCommand.INSTALL.getRequestContext();
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
index 8b2806b..fe14f59 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
@@ -39,7 +39,6 @@ import org.apache.wiki.auth.acl.Acl;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.preferences.Preferences;
 import org.apache.wiki.render.CleanTextRenderer;
-import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.util.TextUtil;
 import org.jdom2.Attribute;
 import org.jdom2.Content;
@@ -173,8 +172,7 @@ public class JSPWikiMarkupParser extends MarkupParser {
     }
 
     // FIXME: parsers should be pooled for better performance.
-    private void initialize()
-    {
+    private void initialize() {
         initInlineImagePatterns();
 
         m_camelCasePattern = m_engine.getAttribute( CAMELCASE_PATTERN );
@@ -187,38 +185,29 @@ public class JSPWikiMarkupParser extends MarkupParser {
             }
             m_engine.setAttribute( CAMELCASE_PATTERN, m_camelCasePattern );
         }
-        //
-        //  Set the properties.
-        //
-        Properties props      = m_engine.getWikiProperties();
 
-        String cclinks = m_context.getPage().getAttribute( PROP_CAMELCASELINKS );
+        //  Set the properties.
+        final Properties props = m_engine.getWikiProperties();
+        final String cclinks = m_context.getPage().getAttribute( PROP_CAMELCASELINKS );
 
-        if( cclinks != null )
-        {
+        if( cclinks != null ) {
             m_camelCaseLinks = TextUtil.isPositive( cclinks );
-        }
-        else
-        {
-            m_camelCaseLinks  = TextUtil.getBooleanProperty( props,
-                                                             PROP_CAMELCASELINKS,
-                                                             m_camelCaseLinks );
+        } else {
+            m_camelCaseLinks  = TextUtil.getBooleanProperty( props, PROP_CAMELCASELINKS, m_camelCaseLinks );
         }
 
-        Boolean wysiwygVariable = (Boolean)m_context.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        if( wysiwygVariable != null )
-        {
-            m_wysiwygEditorMode = wysiwygVariable.booleanValue();
+        final Boolean wysiwygVariable = (Boolean)m_context.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
+        if( wysiwygVariable != null ) {
+            m_wysiwygEditorMode = wysiwygVariable;
         }
 
-        m_plainUris           = m_context.getBooleanWikiProperty( PROP_PLAINURIS, m_plainUris );
-        m_useOutlinkImage     = m_context.getBooleanWikiProperty( PROP_USEOUTLINKIMAGE, m_useOutlinkImage );
-        m_useAttachmentImage  = m_context.getBooleanWikiProperty( PROP_USEATTACHMENTIMAGE, m_useAttachmentImage );
-        m_allowHTML           = m_context.getBooleanWikiProperty( PROP_ALLOWHTML, m_allowHTML );
-        m_useRelNofollow      = m_context.getBooleanWikiProperty( PROP_USERELNOFOLLOW, m_useRelNofollow );
+        m_plainUris          = m_context.getBooleanWikiProperty( PROP_PLAINURIS, m_plainUris );
+        m_useOutlinkImage    = m_context.getBooleanWikiProperty( PROP_USEOUTLINKIMAGE, m_useOutlinkImage );
+        m_useAttachmentImage = m_context.getBooleanWikiProperty( PROP_USEATTACHMENTIMAGE, m_useAttachmentImage );
+        m_allowHTML          = m_context.getBooleanWikiProperty( PROP_ALLOWHTML, m_allowHTML );
+        m_useRelNofollow     = m_context.getBooleanWikiProperty( PROP_USERELNOFOLLOW, m_useRelNofollow );
 
-        if( m_engine.getUserManager().getUserDatabase() == null || m_engine.getAuthorizationManager() == null )
-        {
+        if( m_engine.getUserManager().getUserDatabase() == null || m_engine.getAuthorizationManager() == null ) {
             disableAccessRules();
         }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
index 8ef5c22..56b9c30 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
@@ -18,13 +18,6 @@
 */
 package org.apache.wiki.parser;
 
-import java.io.IOException;
-import java.text.MessageFormat;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.ResourceBundle;
-
 import org.apache.log4j.Logger;
 import org.apache.oro.text.regex.MatchResult;
 import org.apache.oro.text.regex.PatternMatcher;
@@ -40,6 +33,13 @@ import org.apache.wiki.preferences.Preferences;
 import org.apache.wiki.render.RenderingManager;
 import org.jdom2.Text;
 
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.ResourceBundle;
+
 
 /**
  * Stores the contents of a plugin in a WikiDocument DOM tree.
@@ -78,7 +78,7 @@ public class PluginContent extends Text {
      * @param pluginName The FQN of a plugin.
      * @param parameters A Map of parameters.
      */
-    public PluginContent(String pluginName, Map<String, String> parameters) {
+    public PluginContent( final String pluginName, final Map< String, String > parameters) {
         m_pluginName = pluginName;
         m_params = parameters;
     }
@@ -99,7 +99,7 @@ public class PluginContent extends Text {
      * @param name the name of the parameter.
      * @return The value from the map, or null, if no such parameter exists.
      */
-    public String getParameter(String name) {
+    public String getParameter( final String name) {
         return m_params.get(name);
     }
 
@@ -108,7 +108,7 @@ public class PluginContent extends Text {
      *
      * @return The parameter map.
      */
-    public Map<String, String> getParameters() {
+    public Map< String, String > getParameters() {
         return m_params;
     }
 
@@ -129,22 +129,17 @@ public class PluginContent extends Text {
      * @return The plugin rendered according to the options set in the WikiContext.
      */
     public String getText() {
-        WikiDocument doc = ( WikiDocument )getDocument();
-
-        if (doc == null) {
+        final WikiDocument doc = ( WikiDocument )getDocument();
+        if( doc == null ) {
             //
-            // This element has not yet been attached anywhere, so we simply assume there is
-            // no rendering and return the plugin name.  This is required e.g. when the 
-            // paragraphify() checks whether the element is empty or not.  We can't of course
-            // know whether the rendering would result in an empty string or not, but let us
-            // assume it does not.
+            // This element has not yet been attached anywhere, so we simply assume there is no rendering and return the plugin name.
+            // This is required e.g. when the paragraphify() checks whether the element is empty or not.  We can't of course know
+            // whether the rendering would result in an empty string or not, but let us assume it does not.
             //
-
             return getPluginName();
         }
 
-        WikiContext context = doc.getContext();
-        
+        final WikiContext context = doc.getContext();
         if( context == null ) {
             log.info( "WikiContext garbage-collected, cannot proceed" );
             return getPluginName();
@@ -159,12 +154,12 @@ public class PluginContent extends Text {
      * @param context WikiContext in which the plugin is executed. Must NOT be null.
      * @return plugin contents.
      */
-	public String invoke( WikiContext context ) {
+	public String invoke( final WikiContext context ) {
 		String result;
-		Boolean wysiwygVariable = (Boolean) context.getVariable(RenderingManager.WYSIWYG_EDITOR_MODE);
+		final Boolean wysiwygVariable = ( Boolean )context.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         boolean wysiwygEditorMode = false;
-        if (wysiwygVariable != null) {
-            wysiwygEditorMode = wysiwygVariable.booleanValue();
+        if( wysiwygVariable != null ) {
+            wysiwygEditorMode = wysiwygVariable;
         }
 
         try {
@@ -178,36 +173,32 @@ public class PluginContent extends Text {
                 result = PLUGIN_START + m_pluginName + SPACE;
 
                 // convert newlines to <br> in case the plugin has a body.
-                String cmdLine = (m_params.get(CMDLINE)).replaceAll(LINEBREAK, ELEMENT_BR);
-
+                final String cmdLine = m_params.get( CMDLINE ).replaceAll( LINEBREAK, ELEMENT_BR );
                 result = result + cmdLine + PLUGIN_END;
             } else {
-                Boolean b = (Boolean) context.getVariable(RenderingManager.VAR_EXECUTE_PLUGINS);
-                if (b != null && !b.booleanValue()) {
+                final Boolean b = ( Boolean )context.getVariable(RenderingManager.VAR_EXECUTE_PLUGINS );
+                if (b != null && !b ) {
                     return BLANK;
                 }
 
-                WikiEngine engine = context.getEngine();
+                final WikiEngine engine = context.getEngine();
+                final Map< String, String > parsedParams = new HashMap<>();
 
-                Map<String, String> parsedParams = new HashMap<String, String>();
-
-                //
                 //  Parse any variable instances from the string
-                //
-                for (Map.Entry<String, String> e : m_params.entrySet()) {
+                for( final Map.Entry< String, String > e : m_params.entrySet() ) {
                     String val = e.getValue();
-                    val = engine.getVariableManager().expandVariables(context, val);
-                    parsedParams.put(e.getKey(), val);
+                    val = engine.getVariableManager().expandVariables( context, val );
+                    parsedParams.put( e.getKey(), val );
                 }
-                PluginManager pm = engine.getPluginManager();
-                result = pm.execute(context, m_pluginName, parsedParams);
+                final PluginManager pm = engine.getPluginManager();
+                result = pm.execute( context, m_pluginName, parsedParams );
             }
-        } catch (Exception e) {
-            if (wysiwygEditorMode) {
+        } catch( final Exception e ) {
+            if( wysiwygEditorMode ) {
                 result = "";
             } else {
                 // log.info("Failed to execute plugin",e);
-                ResourceBundle rb = Preferences.getBundle(context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
+                final ResourceBundle rb = Preferences.getBundle( context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE );
                 result = MarkupParser.makeError( MessageFormat.format( rb.getString( "plugin.error.insertionfailed" ), 
                 		                                               context.getRealPage().getWiki(), 
                 		                                               context.getRealPage().getName(), 
@@ -215,7 +206,6 @@ public class PluginContent extends Text {
             }
         }
 
-
         return result;
 	}
 
@@ -225,18 +215,18 @@ public class PluginContent extends Text {
      * @param context The WikiContext
      * @throws PluginException If something goes wrong.
      */
-    public void executeParse(WikiContext context) throws PluginException {
-        PluginManager pm = context.getEngine().getPluginManager();
-        if (pm.pluginsEnabled()) {
-            ResourceBundle rb = Preferences.getBundle(context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
-            Map<String, String> params = getParameters();
-            WikiPlugin plugin = pm.newWikiPlugin(getPluginName(), rb);
+    public void executeParse( final WikiContext context ) throws PluginException {
+        final PluginManager pm = context.getEngine().getPluginManager();
+        if( pm.pluginsEnabled() ) {
+            final ResourceBundle rb = Preferences.getBundle(context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
+            final Map< String, String > params = getParameters();
+            final WikiPlugin plugin = pm.newWikiPlugin( getPluginName(), rb );
             try {
-                if (plugin != null && plugin instanceof ParserStagePlugin) {
-                    ((ParserStagePlugin) plugin).executeParser(this, context, params);
+                if( plugin != null && plugin instanceof ParserStagePlugin ) {
+                    ( ( ParserStagePlugin )plugin ).executeParser(this, context, params );
                 }
-            } catch (ClassCastException e) {
-                throw new PluginException(MessageFormat.format(rb.getString("plugin.error.notawikiplugin"), getPluginName()), e);
+            } catch( final ClassCastException e ) {
+                throw new PluginException( MessageFormat.format( rb.getString("plugin.error.notawikiplugin"), getPluginName() ), e );
             }
         }
     }
@@ -251,43 +241,38 @@ public class PluginContent extends Text {
      * @throws PluginException If plugin invocation is faulty
      * @since 2.10.0
      */
-    public static PluginContent parsePluginLine(WikiContext context, String commandline, int pos) throws PluginException {
-        PatternMatcher matcher = new Perl5Matcher();
+    public static PluginContent parsePluginLine( final WikiContext context, final String commandline, final int pos ) throws PluginException {
+        final PatternMatcher matcher = new Perl5Matcher();
 
         try {
-            PluginManager pm = context.getEngine().getPluginManager();
-            if (matcher.contains(commandline, pm.getPluginPattern())) {
-
-                MatchResult res = matcher.getMatch();
-
-                String plugin = res.group(2);
-                String args = commandline.substring(res.endOffset(0),
-                        commandline.length() -
-                                (commandline.charAt(commandline.length() - 1) == '}' ? 1 : 0));
-                Map<String, String> arglist = pm.parseArgs(args);
+            final PluginManager pm = context.getEngine().getPluginManager();
+            if( matcher.contains( commandline, pm.getPluginPattern() ) ) {
+                final MatchResult res = matcher.getMatch();
+                final String plugin = res.group( 2 );
+                final String args = commandline.substring( res.endOffset( 0 ),
+                                                           commandline.length() - ( commandline.charAt( commandline.length() - 1 ) == '}' ? 1 : 0 ) );
+                final Map< String, String > arglist = pm.parseArgs( args );
 
                 // set wikitext bounds of plugin as '_bounds' parameter, e.g., [345,396]
-                if (pos != -1) {
-                    int end = pos + commandline.length() + 2;
-                    String bounds = pos + "|" + end;
-                    arglist.put(PluginManager.PARAM_BOUNDS, bounds);
+                if( pos != -1 ) {
+                    final int end = pos + commandline.length() + 2;
+                    final String bounds = pos + "|" + end;
+                    arglist.put( PluginManager.PARAM_BOUNDS, bounds );
                 }
 
-                PluginContent result = new PluginContent(plugin, arglist);
-
-                return result;
+                return new PluginContent( plugin, arglist );
             }
-        } catch (ClassCastException e) {
-            log.error("Invalid type offered in parsing plugin arguments.", e);
-            throw new InternalWikiException("Oops, someone offered !String!", e);
-        } catch (NoSuchElementException e) {
-            String msg = "Missing parameter in plugin definition: " + commandline;
-            log.warn(msg, e);
-            throw new PluginException(msg);
-        } catch (IOException e) {
-            String msg = "Zyrf.  Problems with parsing arguments: " + commandline;
-            log.warn(msg, e);
-            throw new PluginException(msg);
+        } catch( final ClassCastException e ) {
+            log.error( "Invalid type offered in parsing plugin arguments.", e );
+            throw new InternalWikiException( "Oops, someone offered !String!", e );
+        } catch( final NoSuchElementException e ) {
+            final String msg = "Missing parameter in plugin definition: " + commandline;
+            log.warn( msg, e );
+            throw new PluginException( msg );
+        } catch( final IOException e ) {
+            final String msg = "Zyrf.  Problems with parsing arguments: " + commandline;
+            log.warn( msg, e );
+            throw new PluginException( msg );
         }
 
         return null;
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/VariableContent.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/VariableContent.java
index ea12aa0..2d7ba47 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/VariableContent.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/VariableContent.java
@@ -19,22 +19,20 @@
 package org.apache.wiki.parser;
 
 import org.apache.commons.text.StringEscapeUtils;
-import org.jdom2.Text;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.api.exceptions.NoSuchVariableException;
-import org.apache.wiki.render.RenderingManager;
+import org.jdom2.Text;
 
 /**
  *  Stores the contents of a WikiVariable in a WikiDocument DOM tree.
  *  <p>
- *  When the WikiDocument is rendered, if the {@link RenderingManager#WYSIWYG_EDITOR_MODE}
- *  is set to {@link Boolean#TRUE}, the variable declaration is rendered instead
- *  of the variable value.
+ *  When the WikiDocument is rendered, if the {@link WikiContext#VAR_WYSIWYG_EDITOR_MODE} is set to {@link Boolean#TRUE}, the
+ *  variable declaration is rendered instead of the variable value.
  *
  *  @since  2.4
  */
-public class VariableContent extends Text
-{
+public class VariableContent extends Text {
+
     private static final long serialVersionUID = 1L;
 
     private String m_varName;
@@ -44,7 +42,7 @@ public class VariableContent extends Text
      *  
      *  @param varName The name of the variable.
      */
-    public VariableContent( String varName )
+    public VariableContent( final String varName )
     {
         m_varName = varName;
     }
@@ -54,36 +52,27 @@ public class VariableContent extends Text
      *   
      *   @return The rendered value of the variable.
      */
-    public String getValue()
-    {
-        String result = "";
-        WikiDocument root = (WikiDocument) getDocument();
+    public String getValue() {
+        String result;
+        final WikiDocument root = (WikiDocument) getDocument();
 
-        if( root == null )
-        {
+        if( root == null ) {
             // See similar note in PluginContent
             return m_varName;
         }
         
-        WikiContext context = root.getContext();
-
-        if( context == null )
+        final WikiContext context = root.getContext();
+        if( context == null ) {
             return "No WikiContext available: INTERNAL ERROR";
+        }
     
-        Boolean wysiwygEditorMode = (Boolean)context.getVariable(RenderingManager.WYSIWYG_EDITOR_MODE);
-        
-        if( wysiwygEditorMode != null && wysiwygEditorMode.booleanValue() )
-        {
+        final Boolean wysiwygEditorMode = ( Boolean )context.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
+        if( wysiwygEditorMode != null && wysiwygEditorMode ) {
             result = "[" + m_varName + "]";
-        }
-        else
-        {
-            try
-            {
+        } else {
+            try {
                 result = context.getEngine().getVariableManager().parseAndGetValue( context, m_varName );
-            }
-            catch( NoSuchVariableException e )
-            {
+            } catch( final NoSuchVariableException e ) {
                 result = MarkupParser.makeError( "No such variable: " + e.getMessage() ).getText(); 
             }
         }
@@ -95,8 +84,7 @@ public class VariableContent extends Text
      *  Returns exactly getValue().
      *  @return Whatever getValue() returns.
      */
-    public String getText()
-    {
+    public String getText() {
         return getValue();
     }
 
@@ -104,8 +92,8 @@ public class VariableContent extends Text
      *  Returns a debug-suitable string.
      *  @return Debug string
      */
-    public String toString()
-    {
-        return "VariableElement[\""+m_varName+"\"]";
+    public String toString() {
+        return "VariableElement[\"" + m_varName + "\"]";
     }
+
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index cb9969f..989a7ba 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -200,7 +200,7 @@ public class DefaultRenderingManager implements RenderingManager {
      */
     @Override
     public String getHTML( final WikiContext context, final WikiDocument doc ) throws IOException {
-        final Boolean wysiwygVariable = ( Boolean )context.getVariable( WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )context.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         final boolean wysiwygEditorMode;
         if( wysiwygVariable != null ) {
             wysiwygEditorMode = wysiwygVariable;
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index e80dbfa..12564dc 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -57,12 +57,6 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
 
     /**
-     *  Name of the WikiContext variable which is set to Boolean.TRUE or Boolean.FALSE depending on whether WYSIWYG is currently
-     *  in effect.
-     */
-    String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
-
-    /**
      *  Variable name which tells whether plugins should be executed or not.  Value can be either {@code Boolean.TRUE} or
      *  {@code Boolean.FALSE}. While not set it's value is {@code null}.
      */
@@ -97,19 +91,6 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     WikiDocument getRenderedDocument( WikiContext context, String pagedata );
 
     /**
-     *  Simply renders a WikiDocument to a String.  This version does not get the document from the cache - in fact, it does
-     *  not cache the document at all.  This is very useful, if you have something that you want to render outside the caching
-     *  routines.  Because the cache is based on full pages, and the cache keys are based on names, use this routine if you're
-     *  rendering anything for yourself.
-     *
-     *  @param context The WikiContext to render in
-     *  @param doc A proper WikiDocument
-     *  @return Rendered HTML.
-     *  @throws IOException If the WikiDocument is poorly formed.
-     */
-    String getHTML( WikiContext context, WikiDocument doc ) throws IOException;
-
-    /**
      * Returns a WikiRenderer instance, initialized with the given context and doc. The object is an XHTMLRenderer,
      * unless overridden in jspwiki.properties with PROP_RENDERER.
      *
@@ -131,6 +112,19 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     WikiRenderer getWysiwygRenderer( WikiContext context, WikiDocument doc );
 
     /**
+     *  Simply renders a WikiDocument to a String.  This version does not get the document from the cache - in fact, it does
+     *  not cache the document at all.  This is very useful, if you have something that you want to render outside the caching
+     *  routines.  Because the cache is based on full pages, and the cache keys are based on names, use this routine if you're
+     *  rendering anything for yourself.
+     *
+     *  @param context The WikiContext to render in
+     *  @param doc A proper WikiDocument
+     *  @return Rendered HTML.
+     *  @throws IOException If the WikiDocument is poorly formed.
+     */
+    String getHTML( WikiContext context, WikiDocument doc ) throws IOException;
+
+    /**
      *   Convenience method for rendering, using the default parser and renderer.  Note that you can't use this method
      *   to do any arbitrary rendering, as the pagedata MUST be the data from the that the WikiContext refers to - this
      *   method caches the HTML internally, and will return the cached version.  If the pagedata is different from what
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/variables/DefaultVariableManager.java b/jspwiki-main/src/main/java/org/apache/wiki/variables/DefaultVariableManager.java
index 7ba3d1a..c998d1d 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/variables/DefaultVariableManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/variables/DefaultVariableManager.java
@@ -29,7 +29,6 @@ import org.apache.wiki.api.exceptions.NoSuchVariableException;
 import org.apache.wiki.api.filters.PageFilter;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.modules.InternalModule;
-import org.apache.wiki.parser.LinkParsingOperations;
 import org.apache.wiki.preferences.Preferences;
 
 import javax.servlet.http.HttpServletRequest;
@@ -66,17 +65,9 @@ public class DefaultVariableManager implements VariableManager {
     }
 
     /**
-     *  Parses the link and finds a value.  This is essentially used once
-     *  {@link LinkParsingOperations#isVariableLink(String)} has found that
-     *  the link text actually contains a variable.  For example, you could
-     *  pass in "{$username}" and get back "JanneJalkanen".
-     *
-     *  @param  context The WikiContext
-     *  @param  link    The link text containing the variable name.
-     *  @return The variable value.
-     *  @throws IllegalArgumentException If the format is not valid (does not start with "{$", is zero length, etc.)
-     *  @throws NoSuchVariableException If a variable is not known.
+     *  {@inheritDoc}
      */
+    @Override
     public String parseAndGetValue( final WikiContext context, final String link ) throws IllegalArgumentException, NoSuchVariableException {
         if( !link.startsWith( "{$" ) ) {
             throw new IllegalArgumentException( "Link does not start with {$" );
@@ -90,15 +81,9 @@ public class DefaultVariableManager implements VariableManager {
     }
 
     /**
-     *  This method does in-place expansion of any variables.  However, the expansion is not done twice, that is,
-     *  a variable containing text $variable will not be expanded.
-     *  <P>
-     *  The variables should be in the same format ({$variablename} as in the web pages.
-     *
-     *  @param context The WikiContext of the current page.
-     *  @param source  The source string.
-     *  @return The source string with variables expanded.
+     *  {@inheritDoc}
      */
+    @Override
     // FIXME: somewhat slow.
     public String expandVariables( final WikiContext context, final String source ) {
         final StringBuilder result = new StringBuilder();
@@ -132,14 +117,9 @@ public class DefaultVariableManager implements VariableManager {
     }
 
     /**
-     *  Returns the value of a named variable.  See {@link #getValue(WikiContext, String)}. The only difference is that
-     *  this method does not throw an exception, but it returns the given default value instead.
-     *
-     *  @param context WikiContext
-     *  @param varName The name of the variable
-     *  @param defValue A default value.
-     *  @return The variable value, or if not found, the default value.
+     *  {@inheritDoc}
      */
+    @Override
     public String getValue( final WikiContext context, final String varName, final String defValue ) {
         try {
             return getValue( context, varName );
@@ -149,42 +129,17 @@ public class DefaultVariableManager implements VariableManager {
     }
 
     /**
-     *  Shortcut to getValue(). However, this method does not throw a NoSuchVariableException, but returns null
-     *  in case the variable does not exist.
-     *
-     *  @param context WikiContext to look the variable in
-     *  @param name Name of the variable to look for
-     *  @return Variable value, or null, if there is no such variable.
-     *  @since 2.2 on WikiEngine, moved to VariableManager on 2.11.0
+     *  {@inheritDoc}
      */
+    @Override
     public String getVariable( final WikiContext context, final String name ) {
         return getValue( context, name, null );
     }
 
     /**
-     *  Returns a value of the named variable.  The resolving order is
-     *  <ol>
-     *    <li>Known "constant" name, such as "pagename", etc.  This is so
-     *        that pages could not override certain constants.
-     *    <li>WikiContext local variable.  This allows a programmer to
-     *        set a parameter which cannot be overridden by user.
-     *    <li>HTTP Session
-     *    <li>HTTP Request parameters
-     *    <li>WikiPage variable.  As set by the user with the SET directive.
-     *    <li>jspwiki.properties
-     *  </ol>
-     *
-     *  Use this method only whenever you really need to have a parameter that
-     *  can be overridden by anyone using the wiki.
-     *
-     *  @param context The WikiContext
-     *  @param varName Name of the variable.
-     *
-     *  @return The variable value.
-     *
-     *  @throws IllegalArgumentException If the name is somehow broken.
-     *  @throws NoSuchVariableException If a variable is not known.
+     *  {@inheritDoc}
      */
+    @Override
     public String getValue( final WikiContext context, final String varName ) throws IllegalArgumentException, NoSuchVariableException {
         if( varName == null ) {
             throw new IllegalArgumentException( "Null variable name." );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java b/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
index 043c395..92cfab3 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
@@ -20,7 +20,6 @@ package org.apache.wiki.variables;
 
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.api.exceptions.NoSuchVariableException;
-import org.apache.wiki.parser.LinkParsingOperations;
 
 /**
  *  Manages variables.  Variables are case-insensitive.  A list of all available variables is on a Wiki page called "WikiVariables".
@@ -35,9 +34,9 @@ public interface VariableManager {
 
     /**
      *  Parses the link and finds a value.  This is essentially used once
-     *  {@link LinkParsingOperations#isVariableLink(String)} has found that
-     *  the link text actually contains a variable.  For example, you could
-     *  pass in "{$username}" and get back "JanneJalkanen".
+     *  {@link org.apache.wiki.parser.LinkParsingOperations#isVariableLink(String) LinkParsingOperations#isVariableLink(String)}
+     *  has found that the link text actually contains a variable.  For example, you could pass in "{$username}" and get back
+     *  "JanneJalkanen".
      *
      *  @param  context The WikiContext
      *  @param  link    The link text containing the variable name.
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
index 3c7daf4..4de92d6 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
@@ -18,17 +18,15 @@
  */
 package org.apache.wiki.markdown.extensions.jspwikilinks.attributeprovider;
 
+import com.vladsch.flexmark.ast.Link;
 import com.vladsch.flexmark.util.ast.Node;
+import com.vladsch.flexmark.util.html.Attributes;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
 import org.apache.wiki.parser.LinkParsingOperations;
 import org.apache.wiki.parser.MarkupParser;
-import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.util.TextUtil;
 
-import com.vladsch.flexmark.ast.Link;
-import com.vladsch.flexmark.util.html.Attributes;
-
 
 /**
  * {@link NodeAttributeProviderState} which sets the attributes for interwiki links.
@@ -44,7 +42,7 @@ public class InterWikiLinkAttributeProviderState implements NodeAttributeProvide
         this.hasRef = hasRef;
         this.wikiContext = wikiContext;
         this.linkOperations = new LinkParsingOperations( wikiContext );
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
index 48c5406..e0efb76 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
@@ -19,14 +19,12 @@
 package org.apache.wiki.markdown.extensions.jspwikilinks.attributeprovider;
 
 import com.vladsch.flexmark.util.ast.Node;
+import com.vladsch.flexmark.util.html.Attributes;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.htmltowiki.XHtmlToWikiConfig;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
-import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.render.WikiRenderer;
 
-import com.vladsch.flexmark.util.html.Attributes;
-
 
 /**
  * {@link NodeAttributeProviderState} to finish up polishing WYSIWYG editing mode. More or less equivalent to WysiwygEditingRenderer, the main difference
@@ -39,7 +37,7 @@ public class WysiwygEditingAttributeProviderState implements NodeAttributeProvid
 
     public WysiwygEditingAttributeProviderState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
@@ -71,7 +69,7 @@ public class WysiwygEditingAttributeProviderState implements NodeAttributeProvid
                     // to this wiki string: "TargetPage#Heading2".
                     attributes.replaceValue( "href", newHref.replaceFirst( WikiRenderer.LINKS_SOURCE, WikiRenderer.LINKS_TRANSLATION ) );
                 } else if( href != null && href.startsWith( editPageLinkUrl ) ) {
-                    String title = attributes.getValue( "title" );
+                    final String title = attributes.getValue( "title" );
                     if( title != null ) {
                         // remove the title since we don't want to eventually save the default undefined page title.
                         attributes.replaceValue( "title", "" );
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
index c7e46d4..3d6c4cb 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
@@ -26,7 +26,6 @@ import org.apache.wiki.WikiPage;
 import org.apache.wiki.auth.WikiSecurityException;
 import org.apache.wiki.auth.acl.Acl;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
-import org.apache.wiki.render.RenderingManager;
 
 
 /**
@@ -40,7 +39,7 @@ public class AccessRuleLinkNodePostProcessorState implements NodePostProcessorSt
 
     public AccessRuleLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
index 66b9cd7..39a1252 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
@@ -29,7 +29,6 @@ import org.apache.wiki.markdown.nodes.JSPWikiLink;
 import org.apache.wiki.parser.LinkParsingOperations;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.preferences.Preferences;
-import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.util.TextUtil;
 
 import java.text.MessageFormat;
@@ -53,7 +52,7 @@ public class InterWikiLinkNodePostProcessorState implements NodePostProcessorSta
         this.linkOperations = new LinkParsingOperations( wikiContext );
         this.document = document;
         this.m_useOutlinkImage = wikiContext.getBooleanWikiProperty( MarkupParser.PROP_USEOUTLINKIMAGE, m_useOutlinkImage );
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
index 99a9ed5..47661b5 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
@@ -25,7 +25,6 @@ import org.apache.wiki.WikiContext;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
 import org.apache.wiki.preferences.Preferences;
-import org.apache.wiki.render.RenderingManager;
 
 import java.text.MessageFormat;
 import java.util.ResourceBundle;
@@ -42,7 +41,7 @@ public class MetadataLinkNodePostProcessorState implements NodePostProcessorStat
 
     public MetadataLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
index 87d5b3c..4012797 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
@@ -25,7 +25,6 @@ import com.vladsch.flexmark.util.sequence.CharSubSequence;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
 import org.apache.wiki.parser.MarkupParser;
-import org.apache.wiki.render.RenderingManager;
 
 
 /**
@@ -47,7 +46,7 @@ class NodePostProcessorStateCommonOperations {
     }
 
     static void addOutlinkImage( final NodeTracker state, final Node node, final WikiContext wikiContext, final boolean useOutlinkImage ) {
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         final boolean wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable;
 
         if( useOutlinkImage && !wysiwygEditorMode ) {
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
index 4e13e3d..ea18af3 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
@@ -30,7 +30,6 @@ import org.apache.wiki.api.plugin.WikiPlugin;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
 import org.apache.wiki.parser.PluginContent;
 import org.apache.wiki.preferences.Preferences;
-import org.apache.wiki.render.RenderingManager;
 
 import java.text.MessageFormat;
 import java.util.ResourceBundle;
@@ -47,7 +46,7 @@ public class PluginLinkNodePostProcessorState implements NodePostProcessorState<
 
     public PluginLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
index 8855af5..6a72cf7 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
@@ -26,7 +26,6 @@ import org.apache.commons.text.StringEscapeUtils;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.api.exceptions.NoSuchVariableException;
 import org.apache.wiki.markdown.nodes.JSPWikiLink;
-import org.apache.wiki.render.RenderingManager;
 
 
 /**
@@ -39,7 +38,7 @@ public class VariableLinkNodePostProcessorState implements NodePostProcessorStat
 
     public VariableLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
-        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
+        final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE );
         m_wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable;
     }
 
diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
index 71bdce9..d7ab340 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/CKeditor.jsp
@@ -50,7 +50,7 @@
            "//cdn.ckeditor.com/4.5.1/standard/ckeditor.js" );
     */
 
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -108,7 +108,7 @@
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for CKeditor has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
 
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
index 4d5ca8d..470d060 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/FCK.jsp
@@ -38,7 +38,7 @@
 --%>
 <%  WikiContext context = WikiContext.findContext( pageContext );
     WikiEngine engine = context.getEngine();
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -85,7 +85,7 @@
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for FCK has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
diff --git a/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp b/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
index 1ce9593..45c4335 100644
--- a/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/editors/TinyMCE.jsp
@@ -50,7 +50,7 @@
            "//tinymce.cachefly.net/4.2/tinymce.min.js" );
     */
 
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -95,21 +95,17 @@
    if( usertext == null ) usertext = "";
 
    String pageAsHtml;
-   try
-   {
+   try {
        //pageAsHtml = StringEscapeUtils.escapeJavaScript( engine.getRenderingManager().getHTML( context, usertext ) );
        pageAsHtml = engine.getRenderingManager().getHTML( context, usertext );
-   }
-       catch( Exception e )
-   {
+   } catch( Exception e ) {
        pageAsHtml = "Error in converting wiki-markup to well-formed HTML \n" + e.toString();
        //pageAsHtml = e.toString() + "\n" + usertext; //error
    }
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for TinyMCE has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
index 081e5cd..9fa10da 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/CKeditor.jsp
@@ -51,7 +51,7 @@
            "//cdn.ckeditor.com/4.5.1/standard/ckeditor.js" );
     */
 
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -114,8 +114,7 @@
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for CKeditor has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
index 2965c13..5e46921 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/TinyMCE.jsp
@@ -48,7 +48,7 @@
     WikiContext context = WikiContext.findContext( pageContext );
     WikiEngine engine = context.getEngine();
 
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -115,15 +115,12 @@
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for TinyMCE has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
-
    /*FSS not used
    String templateDir = (String)engine.getWikiProperties().get( WikiEngine.PROP_TEMPLATEDIR );
-
    String protocol = "http://";
    if( request.isSecure() )
    {
diff --git a/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp b/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
index ba2e504..7c2db80 100644
--- a/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/editors/wysiwyg.jsp
@@ -44,7 +44,7 @@
     WikiContext context = WikiContext.findContext( pageContext );
     WikiEngine engine = context.getEngine();
 
-    context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.TRUE );
+    context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.TRUE );
     context.setVariable( WikiEngine.PROP_RUNFILTERS,  "false" );
 
     WikiPage wikiPage = context.getPage();
@@ -106,14 +106,12 @@
 
    // Disable the WYSIWYG_EDITOR_MODE and reset the other properties immediately
    // after the XHTML for wysiwyg editor has been rendered.
-   context.setVariable( RenderingManager.WYSIWYG_EDITOR_MODE, Boolean.FALSE );
-
+   context.setVariable( WikiContext.VAR_WYSIWYG_EDITOR_MODE, Boolean.FALSE );
    context.setVariable( WikiEngine.PROP_RUNFILTERS,  null );
    wikiPage.setAttribute( JSPWikiMarkupParser.PROP_CAMELCASELINKS, originalCCLOption );
 
    /*not used
    String templateDir = (String)engine.getWikiProperties().get( WikiEngine.PROP_TEMPLATEDIR );
-
    String protocol = "http://";
    if( request.isSecure() )
    {


[jspwiki] 11/26: fix bug from previous refactor: parsed WikiDocument containing title must have the associated WikiContext

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 4e2ca7168f554bdf0821f9cd1a0e836c19f390b6
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 21:20:52 2020 +0100

    fix bug from previous refactor: parsed WikiDocument containing title must have the associated WikiContext
---
 .../src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
index 567e65c..178e468 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
@@ -848,11 +848,13 @@ public class JSPWikiMarkupParser extends MarkupParser {
         try {
             final JSPWikiMarkupParser dtr = getCleanTranslator();
             dtr.setInputReader( new StringReader( title ) );
+            final WikiDocument doc = dtr.parse();
+            doc.setContext( m_context );
 
-            return XmlUtil.extractTextFromDocument( dtr.parse() );
+            return XmlUtil.extractTextFromDocument( doc );
         } catch( final IOException e ) {
-            log.fatal("CleanTranslator not working", e );
-            throw new InternalWikiException( "CleanTranslator not working as expected, when cleaning title"+ e.getMessage() , e );
+            log.fatal("Title parsing not working", e );
+            throw new InternalWikiException( "Xml text extraction not working as expected when cleaning title" + e.getMessage() , e );
         }
     }
 


[jspwiki] 08/26: format code

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 373f662a62b78da3a24e6e4ed25c0d75bf95e038
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 00:26:26 2020 +0100

    format code
---
 .../java/org/apache/wiki/parser/WikiDocument.java  | 41 ++++++++++------------
 1 file changed, 18 insertions(+), 23 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/WikiDocument.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/WikiDocument.java
index 3cfe7b9..d7967c5 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/WikiDocument.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/WikiDocument.java
@@ -18,40 +18,36 @@
 */
 package org.apache.wiki.parser;
 
-import java.lang.ref.WeakReference;
-
-import org.jdom2.Document;
-
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiPage;
+import org.jdom2.Document;
+
+import java.lang.ref.WeakReference;
 
 /**
- *  Stores the DOM tree of a rendered WikiPage.  This class
- *  extends the org.jdom.Document to provide some extra metadata
+ *  Stores the DOM tree of a rendered WikiPage. This class extends the org.jdom.Document to provide some extra metadata
  *  specific to JSPWiki.
  *  <p>
- *  The document is not stored as metadata in the WikiPage because
- *  otherwise it could not be cached separately.
+ *  The document is not stored as metadata in the WikiPage because otherwise it could not be cached separately.
  *  
  *  @since  2.4
  */
-public class WikiDocument extends Document
-{
+public class WikiDocument extends Document {
+
     private static final long serialVersionUID = 1L;
     
-    private WikiPage                   m_page;
-    private String                     m_wikiText;
-
-    private WeakReference<WikiContext> m_context;
+    private WikiPage m_page;
+    private String m_wikiText;
+    private WeakReference< WikiContext > m_context;
     
     /**
      *  Creates a new WikiDocument for a specific page.
      * 
      *  @param page The page to which this document refers to.
      */
-    public WikiDocument( WikiPage page )
+    public WikiDocument( final WikiPage page )
     {
-        m_page     = page;
+        m_page = page;
     }
     
     /**
@@ -59,7 +55,7 @@ public class WikiDocument extends Document
      *  
      *  @param data The WikiMarkup
      */
-    public void setPageData( String data )
+    public void setPageData( final String data )
     {
         m_wikiText = data;
     }
@@ -85,17 +81,15 @@ public class WikiDocument extends Document
     }
 
     /**
-     *  Set the WikiContext in which the WikiDocument is rendered. The
-     *  WikiContext is stored in a WeakReference, which means that it 
-     *  can be garbagecollected away.  This is to allow for caching of
-     *  the WikiDocument without having to carry the WikiContext around
+     *  Set the WikiContext in which the WikiDocument is rendered. The WikiContext is stored in a WeakReference, which means that it
+     *  can be garbagecollected away.  This is to allow for caching of the WikiDocument without having to carry the WikiContext around
      *  for a long time.
      *  
      *  @param ctx A WikiContext.
      */
-    public void setContext( WikiContext ctx )
+    public void setContext( final WikiContext ctx )
     {
-        m_context = new WeakReference<WikiContext>( ctx );
+        m_context = new WeakReference<>( ctx );
     }
     
     /**
@@ -108,4 +102,5 @@ public class WikiDocument extends Document
     {
         return m_context.get();
     }
+
 }


[jspwiki] 23/26: apply further formatting

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit d518941177d75a13fbdd4ebe4ca2cf9bade3c238
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 23:34:02 2020 +0100

    apply further formatting
---
 .../java/org/apache/wiki/parser/MarkupParser.java  | 120 ++++-----
 .../main/java/org/apache/wiki/util/TextUtil.java   | 298 ++++++++++-----------
 2 files changed, 190 insertions(+), 228 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
index 5450a8b..0bcdad6 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
@@ -42,92 +42,82 @@ import java.util.List;
  *
  *   @since  2.4
  */
-public abstract class MarkupParser
-{
-    /** Allow this many characters to be pushed back in the stream.  In effect,
-        this limits the size of a single line.  */
-    protected static final int              PUSHBACK_BUFFER_SIZE = 10*1024;
-    protected PushbackReader                m_in;
-    private int              m_pos = -1; // current position in reader stream
+public abstract class MarkupParser {
 
-    protected WikiEngine     m_engine;
-    protected WikiContext    m_context;
+    /** Allow this many characters to be pushed back in the stream.  In effect, this limits the size of a single line.  */
+    protected static final int PUSHBACK_BUFFER_SIZE = 10*1024;
+    protected PushbackReader m_in;
+    private int m_pos = -1; // current position in reader stream
+
+    protected WikiEngine m_engine;
+    protected WikiContext m_context;
 
     /** Optionally stores internal wikilinks */
-    protected ArrayList< StringTransmutator >      m_localLinkMutatorChain    = new ArrayList<>();
-    protected ArrayList< StringTransmutator >      m_externalLinkMutatorChain = new ArrayList<>();
-    protected ArrayList< StringTransmutator >      m_attachmentLinkMutatorChain = new ArrayList<>();
-    protected ArrayList< HeadingListener >         m_headingListenerChain     = new ArrayList<>();
-    protected ArrayList< StringTransmutator >      m_linkMutators             = new ArrayList<>();
-
-    protected boolean        m_inlineImages     = true;
-    protected boolean        m_parseAccessRules = true;
+    protected ArrayList< StringTransmutator > m_localLinkMutatorChain = new ArrayList<>();
+    protected ArrayList< StringTransmutator > m_externalLinkMutatorChain = new ArrayList<>();
+    protected ArrayList< StringTransmutator > m_attachmentLinkMutatorChain = new ArrayList<>();
+    protected ArrayList< StringTransmutator > m_linkMutators = new ArrayList<>();
+    protected ArrayList< HeadingListener > m_headingListenerChain = new ArrayList<>();
+
+    protected boolean m_inlineImages = true;
+    protected boolean m_parseAccessRules = true;
     /** Keeps image regexp Patterns */
     protected List< Pattern > m_inlineImagePatterns = null;
     protected LinkParsingOperations m_linkParsingOperations;
 
     private static final Logger log = Logger.getLogger( MarkupParser.class );
 
-    /** If set to "true", allows using raw HTML within Wiki text.  Be warned,
-        this is a VERY dangerous option to set - never turn this on in a publicly
-        allowable Wiki, unless you are absolutely certain of what you're doing. */
-    public static final String     PROP_ALLOWHTML        = "jspwiki.translatorReader.allowHTML";
+    /** If set to "true", allows using raw HTML within Wiki text.  Be warned, this is a VERY dangerous option to set -
+       never turn this on in a publicly allowable Wiki, unless you are absolutely certain of what you're doing. */
+    public static final String PROP_ALLOWHTML = "jspwiki.translatorReader.allowHTML";
+
     /** If set to "true", enables plugins during parsing */
-    public static final String     PROP_RUNPLUGINS       = "jspwiki.translatorReader.runPlugins";
+    public static final String PROP_RUNPLUGINS = "jspwiki.translatorReader.runPlugins";
 
-    /** Lists all punctuation characters allowed in WikiMarkup. These
-        will not be cleaned away. This is for compatibility for older versions
+    /** If true, all outward links (external links) have a small link image appended. */
+    public static final String PROP_USEOUTLINKIMAGE = "jspwiki.translatorReader.useOutlinkImage";
+
+    /** If set to "true", all external links are tagged with 'rel="nofollow"' */
+    public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow";
+
+    /** Lists all punctuation characters allowed in WikiMarkup. These will not be cleaned away. This is for compatibility for older versions
         of JSPWiki. */
-    protected static final String LEGACY_CHARS_ALLOWED      = "._";
+    protected static final String LEGACY_CHARS_ALLOWED = "._";
 
     /** Lists all punctuation characters allowed in page names. */
-    public    static final String PUNCTUATION_CHARS_ALLOWED = " ()&+,-=._$";
+    public static final String PUNCTUATION_CHARS_ALLOWED = " ()&+,-=._$";
 
-    public    static final String HASHLINK = "hashlink";
+    public static final String HASHLINK = "hashlink";
 
     /** Name of the outlink image; relative path to the JSPWiki directory. */
-    public    static final String OUTLINK_IMAGE = "images/out.png";
+    public static final String OUTLINK_IMAGE = "images/out.png";
     /** Outlink css class. */
-    public    static final String OUTLINK = "outlink";
-
-    /** If true, all outward links (external links) have a small link image appended. */
-    public    static final String PROP_USEOUTLINKIMAGE  = "jspwiki.translatorReader.useOutlinkImage";
+    public static final String OUTLINK = "outlink";
 
-    private   static final String INLINE_IMAGE_PATTERNS = "JSPWikiMarkupParser.inlineImagePatterns";
+    private static final String INLINE_IMAGE_PATTERNS = "JSPWikiMarkupParser.inlineImagePatterns";
 
-    /** If set to "true", all external links are tagged with 'rel="nofollow"' */
-    public static final String     PROP_USERELNOFOLLOW   = "jspwiki.translatorReader.useRelNofollow";
-
-    /** The value for anchor element <tt>class</tt> attributes when used
-     * for wiki page (normal) links. The value is "wikipage". */
+    /** The value for anchor element <tt>class</tt> attributes when used for wiki page (normal) links. The value is "wikipage". */
    public static final String CLASS_WIKIPAGE = "wikipage";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for edit page links. The value is "createpage". */
+   /** The value for anchor element <tt>class</tt> attributes when used for edit page links. The value is "createpage". */
    public static final String CLASS_EDITPAGE = "createpage";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for interwiki page links. The value is "interwiki". */
+   /** The value for anchor element <tt>class</tt> attributes when used for interwiki page links. The value is "interwiki". */
    public static final String CLASS_INTERWIKI = "interwiki";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for footnote links. The value is "footnote". */
+   /** The value for anchor element <tt>class</tt> attributes when used for footnote links. The value is "footnote". */
    public static final String CLASS_FOOTNOTE = "footnote";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for footnote links. The value is "footnote". */
+   /** The value for anchor element <tt>class</tt> attributes when used for footnote links. The value is "footnote". */
    public static final String CLASS_FOOTNOTE_REF = "footnoteref";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for external links. The value is "external". */
+   /** The value for anchor element <tt>class</tt> attributes when used for external links. The value is "external". */
    public static final String CLASS_EXTERNAL = "external";
 
-   /** The value for anchor element <tt>class</tt> attributes when used
-     * for attachments. The value is "attachment". */
+   /** The value for anchor element <tt>class</tt> attributes when used for attachments. The value is "attachment". */
    public static final String CLASS_ATTACHMENT = "attachment";
 
-   public static final String[] CLASS_TYPES =
-   {
+   public static final String[] CLASS_TYPES = {
       CLASS_WIKIPAGE,
       CLASS_EDITPAGE,
       "",
@@ -355,6 +345,19 @@ public abstract class MarkupParser
     }
 
     /**
+     *  Cleans away extra legacy characters.  This method functions exactly like pre-2.6 cleanLink()
+     *  <P>
+     *  [ This is a link ] -&gt; ThisIsALink
+     *
+     *  @param link Link to be cleared. Null is safe, and causes this to return null.
+     *  @return A cleaned link.
+     *  @since 2.6
+     */
+    public static String wikifyLink( final String link ) {
+        return cleanLink( link, LEGACY_CHARS_ALLOWED );
+    }
+
+    /**
      *  Cleans a Wiki name based on a list of characters.  Also, any multiple whitespace is collapsed into a single space, and any
      *  leading or trailing space is removed.
      *
@@ -409,17 +412,4 @@ public abstract class MarkupParser
         return clean.toString();
     }
 
-    /**
-     *  Cleans away extra legacy characters.  This method functions exactly like pre-2.6 cleanLink()
-     *  <P>
-     *  [ This is a link ] -&gt; ThisIsALink
-     *
-     *  @param link Link to be cleared. Null is safe, and causes this to return null.
-     *  @return A cleaned link.
-     *  @since 2.6
-     */
-    public static String wikifyLink( final String link ) {
-        return MarkupParser.cleanLink(link, LEGACY_CHARS_ALLOWED);
-    }
-
 }
diff --git a/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java b/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
index ba46853..31bf8a1 100644
--- a/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
+++ b/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
@@ -35,45 +35,42 @@ import java.util.Random;
  */
 public final class TextUtil {
 
-    static final String   HEX_DIGITS = "0123456789ABCDEF";
+    static final String HEX_DIGITS = "0123456789ABCDEF";
 
-    /**
-     *  Private constructor prevents instantiation.
-     */
+    /** Pick from some letters that won't be easily mistaken for each other to compose passwords. So, for example, omit o O and 0, 1 l and L.*/
+    static final String PWD_BASE = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+@";
+
+    /** Length of password. {@link #generateRandomPassword() */
+    public static final int PASSWORD_LENGTH = 8;
+
+    /** Private constructor prevents instantiation. */
     private TextUtil() {}
 
     /**
-     *  java.net.URLEncoder.encode() method in JDK < 1.4 is buggy.  This duplicates
-     *  its functionality.
+     *  java.net.URLEncoder.encode() method in JDK < 1.4 is buggy.  This duplicates its functionality.
+     *
      *  @param rs the string to encode
      *  @return the URL-encoded string
      */
-    protected static String urlEncode( byte[] rs ) {
-    	StringBuilder result = new StringBuilder(rs.length*2);
-
-        // Does the URLEncoding.  We could use the java.net one, but
-        // it does not eat byte[]s.
-
-        for( int i = 0; i < rs.length; i++ ) {
-            char c = ( char )rs[i];
+    protected static String urlEncode( final byte[] rs ) {
+    	final StringBuilder result = new StringBuilder( rs.length * 2 );
 
+        // Does the URLEncoding.  We could use the java.net one, but it does not eat byte[]s.
+        for( final byte r : rs ) {
+            final char c = ( char )r;
             switch( c ) {
-              case '_':
-              case '.':
-              case '*':
-              case '-':
-              case '/':
+            case '_':
+            case '.':
+            case '*':
+            case '-':
+            case '/':
                 result.append( c );
                 break;
-
-              case ' ':
+            case ' ':
                 result.append( '+' );
                 break;
-
-              default:
-                if( ( c >= 'a' && c <= 'z' ) ||
-                    ( c >= 'A' && c <= 'Z' ) ||
-                    ( c >= '0' && c <= '9' ) ) {
+            default:
+                if( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) ) {
                     result.append( c );
                 } else {
                     result.append( '%' );
@@ -81,15 +78,13 @@ public final class TextUtil {
                     result.append( HEX_DIGITS.charAt( c & 0x0F ) );
                 }
             }
-
-        } // for
+        }
 
         return result.toString();
     }
 
     /**
-     *  URL encoder does not handle all characters correctly.
-     *  See <A HREF="http://developer.java.sun.com/developer/bugParade/bugs/4257115.html">
+     *  URL encoder does not handle all characters correctly. See <A HREF="http://developer.java.sun.com/developer/bugParade/bugs/4257115.html">
      *  Bug parade, bug #4257115</A> for more information.
      *  <P>
      *  Thanks to CJB for this fix.
@@ -100,12 +95,12 @@ public final class TextUtil {
      *
      *  @throws IllegalArgumentException If the byte array is not a valid string.
      */
-    protected static String urlDecode( byte[] bytes, String encoding ) throws  IllegalArgumentException {
+    protected static String urlDecode( final byte[] bytes, final String encoding ) throws  IllegalArgumentException {
         if( bytes == null ) {
             return null;
         }
 
-        byte[] decodeBytes   = new byte[bytes.length];
+        final byte[] decodeBytes = new byte[ bytes.length ];
         int decodedByteCount = 0;
 
         try {
@@ -125,7 +120,7 @@ public final class TextUtil {
                 }
             }
 
-        } catch( IndexOutOfBoundsException ae ) {
+        } catch( final IndexOutOfBoundsException ae ) {
             throw new IllegalArgumentException( "Malformed UTF-8 string?" );
         }
 
@@ -138,14 +133,13 @@ public final class TextUtil {
      *  @param text The text to decode
      *  @return An URLEncoded string.
      */
-    public static String urlEncodeUTF8( String text ) {
+    public static String urlEncodeUTF8( final String text ) {
         // If text is null, just return an empty string
         if ( text == null ) {
             return "";
         }
 
-        byte[] rs = text.getBytes( StandardCharsets.UTF_8 );
-        return urlEncode( rs );
+        return urlEncode( text.getBytes( StandardCharsets.UTF_8 ) );
     }
 
     /**
@@ -154,7 +148,7 @@ public final class TextUtil {
      *  @param utf8 The UTF-8 encoded string
      *  @return A plain, normal string.
      */
-    public static String urlDecodeUTF8( String utf8 ) {
+    public static String urlDecodeUTF8( final String utf8 ) {
         if( utf8 == null ) {
             return null;
         }
@@ -171,9 +165,8 @@ public final class TextUtil {
      * @param encoding The encoding in which to encode
      * @return An URL encoded string.
      */
-    public static String urlEncode( String data, String encoding ) {
-        // Presumably, the same caveats apply as in FileSystemProvider.
-        // Don't see why it would be horribly kludgy, though.
+    public static String urlEncode( final String data, final String encoding ) {
+        // Presumably, the same caveats apply as in FileSystemProvider. Don't see why it would be horribly kludgy, though.
         if( StandardCharsets.UTF_8.toString().equals( encoding ) ) {
             return urlEncodeUTF8( data );
         }
@@ -191,9 +184,8 @@ public final class TextUtil {
      * @return A decoded string.
      * @throws IllegalArgumentException If the data cannot be decoded.
      */
-    public static String urlDecode( String data, String encoding ) throws IllegalArgumentException {
-        // Presumably, the same caveats apply as in FileSystemProvider.
-        // Don't see why it would be horribly kludgy, though.
+    public static String urlDecode( final String data, final String encoding ) throws IllegalArgumentException {
+        // Presumably, the same caveats apply as in FileSystemProvider. Don't see why it would be horribly kludgy, though.
         if( "UTF-8".equals( encoding ) ) {
             return urlDecodeUTF8( data );
         }
@@ -202,8 +194,7 @@ public final class TextUtil {
     }
 
     /**
-     *  Replaces the relevant entities inside the String. All &amp; &gt;, &lt;, and &quot; are replaced by their
-     *  respective names.
+     *  Replaces the relevant entities inside the String. All &amp; &gt;, &lt;, and &quot; are replaced by their respective names.
      *
      *  @since 1.6.1
      *  @param src The source string.
@@ -226,13 +217,19 @@ public final class TextUtil {
      *  @param dest The string to replace <I>src</I> with.
      *  @return A string with the replacement done.
      */
-    public static String replaceString( String orig, String src, String dest ) {
-        if ( orig == null ) return null;
-        if ( src == null || dest == null ) throw new NullPointerException();
-        if ( src.length() == 0 ) return orig;
+    public static String replaceString( final String orig, final String src, final String dest ) {
+        if ( orig == null ) {
+            return null;
+        }
+        if ( src == null || dest == null ) {
+            throw new NullPointerException();
+        }
+        if ( src.length() == 0 ) {
+            return orig;
+        }
 
-        StringBuilder res = new StringBuilder( orig.length() + 20 ); // Pure guesswork
-        int start = 0;
+        final StringBuilder res = new StringBuilder( orig.length() + 20 ); // Pure guesswork
+        int start;
         int end = 0;
         int last = 0;
 
@@ -242,7 +239,6 @@ public final class TextUtil {
             end  = start + src.length();
             last = start + src.length();
         }
-
         res.append( orig.substring( end ) );
 
         return res.toString();
@@ -257,10 +253,12 @@ public final class TextUtil {
      *  @param text The new text to insert into the string.
      *  @return The string with the orig replaced with text.
      */
-    public static String replaceString( String orig, int start, int end, String text ) {
-        if( orig == null ) return null;
+    public static String replaceString( final String orig, final int start, final int end, final String text ) {
+        if( orig == null ) {
+            return null;
+        }
 
-        StringBuilder buf = new StringBuilder(orig);
+        final StringBuilder buf = new StringBuilder( orig );
         buf.replace( start, end, text );
         return buf.toString();
     }
@@ -273,24 +271,24 @@ public final class TextUtil {
      *  @param dest The string to replace <I>src</I> with.
      *  @return A string with all instances of src replaced with dest.
      */
-    public static String replaceStringCaseUnsensitive( String orig, String src, String dest ) {
-        if( orig == null ) return null;
-
-        StringBuilder res = new StringBuilder();
-        int start        = 0;
-        int end          = 0;
-        int last         = 0;
+    public static String replaceStringCaseUnsensitive( final String orig, final String src, final String dest ) {
+        if( orig == null ) {
+            return null;
+        }
 
-        String origCaseUnsn = orig.toLowerCase();
-        String srcCaseUnsn = src.toLowerCase();
+        final StringBuilder res = new StringBuilder();
+        int start;
+        int end = 0;
+        int last = 0;
 
+        final String origCaseUnsn = orig.toLowerCase();
+        final String srcCaseUnsn = src.toLowerCase();
         while( ( start = origCaseUnsn.indexOf( srcCaseUnsn, end ) ) != -1 ) {
             res.append( orig.substring( last, start ) );
             res.append( dest );
             end  = start + src.length();
             last = start + src.length();
         }
-
         res.append( orig.substring( end ) );
 
         return res.toString();
@@ -303,25 +301,21 @@ public final class TextUtil {
      *  @param defvalue A default value in case the value is not a number
      *  @return The parsed value (or defvalue).
      */
-    public static int parseIntParameter( String value, int defvalue ) {
-        int val = defvalue;
-
+    public static int parseIntParameter( final String value, final int defvalue ) {
         try {
-            val = Integer.parseInt( value.trim() );
-        } catch( Exception e ) {}
+            return Integer.parseInt( value.trim() );
+        } catch( final Exception e ) {}
 
-        return val;
+        return defvalue;
     }
 
     /**
      *  Gets an integer-valued property from a standard Properties list.
      *
-     *  Before inspecting the props, we first check if there is a Java System Property with the same name, if it exists
-     *  we use that value, if not we check an environment variable with that (almost) same name, almost meaning we replace
-     *  dots with underscores.
+     *  Before inspecting the props, we first check if there is a Java System Property with the same name, if it exists we use that value,
+     *  if not we check an environment variable with that (almost) same name, almost meaning we replace dots with underscores.
      *
-     *  If the value does not exist, or is a
-     *  non-integer, returns defVal.
+     *  If the value does not exist, or is a non-integer, returns defVal.
      *
      *  @since 2.1.48.
      *  @param props The property set to look through
@@ -329,23 +323,22 @@ public final class TextUtil {
      *  @param defVal If the property is not found or is a non-integer, returns this value.
      *  @return The property value as an integer (or defVal).
      */
-    public static int getIntegerProperty( Properties props,  String key, int defVal ) {
-        String val = System.getProperties().getProperty(key, System.getenv(StringUtils.replace(key,".","_")));
-        if (val == null) {
-            val = props.getProperty(key);
+    public static int getIntegerProperty( final Properties props, final String key, final int defVal ) {
+        String val = System.getProperties().getProperty( key, System.getenv( StringUtils.replace( key,".","_" ) ) );
+        if( val == null ) {
+            val = props.getProperty( key );
         }
         return parseIntParameter( val, defVal );
     }
 
     /**
-     *  Gets a boolean property from a standard Properties list. Returns the default value, in case the key has not
-     *  been set.
+     *  Gets a boolean property from a standard Properties list. Returns the default value, in case the key has not been set.
      *  Before inspecting the props, we first check if there is a Java System Property with the same name, if it exists
      *  we use that value, if not we check an environment variable with that (almost) same name, almost meaning we replace
      *  dots with underscores.
      *  <P>
-     *  The possible values for the property are "true"/"false", "yes"/"no", or "on"/"off".  Any value not
-     *  recognized is always defined as "false".
+     *  The possible values for the property are "true"/"false", "yes"/"no", or "on"/"off".  Any value not recognized is always defined
+     *  as "false".
      *
      *  @param props   A list of properties to search.
      *  @param key     The property key.
@@ -355,10 +348,10 @@ public final class TextUtil {
      *
      *  @since 2.0.11
      */
-    public static boolean getBooleanProperty( Properties props, String key, boolean defval ) {
-        String val = System.getProperties().getProperty(key, System.getenv(StringUtils.replace(key,".","_")));
-        if (val == null) {
-            val = props.getProperty(key);
+    public static boolean getBooleanProperty( final Properties props, final String key, final boolean defval ) {
+        String val = System.getProperties().getProperty( key, System.getenv( StringUtils.replace( key,".","_" ) ) );
+        if( val == null ) {
+            val = props.getProperty( key );
         }
         if( val == null ) {
             return defval;
@@ -381,12 +374,12 @@ public final class TextUtil {
      *  @return The property value.
      *  @since 2.1.151
      */
-    public static String getStringProperty(Properties props, String key, String defval) {
-        String val = System.getProperties().getProperty(key, System.getenv(StringUtils.replace(key,".","_")));
-        if (val == null) {
-            val = props.getProperty(key);
+    public static String getStringProperty( final Properties props, final String key, final String defval ) {
+        String val = System.getProperties().getProperty( key, System.getenv( StringUtils.replace( key,".","_" ) ) );
+        if( val == null ) {
+            val = props.getProperty( key );
         }
-        if (val == null) {
+        if( val == null ) {
             return defval;
         }
         return val.trim();
@@ -396,14 +389,14 @@ public final class TextUtil {
      *  Throws an exception if a property is not found.
      *
      *  @param props A set of properties to search the key in.
-     *  @param key   The key to look for.
+     *  @param key The key to look for.
      *  @return The required property
      *
      *  @throws NoSuchElementException If the search key is not in the property set.
      *  @since 2.0.26 (on TextUtils, moved To WikiEngine on 2.11.0-M1 and back to TextUtils on 2.11.0-M6)
      */
-    public static String getRequiredProperty( Properties props, String key ) throws NoSuchElementException {
-        String value = getStringProperty( props, key, null );
+    public static String getRequiredProperty( final Properties props, final String key ) throws NoSuchElementException {
+        final String value = getStringProperty( props, key, null );
         if( value == null ) {
             throw new NoSuchElementException( "Required property not found: " + key );
         }
@@ -413,12 +406,10 @@ public final class TextUtil {
     /**
      *  Fetches a file path property from the set of Properties.
      *
-     *  Before inspecting the props, we first check if there is a Java System Property with the same name, if it exists
-     *  we use that value, if not we check an environment variable with that (almost) same name, almost meaning we replace
-     *  dots with underscores.
+     *  Before inspecting the props, we first check if there is a Java System Property with the same name, if it exists we use that value,
+     *  if not we check an environment variable with that (almost) same name, almost meaning we replace dots with underscores.
      *
-     *  If the implementation fails to create the canonical path it just returns
-     *  the original value of the property which is a bit doggy.
+     *  If the implementation fails to create the canonical path it just returns the original value of the property which is a bit doggy.
      *
      *  @param props The Properties to search through
      *  @param key   The property key
@@ -426,22 +417,20 @@ public final class TextUtil {
      *  @return the canonical path of the file or directory being referenced
      *  @since 2.10.1
      */
-    public static String getCanonicalFilePathProperty(Properties props, String key, String defval) {
-
-        String result;
-        String val = System.getProperties().getProperty(key, System.getenv(StringUtils.replace(key,".","_")));
-        if (val == null) {
-            val = props.getProperty(key);
+    public static String getCanonicalFilePathProperty( final Properties props, final String key, final String defval ) {
+        String val = System.getProperties().getProperty( key, System.getenv( StringUtils.replace( key,".","_" ) ) );
+        if( val == null ) {
+            val = props.getProperty( key );
         }
 
         if( val == null ) {
             val = defval;
         }
 
+        String result;
         try {
-            result = new File(new File(val.trim()).getCanonicalPath()).getAbsolutePath();
-        }
-        catch(IOException e) {
+            result = new File( new File( val.trim() ).getCanonicalPath() ).getAbsolutePath();
+        } catch( final IOException e ) {
             result = val.trim();
         }
         return result;
@@ -461,7 +450,9 @@ public final class TextUtil {
         	return false;
         }
         val = val.trim();
-        return val.equalsIgnoreCase( "true" ) || val.equalsIgnoreCase( "on" ) || val.equalsIgnoreCase( "yes" );
+        return val.equalsIgnoreCase( "true" )
+               || val.equalsIgnoreCase( "on" )
+               || val.equalsIgnoreCase( "yes" );
     }
 
     /**
@@ -472,15 +463,13 @@ public final class TextUtil {
      *  <LI>The CR/LF/CRLF mess is normalized to plain CRLF.
      *  </UL>
      *
-     *  The reason why we're using CRLF is that most browser already return CRLF since that is the closest thing to
-     *  a HTTP standard.
+     *  The reason why we're using CRLF is that most browser already return CRLF since that is the closest thing to a HTTP standard.
      *
      *  @param postData The data to normalize
      *  @return Normalized data
      */
-    public static String normalizePostData( String postData ) {
-        StringBuilder sb = new StringBuilder();
-
+    public static String normalizePostData( final String postData ) {
+        final StringBuilder sb = new StringBuilder();
         for( int i = 0; i < postData.length(); i++ ) {
             switch( postData.charAt(i) ) {
               case 0x0a: // LF, UNIX
@@ -496,7 +485,7 @@ public final class TextUtil {
                 break;
 
               default:
-                sb.append( postData.charAt(i) );
+                sb.append( postData.charAt( i ) );
                 break;
             }
         }
@@ -515,12 +504,12 @@ public final class TextUtil {
     private static final int OTHER = 4;
     private static final Random RANDOM = new SecureRandom();
 
-    private static int getCharKind( int c ) {
+    private static int getCharKind( final int c ) {
         if( c == -1 ) {
             return EOI;
         }
 
-        char ch = ( char )c;
+        final char ch = ( char )c;
 
         if( Character.isLowerCase( ch ) ) {
             return LOWER;
@@ -534,39 +523,36 @@ public final class TextUtil {
     }
 
     /**
-     *  Adds spaces in suitable locations of the input string.  This is used to transform a WikiName into a more
-     *  readable format.
+     *  Adds spaces in suitable locations of the input string.  This is used to transform a WikiName into a more readable format.
      *
      *  @param s String to be beautified.
      *  @return A beautified string.
      */
-    public static String beautifyString( String s ) {
+    public static String beautifyString( final String s ) {
         return beautifyString( s, " " );
     }
 
     /**
-     *  Adds spaces in suitable locations of the input string.  This is used to transform a WikiName into a more
-     *  readable format.
+     *  Adds spaces in suitable locations of the input string.  This is used to transform a WikiName into a more readable format.
      *
      *  @param s String to be beautified.
      *  @param space Use this string for the space character.
      *  @return A beautified string.
      *  @since 2.1.127
      */
-    public static String beautifyString( String s, String space ) {
+    public static String beautifyString( final String s, final String space ) {
         if( s == null || s.length() == 0 ) {
         	return "";
         }
 
-        StringBuilder result = new StringBuilder();
+        final StringBuilder result = new StringBuilder();
 
-        int cur     = s.charAt( 0 );
+        int cur = s.charAt( 0 );
         int curKind = getCharKind( cur );
 
         int prevKind = LOWER;
-        int nextKind = -1;
-
-        int next = -1;
+        int nextKind;
+        int next;
         int nextPos = 1;
 
         while( curKind != EOI ) {
@@ -596,11 +582,8 @@ public final class TextUtil {
      *  Creates a Properties object based on an array which contains alternatively a key and a value.  It is useful
      *  for generating default mappings. For example:
      *  <pre>
-     *     String[] properties = { "jspwiki.property1", "value1",
-     *                             "jspwiki.property2", "value2 };
-     *
+     *     String[] properties = { "jspwiki.property1", "value1", "jspwiki.property2", "value2 };
      *     Properties props = TextUtil.createPropertes( values );
-     *
      *     System.out.println( props.getProperty("jspwiki.property1") );
      *  </pre>
      *  would output "value1".
@@ -611,12 +594,12 @@ public final class TextUtil {
      *  @throws IllegalArgumentException if the property array is missing a value for a key.
      *  @since 2.2.
      */
-    public static Properties createProperties( String[] values ) throws IllegalArgumentException {
+    public static Properties createProperties( final String[] values ) throws IllegalArgumentException {
         if( values.length % 2 != 0 ) {
         	throw new IllegalArgumentException( "One value is missing.");
         }
 
-        Properties props = new Properties();
+        final Properties props = new Properties();
         for( int i = 0; i < values.length; i += 2 ) {
             props.setProperty( values[i], values[i + 1] );
         }
@@ -631,7 +614,7 @@ public final class TextUtil {
      *  @return int Number of counted sections.
      *  @since 2.1.86.
      */
-    public static int countSections( String pagedata ) {
+    public static int countSections( final String pagedata ) {
         int tags  = 0;
         int start = 0;
 
@@ -640,16 +623,13 @@ public final class TextUtil {
             start += 4; // Skip this "----"
         }
 
-        //
         // The first section does not get the "----"
-        //
         return pagedata.length() > 0 ? tags + 1 : 0;
     }
 
     /**
-     *  Gets the given section (separated with "----") from the page text.
-     *  Note that the first section is always #1.  If a page has no section markers,
-     *  then there is only a single section, #1.
+     *  Gets the given section (separated with "----") from the page text. Note that the first section is always #1.  If a page has no
+     *  section markers, then there is only a single section, #1.
      *
      *  @param pagedata WikiText to parse.
      *  @param section  Which section to get.
@@ -657,7 +637,7 @@ public final class TextUtil {
      *  @throws IllegalArgumentException If the page does not contain this many sections.
      *  @since 2.1.86.
      */
-    public static String getSection( String pagedata, int section ) throws IllegalArgumentException {
+    public static String getSection( final String pagedata, final int section ) throws IllegalArgumentException {
         int tags  = 0;
         int start = 0;
         int previous = 0;
@@ -684,16 +664,15 @@ public final class TextUtil {
     }
 
     /**
-     *  A simple routine which just repeates the arguments.  This is useful for creating something like a line or
-     *  something.
+     *  A simple routine which just repeates the arguments.  This is useful for creating something like a line or something.
      *
      *  @param what String to repeat
      *  @param times How many times to repeat the string.
      *  @return Guess what?
      *  @since 2.1.98.
      */
-    public static String repeatString( String what, int times ) {
-    	StringBuilder sb = new StringBuilder();
+    public static String repeatString( final String what, final int times ) {
+        final StringBuilder sb = new StringBuilder();
         for( int i = 0; i < times; i++ ) {
             sb.append( what );
         }
@@ -708,10 +687,10 @@ public final class TextUtil {
      *  @param s The string to convert
      *  @return the ASCII string
      */
-    public static String native2Ascii( String s ) {
-    	StringBuilder sb = new StringBuilder();
+    public static String native2Ascii( final String s ) {
+        final StringBuilder sb = new StringBuilder();
         for( int i = 0; i < s.length(); i++ ) {
-            char aChar = s.charAt(i);
+            final char aChar = s.charAt(i);
             if( ( aChar < 0x0020 ) || ( aChar > 0x007e ) ) {
                 sb.append( '\\');
                 sb.append( 'u');
@@ -726,11 +705,11 @@ public final class TextUtil {
         return sb.toString();
     }
 
-    private static char toHex( int nibble ) {
+    private static char toHex( final int nibble ) {
         final char[] hexDigit = {
             '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
         };
-        return hexDigit[nibble & 0xF];
+        return hexDigit[ nibble & 0xF ];
     }
 
     /**
@@ -742,7 +721,7 @@ public final class TextUtil {
      * @since 2.3.87
      */
     public static String toHexString( byte[] bytes ) {
-    	StringBuilder sb = new StringBuilder( bytes.length * 2 );
+        final StringBuilder sb = new StringBuilder( bytes.length * 2 );
         for( int i = 0; i < bytes.length; i++ ) {
             sb.append( toHex( bytes[i] >> 4 ) );
             sb.append( toHex( bytes[i] ) );
@@ -766,7 +745,7 @@ public final class TextUtil {
         }
 
         if( s.length() > 1 && s.charAt(0) == '-' ) {
-        	s = s.substring(1);
+        	s = s.substring( 1 );
         }
 
         for( int i = 0; i < s.length(); i++ ) {
@@ -778,9 +757,6 @@ public final class TextUtil {
         return true;
     }
 
-    /** Length of password. @see #generateRandomPassword() */
-    public static final int PASSWORD_LENGTH = 8;
-
     /**
      * Generate a random String suitable for use as a temporary password.
      *
@@ -788,14 +764,10 @@ public final class TextUtil {
      * @since 2.4
      */
     public static String generateRandomPassword() {
-        // Pick from some letters that won't be easily mistaken for each
-        // other. So, for example, omit o O and 0, 1 l and L.
-        String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+@";
-
         String pw = "";
         for( int i = 0; i < PASSWORD_LENGTH; i++ ) {
-            int index = ( int )( RANDOM.nextDouble() * letters.length() );
-            pw += letters.substring( index, index + 1 );
+            int index = ( int )( RANDOM.nextDouble() * PWD_BASE.length() );
+            pw += PWD_BASE.substring( index, index + 1 );
         }
         return pw;
     }


[jspwiki] 19/26: JSPWIKI-120: move remaining textToHtml(..) method from WikiEngine to PageManager

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 6a83a537b2925c72f4c6c657ceb2690ae67d2eb8
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 00:04:50 2020 +0100

    JSPWIKI-120: move remaining textToHtml(..) method from WikiEngine to PageManager
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  | 40 +--------------
 .../main/java/org/apache/wiki/plugin/IfPlugin.java |  2 +-
 .../java/org/apache/wiki/plugin/InsertPage.java    |  2 +-
 .../org/apache/wiki/plugin/PageViewPlugin.java     |  2 +-
 .../wiki/render/DefaultRenderingManager.java       | 33 ++++++++++++
 .../org/apache/wiki/render/RenderingManager.java   |  9 ++++
 .../java/org/apache/wiki/rss/RSSGenerator.java     |  4 +-
 .../java/org/apache/wiki/tags/TranslateTag.java    |  2 +-
 .../apache/wiki/tasks/pages/SaveWikiPageTask.java  | 16 +++---
 .../java/org/apache/wiki/workflow/Workflow.java    | 13 +++--
 .../wiki/plugin/UndefinedPagesPluginTest.java      | 58 ++++++++--------------
 11 files changed, 84 insertions(+), 97 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
index 9f9895b..de440ae 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -19,13 +19,11 @@
 package org.apache.wiki;
 
 import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.time.StopWatch;
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import org.apache.wiki.api.engine.AdminBeanManager;
 import org.apache.wiki.api.engine.FilterManager;
 import org.apache.wiki.api.engine.PluginManager;
-import org.apache.wiki.api.exceptions.FilterException;
 import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.api.exceptions.WikiException;
 import org.apache.wiki.attachment.AttachmentManager;
@@ -932,7 +930,7 @@ public class WikiEngine  {
      */
     public String getHTML( final WikiContext context, final WikiPage page ) {
         final String pagedata = getPageManager().getPureText( page.getName(), page.getVersion() );
-        return textToHTML( context, pagedata );
+        return m_renderingManager.textToHTML( context, pagedata );
     }
 
     /**
@@ -962,42 +960,6 @@ public class WikiEngine  {
     }
 
     /**
-     *  Converts raw page data to HTML.
-     *
-     *  @param pagedata Raw page data to convert to HTML
-     *  @param context  The WikiContext in which the page is to be rendered
-     *  @return Rendered page text
-     */
-    public String textToHTML( final WikiContext context, String pagedata ) {
-        String result = "";
-
-        final boolean runFilters = "true".equals(m_variableManager.getValue(context,VariableManager.VAR_RUNFILTERS,"true"));
-
-        final StopWatch sw = new StopWatch();
-        sw.start();
-        try {
-            if( runFilters ) {
-                pagedata = m_filterManager.doPreTranslateFiltering( context, pagedata );
-            }
-
-            result = m_renderingManager.getHTML( context, pagedata );
-
-            if( runFilters ) {
-                result = m_filterManager.doPostTranslateFiltering( context, result );
-            }
-        } catch( final FilterException e ) {
-            log.error( "page filter threw exception: ", e );
-            // FIXME: Don't yet know what to do
-        }
-        sw.stop();
-        if( log.isDebugEnabled() ) {
-            log.debug( "Page " + context.getRealPage().getName() + " rendered, took " + sw );
-        }
-
-        return result;
-    }
-
-    /**
      * Protected method that signals that the WikiEngine will be shut down by the servlet container. It is called by
      * {@link WikiServlet#destroy()}. When this method is called, it fires a "shutdown" WikiEngineEvent to all registered listeners.
      */
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/IfPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/IfPlugin.java
index 64305d0..a6cb392 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/IfPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/IfPlugin.java
@@ -141,7 +141,7 @@ public class IfPlugin implements WikiPlugin
      */
     public String execute( final WikiContext context, final Map< String, String > params ) throws PluginException {
         return ifInclude( context,params )
-                ? context.getEngine().textToHTML( context, params.get( DefaultPluginManager.PARAM_BODY ) )
+                ? context.getEngine().getRenderingManager().textToHTML( context, params.get( DefaultPluginManager.PARAM_BODY ) )
                 : "" ;
     }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/InsertPage.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/InsertPage.java
index e34e990..d2b9449 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/InsertPage.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/InsertPage.java
@@ -206,7 +206,7 @@ public class InsertPage
                 if( showOnce ) res.append("\" data-once=\""+cookieName );
                 res.append("\" >");
 
-                res.append( engine.textToHTML( includedContext, pageData ) );
+                res.append( engine.getRenderingManager().textToHTML( includedContext, pageData ) );
                 res.append( moreLink );
 
                 res.append("</div>");
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
index 12f312b..1981a44 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
@@ -517,7 +517,7 @@ public class PageViewPlugin extends AbstractReferralPlugin implements WikiPlugin
                         buf.append( footer );
 
                         // let the engine render the list
-                        result = engine.textToHTML( context, buf.toString() );
+                        result = engine.getRenderingManager().textToHTML( context, buf.toString() );
                     }
                 }
             }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 331ad7d..686070c 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -270,6 +270,39 @@ public class DefaultRenderingManager implements RenderingManager {
      *  {@inheritDoc}
      */
     @Override
+    public String textToHTML( final WikiContext context, String pagedata ) {
+        String result = "";
+
+        final boolean runFilters = "true".equals( m_engine.getVariableManager().getValue( context,VariableManager.VAR_RUNFILTERS,"true" ) );
+
+        final StopWatch sw = new StopWatch();
+        sw.start();
+        try {
+            if( runFilters ) {
+                pagedata = m_engine.getFilterManager().doPreTranslateFiltering( context, pagedata );
+            }
+
+            result = getHTML( context, pagedata );
+
+            if( runFilters ) {
+                result = m_engine.getFilterManager().doPostTranslateFiltering( context, result );
+            }
+        } catch( final FilterException e ) {
+            log.error( "page filter threw exception: ", e );
+            // FIXME: Don't yet know what to do
+        }
+        sw.stop();
+        if( log.isDebugEnabled() ) {
+            log.debug( "Page " + context.getRealPage().getName() + " rendered, took " + sw );
+        }
+
+        return result;
+    }
+
+    /**
+     *  {@inheritDoc}
+     */
+    @Override
     public String textToHTML( final WikiContext context,
                               String pagedata,
                               final StringTransmutator localLinkHook,
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index 937fce7..ac2c4b0 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -162,6 +162,15 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     }
 
     /**
+     *  Converts raw page data to HTML.
+     *
+     *  @param pagedata Raw page data to convert to HTML
+     *  @param context  The WikiContext in which the page is to be rendered
+     *  @return Rendered page text
+     */
+    String textToHTML( WikiContext context, String pagedata );
+
+    /**
      *  Helper method for doing the HTML translation.
      *
      *  @param context The WikiContext in which to do the conversion
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java b/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
index 53e5fe2..d4e5687 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
@@ -533,9 +533,7 @@ public class RSSGenerator {
                 if( maxlen > MAX_CHARACTERS ) maxlen = MAX_CHARACTERS;
 
                 if( maxlen > 0 ) {
-                    pageText = m_engine.textToHTML( wikiContext,
-                                                    pageText.substring( firstLine+1,
-                                                                        maxlen ).trim() );
+                    pageText = m_engine.getRenderingManager().textToHTML( wikiContext, pageText.substring( firstLine + 1, maxlen ).trim() );
 
                     if( maxlen == MAX_CHARACTERS ) {
                         pageText += "...";
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/TranslateTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/TranslateTag.java
index f6cbd0c..f4355d2 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/TranslateTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/TranslateTag.java
@@ -52,7 +52,7 @@ public class TranslateTag
 
             if( wikiText != null ) {
                 wikiText = wikiText.trim();
-                final String result = context.getEngine().textToHTML( context, wikiText );
+                final String result = context.getEngine().getRenderingManager().textToHTML( context, wikiText );
                 getPreviousOut().write( result );
             }
         } catch( final Exception e ) {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tasks/pages/SaveWikiPageTask.java b/jspwiki-main/src/main/java/org/apache/wiki/tasks/pages/SaveWikiPageTask.java
index 72ee1b3..e076fb8 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tasks/pages/SaveWikiPageTask.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tasks/pages/SaveWikiPageTask.java
@@ -48,19 +48,19 @@ public class SaveWikiPageTask extends Task {
     @Override
     public Outcome execute() throws WikiException {
         // Retrieve attributes
-        WikiContext context = (WikiContext) getWorkflow().getAttribute( WorkflowManager.WF_WP_SAVE_ATTR_PRESAVE_WIKI_CONTEXT );
-        String proposedText = (String) getWorkflow().getAttribute( WorkflowManager.WF_WP_SAVE_FACT_PROPOSED_TEXT );
+        final WikiContext context = ( WikiContext ) getWorkflow().getAttribute( WorkflowManager.WF_WP_SAVE_ATTR_PRESAVE_WIKI_CONTEXT );
+        final String proposedText = (String) getWorkflow().getAttribute( WorkflowManager.WF_WP_SAVE_FACT_PROPOSED_TEXT );
 
-        WikiEngine engine = context.getEngine();
-        WikiPage page = context.getPage();
+        final WikiEngine engine = context.getEngine();
+        final WikiPage page = context.getPage();
 
         // Let the rest of the engine handle actual saving.
-        engine.getPageManager().putPageText(page, proposedText);
+        engine.getPageManager().putPageText( page, proposedText );
 
         // Refresh the context for post save filtering.
-        engine.getPageManager().getPage(page.getName());
-        engine.textToHTML(context, proposedText);
-        engine.getFilterManager().doPostSaveFiltering(context, proposedText);
+        engine.getPageManager().getPage( page.getName() );
+        engine.getRenderingManager().textToHTML( context, proposedText );
+        engine.getFilterManager().doPostSaveFiltering( context, proposedText );
 
         return Outcome.STEP_COMPLETE;
     }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/workflow/Workflow.java b/jspwiki-main/src/main/java/org/apache/wiki/workflow/Workflow.java
index 80aa960..3a0883b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/workflow/Workflow.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/workflow/Workflow.java
@@ -18,6 +18,11 @@
  */
 package org.apache.wiki.workflow;
 
+import org.apache.wiki.api.exceptions.WikiException;
+import org.apache.wiki.event.WikiEventListener;
+import org.apache.wiki.event.WikiEventManager;
+import org.apache.wiki.event.WorkflowEvent;
+
 import java.io.Serializable;
 import java.security.Principal;
 import java.util.ArrayList;
@@ -28,11 +33,6 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 
-import org.apache.wiki.api.exceptions.WikiException;
-import org.apache.wiki.event.WikiEventListener;
-import org.apache.wiki.event.WikiEventManager;
-import org.apache.wiki.event.WorkflowEvent;
-
 /**
  * <p>
  * Sequence of {@link Step} objects linked together. Workflows are always
@@ -382,8 +382,7 @@ public class Workflow implements Serializable
      * Retrieves a named Object associated with this Workflow. If the Workflow
      * has completed or aborted, this method always returns <code>null</code>.
      *
-     * @param attr
-     *            the name of the attribute
+     * @param attr the name of the attribute
      * @return the value
      */
     public final synchronized Object getAttribute( String attr )
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/UndefinedPagesPluginTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/UndefinedPagesPluginTest.java
index c0a7dad..58aab45 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/UndefinedPagesPluginTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/UndefinedPagesPluginTest.java
@@ -19,8 +19,7 @@
 
 package org.apache.wiki.plugin;
 
-import java.util.Properties;
-
+import net.sf.ehcache.CacheManager;
 import org.apache.wiki.TestEngine;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiPage;
@@ -31,19 +30,18 @@ import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-import net.sf.ehcache.CacheManager;
+import java.util.Properties;
+
+
+public class UndefinedPagesPluginTest {
 
-public class UndefinedPagesPluginTest
-{
     Properties props = TestEngine.getTestProperties();
     TestEngine testEngine;
     WikiContext context;
     PluginManager manager;
 
     @BeforeEach
-    public void setUp()
-        throws Exception
-    {
+    public void setUp() throws Exception {
         CacheManager.getInstance().removeAllCaches();
         testEngine = new TestEngine(props);
 
@@ -55,16 +53,14 @@ public class UndefinedPagesPluginTest
     }
 
     @AfterEach
-    public void tearDown()
-    {
+    public void tearDown() {
         testEngine.deleteTestPage( "TestPage" );
         testEngine.deleteTestPage( "Foobar" );
         TestEngine.emptyWorkDir();
     }
 
-    private String wikitize( String s )
-    {
-        return testEngine.textToHTML( context, s );
+    private String wikitize( final String s ) {
+        return testEngine.getRenderingManager().textToHTML( context, s );
     }
 
     /**
@@ -73,39 +69,29 @@ public class UndefinedPagesPluginTest
      *  be listed as non-existent.
      */
     @Test
-    public void testSimpleUndefined()
-        throws Exception
-    {
-        WikiContext context2 = new WikiContext( testEngine, new WikiPage(testEngine, "Foobar") );
-
-        String res = manager.execute( context2,
-                                      "{INSERT org.apache.wiki.plugin.UndefinedPagesPlugin");
+    public void testSimpleUndefined() throws Exception {
+        final WikiContext context2 = new WikiContext( testEngine, new WikiPage( testEngine, "Foobar" ) );
+        final String res = manager.execute( context2,"{INSERT org.apache.wiki.plugin.UndefinedPagesPlugin" );
+        final String exp = "[Foobar 2]\\\\";
 
-        String exp = "[Foobar 2]\\\\";
-
-        Assertions.assertEquals( wikitize(exp), res );
+        Assertions.assertEquals( wikitize( exp ), res );
     }
 
     @Test
-    public void testCount() throws Exception
-    {
-        String result = null;
-        result = manager.execute(context, "{UndefinedPagesPlugin show=count}");
-        Assertions.assertEquals("1", result);
+    public void testCount() throws Exception {
+        final String result = manager.execute( context, "{UndefinedPagesPlugin show=count}");
+        Assertions.assertEquals("1", result );
 
         // test if the proper exception is thrown:
-        String expectedExceptionString = "parameter showLastModified is not valid for the UndefinedPagesPlugin";
+        final String expectedExceptionString = "parameter showLastModified is not valid for the UndefinedPagesPlugin";
         String exceptionString = null;
-        try
-        {
-            result = manager.execute(context, "{UndefinedPagesPlugin,show=count,showLastModified=true}");
-        }
-        catch (PluginException pe)
-        {
+        try {
+            manager.execute( context, "{UndefinedPagesPlugin,show=count,showLastModified=true}" );
+        } catch( final PluginException pe ) {
             exceptionString = pe.getMessage();
         }
 
-        Assertions.assertEquals(expectedExceptionString, exceptionString);
+        Assertions.assertEquals( expectedExceptionString, exceptionString );
     }
 
 }


[jspwiki] 10/26: Update ASF parent pom + plugin definitions to support, as far as possible, reproducible builds

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 5fad1e7fac27e477d7fb4ba6929e956b7e72a2a2
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 21:19:55 2020 +0100

    Update ASF parent pom + plugin definitions to support, as far as possible, reproducible builds
---
 pom.xml | 31 +++++++++----------------------
 1 file changed, 9 insertions(+), 22 deletions(-)

diff --git a/pom.xml b/pom.xml
index d28be99..48f20fd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -22,7 +22,7 @@
   <parent>
     <groupId>org.apache</groupId>
     <artifactId>apache</artifactId>
-    <version>21</version>
+    <version>22</version>
   </parent>
 
   <groupId>org.apache.jspwiki</groupId>
@@ -39,6 +39,7 @@
   <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+    <project.build.outputTimestamp>2019-01-13T19:30:00Z</project.build.outputTimestamp> <!-- will be changed by release plugin during releases -->
     <jdk.version>1.8</jdk.version>
     <jdk.javadoc.doclet.version>1.1.4</jdk.javadoc.doclet.version>
     <maven.version>3.5</maven.version>
@@ -78,7 +79,7 @@
     <xmlrpc.version>2.0.1</xmlrpc.version>
 
     <plugin.antrun.version>1.8</plugin.antrun.version>
-    <plugin.assembly.version>3.1.1</plugin.assembly.version>
+    <plugin.assembly.version>3.2.0</plugin.assembly.version>
     <plugin.clean.version>3.1.0</plugin.clean.version>
     <plugin.compiler.version>3.8.1</plugin.compiler.version>
     <plugin.dependency.version>3.1.1</plugin.dependency.version>
@@ -86,23 +87,23 @@
     <plugin.enforcer.version>1.4.1</plugin.enforcer.version>
     <plugin.idea.version>2.2.1</plugin.idea.version>
     <plugin.install.version>2.5.2</plugin.install.version>
-    <plugin.jar.version>3.1.2</plugin.jar.version>
+    <plugin.jar.version>3.2.0</plugin.jar.version>
     <plugin.javadoc.version>3.1.1</plugin.javadoc.version>
     <plugin.jxr.version>3.0.0</plugin.jxr.version>
     <plugin.project-info-reports.version>3.0.0</plugin.project-info-reports.version>
-    <plugin.release.version>2.5.3</plugin.release.version>
+    <plugin.release.version>3.0.0-M1</plugin.release.version>
     <plugin.resources.version>3.1.0</plugin.resources.version>
-    <plugin.source.version>3.1.0</plugin.source.version>
-    <plugin.surefire.version>3.0.0-M3</plugin.surefire.version>
+    <plugin.source.version>3.2.1</plugin.source.version>
+    <plugin.surefire.version>3.0.0-M4</plugin.surefire.version>
     <plugin.war.version>3.2.3</plugin.war.version>
     <plugin.inmemdb.version>1.4.3</plugin.inmemdb.version>
     <plugin.jspc.version>3.1.0</plugin.jspc.version>
     <plugin.checksum.version>1.8</plugin.checksum.version>
     <plugin.jslint.version>1.0.1</plugin.jslint.version>
-    <plugin.cargo.version>1.7.6</plugin.cargo.version>
+    <plugin.cargo.version>1.7.9</plugin.cargo.version>
     <plugin.clirr.version>2.8</plugin.clirr.version>
     <plugin.cobertura.version>2.7</plugin.cobertura.version>
-    <plugin.sonar.version>3.6.0.1398</plugin.sonar.version>
+    <plugin.sonar.version>3.7.0.1746</plugin.sonar.version>
     <plugin.sonar-report.version>0.1</plugin.sonar-report.version>
     <plugin.eclipse-lifecycle-mapping.version>1.0.0</plugin.eclipse-lifecycle-mapping.version>
     <maven.compiler.source>${jdk.version}</maven.compiler.source> <!-- override values from parent pom -->
@@ -532,20 +533,6 @@
         <plugin>
           <artifactId>maven-release-plugin</artifactId>
           <version>${plugin.release.version}</version>
-          <dependencies>
-            <dependency>
-              <groupId>org.apache.maven.scm</groupId>
-              <artifactId>maven-scm-api</artifactId>
-              <version>1.9.5</version>
-            </dependency>
-            <dependency>
-              <groupId>org.apache.maven.scm</groupId>
-              <artifactId>maven-scm-providers-standard</artifactId>
-              <version>1.9.5</version>
-              <type>pom</type>
-              <scope>runtime</scope>
-            </dependency>
-          </dependencies>
         </plugin>
 
         <plugin>


[jspwiki] 26/26: 2.11.0-M7-git-05

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit ffee109c1ad599142ae5fc34319f71822cd057b2
Author: juanpablo <ju...@apache.org>
AuthorDate: Fri Jan 17 00:06:33 2020 +0100

    2.11.0-M7-git-05
---
 ChangeLog.md                                            | 16 ++++++++++++++++
 jspwiki-main/src/main/java/org/apache/wiki/Release.java |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/ChangeLog.md b/ChangeLog.md
index aced183..e5f9366 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -17,6 +17,22 @@ specific language governing permissions and limitations
 under the License.
 -->
 
+**2020-01-16  Juan Pablo Santos (juanpablo AT apache DOT org)**
+
+* _2.11.0-M7-git-05_
+
+* [JSPWIKI-120](https://issues.apache.org/jira/browse/JSPWIKI-120): Separate rendering engine from core
+    * `RenderingManager` renamed as `org.apache.wiki.render.DefaultRenderingManager`, with new 
+       `org.apache.wiki.render.RenderingManager` extracted as interface of the latter
+    * moved `textToHtml(..)` methods from `WikiEngine` to `RenderingManager`
+    * moved `getHTML(..)` methods from `WikiEngine` to `RenderingManager`
+    * moved `beautifyTitle( String )` and `beautifyTitleNoBreak` methods from `WikiEngine` to `RenderingManager`__
+* `VAR_EXECUTE_PLUGINS` and `WYSIWYG_EDITOR_MODE` constants from `RenderingManager` moved to `WikiContext` (the latter 
+as `VAR_WYSIWYG_EDITOR_MODE`)
+* constant `PROP_RUNFILTERS` from `WikiEngine` moved to `VariableManager` as `VAR_RUNFILTERS`.
+* constants `PUNCTUATION_CHARS_ALLOWED` and `LEGACY_CHARS_ALLOWED` from `MarkupParser` moved to `TextUtil`.
+* Update ASF parent pom + plugin definitions to support, as far as possible, [reproducible builds](https://maven.apache.org/guides/mini/guide-reproducible-builds.html)
+
 **2020-01-09  Juan Pablo Santos (juanpablo AT apache DOT org)**
 
 * _2.11.0-M7-git-04_
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/Release.java b/jspwiki-main/src/main/java/org/apache/wiki/Release.java
index 6520655..c06bb25 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/Release.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/Release.java
@@ -69,7 +69,7 @@ public final class Release {
      *  <p>
      *  If the build identifier is empty, it is not added.
      */
-    public static final String     BUILD         = "git-04";
+    public static final String     BUILD         = "git-05";
 
     /**
      *  This is the generic version string you should use when printing out the version.  It is of


[jspwiki] 06/26: format code

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit a2da4a8caa30649b6f9ff84d7007f025daa15d14
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Jan 12 22:17:08 2020 +0100

    format code
---
 .../apache/wiki/parser/JSPWikiMarkupParser.java    | 47 +++++++++-------------
 .../main/java/org/apache/wiki/util/XmlUtil.java    | 38 ++++++++---------
 .../java/org/apache/wiki/util/XmlUtilTest.java     |  2 +-
 3 files changed, 38 insertions(+), 49 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
index fe14f59..7dad359 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
@@ -861,24 +861,19 @@ public class JSPWikiMarkupParser extends MarkupParser {
         return hd.m_titleAnchor;
     }
 
-    private String makeSectionTitle( String title )
-    {
+    private String makeSectionTitle( String title ) {
         title = title.trim();
-        String outTitle;
-
-        try
-        {
-            JSPWikiMarkupParser dtr = getCleanTranslator();
-            dtr.setInputReader( new StringReader(title) );
+        final String outTitle;
 
-            CleanTextRenderer ctt = new CleanTextRenderer(m_context, dtr.parse());
+        try {
+            final JSPWikiMarkupParser dtr = getCleanTranslator();
+            dtr.setInputReader( new StringReader( title ) );
 
+            final CleanTextRenderer ctt = new CleanTextRenderer( m_context, dtr.parse() );
             outTitle = ctt.getString();
-        }
-        catch( IOException e )
-        {
-            log.fatal("CleanTranslator not working", e);
-            throw new InternalWikiException("CleanTranslator not working as expected, when cleaning title"+ e.getMessage() , e);
+        } catch( final IOException e ) {
+            log.fatal("CleanTranslator not working", e );
+            throw new InternalWikiException( "CleanTranslator not working as expected, when cleaning title"+ e.getMessage() , e );
         }
 
         return outTitle;
@@ -892,35 +887,29 @@ public class JSPWikiMarkupParser extends MarkupParser {
      *  @param hd a List to which heading should be added
      *  @return An Element containing the heading
      */
-    public Element makeHeading( int level, String title, Heading hd )
-    {
-        Element el = null;
-
-        String pageName = m_context.getPage().getName();
-
-        String outTitle = makeSectionTitle( title );
-
+    public Element makeHeading( final int level, final String title, final Heading hd ) {
+        final Element el;
+        final String pageName = m_context.getPage().getName();
+        final String outTitle = makeSectionTitle( title );
         hd.m_level = level;
 
-        switch( level )
-        {
+        switch( level ) {
           case Heading.HEADING_SMALL:
-            el = new Element("h4").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
+            el = new Element( "h4" ).setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ) );
             break;
 
           case Heading.HEADING_MEDIUM:
-            el = new Element("h3").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
+            el = new Element( "h3" ).setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ) );
             break;
 
           case Heading.HEADING_LARGE:
-            el = new Element("h2").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ));
+            el = new Element( "h2" ).setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd ) );
             break;
 
           default:
-            throw new InternalWikiException("Illegal heading type "+level);
+            throw new InternalWikiException( "Illegal heading type " + level );
         }
 
-
         return el;
     }
 
diff --git a/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java b/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
index 3bb76b5..2412b2c 100644
--- a/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
+++ b/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
@@ -57,28 +57,28 @@ public final class XmlUtil  {
 	 * empty list is returned.
 	 * 
 	 * @param xml file to parse; matches all resources from classpath, filters repeated items.
-	 * @param requestedNodes requestd nodes on the xml file
+	 * @param requestedNodes requested nodes on the xml file
 	 * @return the requested nodes of the XML file.
 	 */
-	public static List<Element> parse( String xml, String requestedNodes )
+	public static List<Element> parse( final String xml, final String requestedNodes )
 	{
 		if( StringUtils.isNotEmpty( xml ) && StringUtils.isNotEmpty( requestedNodes ) ) {
-			Set<Element> readed = new HashSet<Element>();
-			SAXBuilder builder = new SAXBuilder();
+			final Set<Element> readed = new HashSet<>();
+			final SAXBuilder builder = new SAXBuilder();
 			try {
-				Enumeration< URL > resources = XmlUtil.class.getClassLoader().getResources( xml );
+				final Enumeration< URL > resources = XmlUtil.class.getClassLoader().getResources( xml );
 				while( resources.hasMoreElements() ) {
-	                URL resource = resources.nextElement();
+					final URL resource = resources.nextElement();
 	                log.debug( "reading " + resource.toString() );
-	                Document doc = builder.build( resource );
-	                XPathFactory xpfac = XPathFactory.instance();
-	                XPathExpression<Element> xp = xpfac.compile( requestedNodes, Filters.element() );
+					final Document doc = builder.build( resource );
+					final XPathFactory xpfac = XPathFactory.instance();
+					final XPathExpression<Element> xp = xpfac.compile( requestedNodes, Filters.element() );
 	                readed.addAll( xp.evaluate( doc ) ); // filter out repeated items
 	            }
-				return new ArrayList<Element>( readed );
-			} catch ( IOException ioe ) {
+				return new ArrayList<>( readed );
+			} catch( final IOException ioe ) {
 				log.error( "Couldn't load all " + xml + " resources", ioe );
-			} catch ( JDOMException jdome ) {
+			} catch( final JDOMException jdome ) {
 				log.error( "error parsing " + xml + " resources", jdome );
 			}
 		}
@@ -93,17 +93,17 @@ public final class XmlUtil  {
 	 * @param requestedNodes requestd nodes on the xml stream.
 	 * @return the requested nodes of the XML stream.
 	 */
-	public static List< Element > parse( InputStream xmlStream, String requestedNodes ) {
+	public static List< Element > parse( final InputStream xmlStream, final String requestedNodes ) {
 		if( xmlStream != null && StringUtils.isNotEmpty( requestedNodes ) ) {
-			SAXBuilder builder = new SAXBuilder();
+			final SAXBuilder builder = new SAXBuilder();
 			try {
-                Document doc = builder.build( xmlStream );
-                XPathFactory xpfac = XPathFactory.instance();
-                XPathExpression< Element > xp = xpfac.compile( requestedNodes,Filters.element() );
+				final Document doc = builder.build( xmlStream );
+				final XPathFactory xpfac = XPathFactory.instance();
+				final XPathExpression< Element > xp = xpfac.compile( requestedNodes,Filters.element() );
 				return xp.evaluate( doc );
-			} catch ( IOException ioe ) {
+			} catch( final IOException ioe ) {
 				log.error( "Couldn't load all " + xmlStream + " resources", ioe );
-			} catch ( JDOMException jdome ) {
+			} catch( final JDOMException jdome ) {
 				log.error( "error parsing " + xmlStream + " resources", jdome );
 			}
 		}		
diff --git a/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java b/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
index 5d19f6e..cefc0e9 100644
--- a/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
+++ b/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
@@ -59,7 +59,7 @@ public class XmlUtilTest {
 
     @Test
     public void testParseFromStream() throws IOException {
-        try( InputStream is = new FileInputStream( new File ("./src/test/resources/ini/jspwiki_module.xml" ) ) ) {
+        try( final InputStream is = new FileInputStream( new File ("./src/test/resources/ini/jspwiki_module.xml" ) ) ) {
             List< Element > elements = XmlUtil.parse( is, "/modules/plugin" );
             Assertions.assertEquals( 2, elements.size() );
 


[jspwiki] 21/26: JSPWIKI-120: moved getHTML methods from WikiEngine to PageManager

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit cc800371717f37236f5a54a8909f030f9c932924
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 00:46:47 2020 +0100

    JSPWIKI-120: moved getHTML methods from WikiEngine to PageManager
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  |  46 +---
 .../apache/wiki/auth/acl/DefaultAclManager.java    |   2 +-
 .../java/org/apache/wiki/plugin/WeblogPlugin.java  | 274 +++++++--------------
 .../wiki/render/DefaultRenderingManager.java       |  25 ++
 .../org/apache/wiki/render/RenderingManager.java   |  31 +++
 .../java/org/apache/wiki/rss/RSSGenerator.java     |   2 +-
 .../java/org/apache/wiki/tags/InsertPageTag.java   |   2 +-
 .../org/apache/wiki/xmlrpc/MetaWeblogHandler.java  |  86 +++----
 .../java/org/apache/wiki/xmlrpc/RPCHandler.java    |   4 +-
 .../org/apache/wiki/xmlrpc/RPCHandlerUTF8.java     |   4 +-
 .../src/test/java/org/apache/wiki/TestEngine.java  |   2 +-
 .../test/java/org/apache/wiki/WikiEngineTest.java  |  13 +-
 .../apache/wiki/pages/DefaultPageManagerTest.java  |   4 +-
 .../wiki/plugin/DefaultPluginManagerTest.java      |   2 +-
 .../java/org/apache/wiki/plugin/GroupsTest.java    |   2 +-
 .../java/org/apache/wiki/plugin/IfPluginTest.java  |  14 +-
 .../org/apache/wiki/plugin/InsertPageTest.java     |  42 ++--
 .../org/apache/wiki/plugin/PageViewPluginTest.java |  36 +--
 .../apache/wiki/render/RenderingManagerTest.java   |  10 +
 .../apache/wiki/stress/MassiveRepositoryTest.java  |   2 +-
 20 files changed, 245 insertions(+), 358 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
index de440ae..9b522e4 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -41,7 +41,6 @@ import org.apache.wiki.event.WikiPageEvent;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.pages.PageManager;
 import org.apache.wiki.parser.MarkupParser;
-import org.apache.wiki.providers.WikiPageProvider;
 import org.apache.wiki.references.ReferenceManager;
 import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.rss.RSSGenerator;
@@ -241,9 +240,6 @@ public class WikiEngine  {
         is not running inside a servlet container (i.e. when testing). */
     private ServletContext   m_servletContext = null;
 
-    /** If true, all titles will be cleaned. */
-    private boolean          m_beautifyTitle = false;
-
     /** Stores the template path.  This is relative to "templates". */
     private String           m_templateDir;
 
@@ -618,7 +614,7 @@ public class WikiEngine  {
                     final URL url = m_servletContext.getResource( viewTemplate );
                     exists = url != null && StringUtils.isNotEmpty( url.getFile() );
                 } catch( final MalformedURLException e ) {
-                    exists = false;
+                    log.warn( "template not found with viewTemplate " + viewTemplate );
                 }
             }
             if( !exists ) {
@@ -851,7 +847,7 @@ public class WikiEngine  {
      */
     // FIXME: Should use servlet context as a default instead of a constant.
     public String getApplicationName() {
-        String appName = TextUtil.getStringProperty( m_properties, PROP_APPNAME, Release.APPNAME );
+        final String appName = TextUtil.getStringProperty( m_properties, PROP_APPNAME, Release.APPNAME );
         return MarkupParser.cleanLink( appName );
     }
 
@@ -922,44 +918,6 @@ public class WikiEngine  {
     }
 
     /**
-     *  Returns the converted HTML of the page using a different context than the default context.
-     *
-     *  @param  context A WikiContext in which you wish to render this page in.
-     *  @param  page WikiPage reference.
-     *  @return HTML-rendered version of the page.
-     */
-    public String getHTML( final WikiContext context, final WikiPage page ) {
-        final String pagedata = getPageManager().getPureText( page.getName(), page.getVersion() );
-        return m_renderingManager.textToHTML( context, pagedata );
-    }
-
-    /**
-     *  Returns the converted HTML of the page.
-     *
-     *  @param page WikiName of the page to convert.
-     *  @return HTML-rendered version of the page.
-     */
-    public String getHTML( final String page )
-    {
-        return getHTML( page, WikiPageProvider.LATEST_VERSION );
-    }
-
-    /**
-     *  Returns the converted HTML of the page's specific version. The version must be a positive integer, otherwise the current
-     *  version is returned.
-     *
-     *  @param pagename WikiName of the page to convert.
-     *  @param version Version number to fetch
-     *  @return HTML-rendered page text.
-     */
-    public String getHTML( final String pagename, final int version ) {
-        final WikiPage page = getPageManager().getPage( pagename, version );
-        final WikiContext context = new WikiContext( this, page );
-        context.setRequestContext( WikiContext.NONE );
-        return getHTML( context, page );
-    }
-
-    /**
      * Protected method that signals that the WikiEngine will be shut down by the servlet container. It is called by
      * {@link WikiServlet#destroy()}. When this method is called, it fires a "shutdown" WikiEngineEvent to all registered listeners.
      */
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
index d5ff97f..7b0ca22 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
@@ -164,7 +164,7 @@ public class DefaultAclManager implements AclManager {
                 //  Or, try parsing the page
                 final WikiContext ctx = new WikiContext( m_engine, page );
                 ctx.setVariable( WikiContext.VAR_EXECUTE_PLUGINS, Boolean.FALSE );
-                m_engine.getHTML(ctx, page);
+                m_engine.getRenderingManager().getHTML(ctx, page);
 
                 if (page.getAcl() == null) {
                     page.setAcl( new AclImpl() );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
index b62b58b..418aa9e 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
@@ -41,7 +41,6 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Calendar;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.Date;
 import java.util.Iterator;
@@ -82,10 +81,9 @@ import java.util.regex.Pattern;
 // FIXME: Add "entries" param as an alternative to "days".
 // FIXME: Entries arrive in wrong order.
 
-public class WeblogPlugin
-    implements WikiPlugin, ParserStagePlugin
-{
-    private static Logger     log = Logger.getLogger(WeblogPlugin.class);
+public class WeblogPlugin implements WikiPlugin, ParserStagePlugin {
+
+    private static final Logger     log = Logger.getLogger(WeblogPlugin.class);
     private static final Pattern HEADINGPATTERN;
 
     /** How many days are considered by default.  Default value is {@value} */
@@ -115,8 +113,7 @@ public class WeblogPlugin
      */
     public static final String  ATTR_ISWEBLOG      = "weblogplugin.isweblog";
 
-    static
-    {
+    static {
         // This is a pretty ugly, brute-force regex. But it will do for now...
         HEADINGPATTERN = Pattern.compile("(<h[1-4][^>]*>)(.*)(</h[1-4]>)", Pattern.CASE_INSENSITIVE);
     }
@@ -129,10 +126,7 @@ public class WeblogPlugin
      *  @param entryNum The entry number.
      *  @return A formatted page name.
      */
-    public static String makeEntryPage( String pageName,
-                                        String date,
-                                        String entryNum )
-    {
+    public static String makeEntryPage( final String pageName, final String date, final String entryNum ) {
         return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date+"_"+entryNum;
     }
 
@@ -142,7 +136,7 @@ public class WeblogPlugin
      *  @param pageName The name of the blog.
      *  @return A formatted name.
      */
-    public static String makeEntryPage( String pageName )
+    public static String makeEntryPage( final String pageName )
     {
         return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName);
     }
@@ -154,96 +148,76 @@ public class WeblogPlugin
      *  @param date The date.
      *  @return A base name for the blog entries.
      */
-    public static String makeEntryPage( String pageName, String date )
-    {
+    public static String makeEntryPage( final String pageName, final String date ) {
         return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date;
     }
 
     /**
      *  {@inheritDoc}
      */
-    public String execute( WikiContext context, Map<String, String> params )
-        throws PluginException
-    {
-        Calendar   startTime;
-        Calendar   stopTime;
+    public String execute( final WikiContext context, final Map< String, String > params ) throws PluginException {
+        final Calendar   startTime;
+        final Calendar   stopTime;
         int        numDays = DEFAULT_DAYS;
-        WikiEngine engine = context.getEngine();
-        AuthorizationManager mgr = engine.getAuthorizationManager();
+        final WikiEngine engine = context.getEngine();
+        final AuthorizationManager mgr = engine.getAuthorizationManager();
 
         //
         //  Parse parameters.
         //
-        String  days;
-        DateFormat entryFormat;
-        String  startDay = null;
+        String days;
+        final DateFormat entryFormat;
+        String startDay;
         boolean hasComments = false;
-        int     maxEntries;
-        String  weblogName;
+        int maxEntries;
+        String weblogName;
 
-        if( (weblogName = params.get(PARAM_PAGE)) == null )
-        {
+        if( (weblogName = params.get(PARAM_PAGE)) == null ) {
             weblogName = context.getPage().getName();
         }
 
-        if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null )
-        {
+        if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null ) {
             days = params.get( PARAM_DAYS );
         }
 
-        if( ( params.get(PARAM_ENTRYFORMAT)) == null )
-        {
+        if( ( params.get(PARAM_ENTRYFORMAT)) == null ) {
             entryFormat = Preferences.getDateFormat( context, TimeFormat.DATETIME );
-        }
-        else
-        {
+        } else {
             entryFormat = new SimpleDateFormat( params.get(PARAM_ENTRYFORMAT) );
         }
 
-        if( days != null )
-        {
-            if( days.equalsIgnoreCase("all") )
-            {
+        if( days != null ) {
+            if( days.equalsIgnoreCase("all") ) {
                 numDays = Integer.MAX_VALUE;
-            }
-            else
-            {
+            } else {
                 numDays = TextUtil.parseIntParameter( days, DEFAULT_DAYS );
             }
         }
 
 
-        if( (startDay = params.get(PARAM_STARTDATE)) == null )
-        {
+        if( (startDay = params.get(PARAM_STARTDATE)) == null ) {
             startDay = context.getHttpParameter( "weblog."+PARAM_STARTDATE );
         }
 
-        if( TextUtil.isPositive( params.get(PARAM_ALLOWCOMMENTS) ) )
-        {
+        if( TextUtil.isPositive( params.get(PARAM_ALLOWCOMMENTS) ) ) {
             hasComments = true;
         }
 
-        maxEntries = TextUtil.parseIntParameter( params.get(PARAM_MAXENTRIES),
-                                                 Integer.MAX_VALUE );
+        maxEntries = TextUtil.parseIntParameter( params.get(PARAM_MAXENTRIES), Integer.MAX_VALUE );
 
         //
         //  Determine the date range which to include.
         //
-
         startTime = Calendar.getInstance();
         stopTime  = Calendar.getInstance();
 
-        if( startDay != null )
-        {
-            SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT );
-            try
-            {
-                Date d = fmt.parse( startDay );
+        if( startDay != null ) {
+            final SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT );
+            try {
+                final Date d = fmt.parse( startDay );
                 startTime.setTime( d );
                 stopTime.setTime( d );
-            }
-            catch( ParseException e )
-            {
+            } catch( final ParseException e ) {
                 return "Illegal time format: "+startDay;
             }
         }
@@ -251,12 +225,10 @@ public class WeblogPlugin
         //
         //  Mark this to be a weblog
         //
-
         context.getPage().setAttribute(ATTR_ISWEBLOG, "true");
 
         //
-        //  We make a wild guess here that nobody can do millisecond
-        //  accuracy here.
+        //  We make a wild guess here that nobody can do millisecond accuracy here.
         //
         startTime.add( Calendar.DAY_OF_MONTH, -numDays );
         startTime.set( Calendar.HOUR, 0 );
@@ -266,38 +238,21 @@ public class WeblogPlugin
         stopTime.set( Calendar.MINUTE, 59 );
         stopTime.set( Calendar.SECOND, 59 );
 
-        StringBuilder sb = new StringBuilder();
-
-        try
-        {
-            List<WikiPage> blogEntries = findBlogEntries( engine,
-                                                          weblogName,
-                                                          startTime.getTime(),
-                                                          stopTime.getTime() );
-
-            Collections.sort( blogEntries, new PageDateComparator() );
+        final StringBuilder sb = new StringBuilder();
+        final List<WikiPage> blogEntries = findBlogEntries( engine, weblogName, startTime.getTime(), stopTime.getTime() );
+        blogEntries.sort( new PageDateComparator() );
 
-            sb.append("<div class=\"weblog\">\n");
+        sb.append("<div class=\"weblog\">\n");
 
-            for( Iterator< WikiPage > i = blogEntries.iterator(); i.hasNext() && maxEntries-- > 0 ; )
-            {
-                WikiPage p = i.next();
-
-                if( mgr.checkPermission( context.getWikiSession(),
-                                         new PagePermission(p, PagePermission.VIEW_ACTION) ) )
-                {
-                    addEntryHTML(context, entryFormat, hasComments, sb, p, params);
-                }
+        for( final Iterator< WikiPage > i = blogEntries.iterator(); i.hasNext() && maxEntries-- > 0 ; ) {
+            final WikiPage p = i.next();
+            if( mgr.checkPermission( context.getWikiSession(), new PagePermission(p, PagePermission.VIEW_ACTION) ) ) {
+                addEntryHTML( context, entryFormat, hasComments, sb, p, params );
             }
-
-            sb.append("</div>\n");
-        }
-        catch( ProviderException e )
-        {
-            log.error( "Could not locate blog entries", e );
-            throw new PluginException( "Could not locate blog entries: "+e.getMessage() );
         }
 
+        sb.append("</div>\n");
+
         return sb.toString();
     }
 
@@ -311,12 +266,10 @@ public class WeblogPlugin
      *  @param entry
      *  @throws ProviderException
      */
-    private void addEntryHTML(WikiContext context, DateFormat entryFormat, boolean hasComments,
-            StringBuilder buffer, WikiPage entry, Map<String, String> params)
-            throws ProviderException
-    {
-        WikiEngine engine = context.getEngine();
-        ResourceBundle rb = Preferences.getBundle(context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
+    private void addEntryHTML( final WikiContext context, final DateFormat entryFormat, final boolean hasComments,
+                               final StringBuilder buffer, final WikiPage entry, final Map< String, String > params) {
+        final WikiEngine engine = context.getEngine();
+        final ResourceBundle rb = Preferences.getBundle(context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
 
         buffer.append("<div class=\"weblogentry\">\n");
 
@@ -325,40 +278,33 @@ public class WeblogPlugin
         //
         buffer.append("<div class=\"weblogentryheading\">\n");
 
-        Date entryDate = entry.getLastModified();
-        buffer.append( entryFormat.format(entryDate) );
-
+        final Date entryDate = entry.getLastModified();
+        buffer.append( entryFormat != null ? entryFormat.format(entryDate) : entryDate );
         buffer.append("</div>\n");
 
         //
-        //  Append the text of the latest version.  Reset the
-        //  context to that page.
+        //  Append the text of the latest version.  Reset the context to that page.
         //
-
-        WikiContext entryCtx = (WikiContext) context.clone();
+        final WikiContext entryCtx = (WikiContext) context.clone();
         entryCtx.setPage( entry );
 
-        String html = engine.getHTML( entryCtx, engine.getPageManager().getPage( entry.getName() ) );
+        String html = engine.getRenderingManager().getHTML( entryCtx, engine.getPageManager().getPage( entry.getName() ) );
 
         // Extract the first h1/h2/h3 as title, and replace with null
         buffer.append("<div class=\"weblogentrytitle\">\n");
-        Matcher matcher = HEADINGPATTERN.matcher( html );
-        if ( matcher.find() )
-        {
-            String title = matcher.group(2);
+        final Matcher matcher = HEADINGPATTERN.matcher( html );
+        if ( matcher.find() ) {
+            final String title = matcher.group(2);
             html = matcher.replaceFirst("");
             buffer.append( title );
-        }
-        else
-        {
+        } else {
             buffer.append( entry.getName() );
         }
         buffer.append("</div>\n");
-
         buffer.append("<div class=\"weblogentrybody\">\n");
-        int preview = TextUtil.parseIntParameter(params.get(PARAM_PREVIEW), 0);
-        if (preview > 0)
-        {
+
+        final int preview = TextUtil.parseIntParameter(params.get(PARAM_PREVIEW), 0);
+        if (preview > 0) {
             //
             // We start with the first 'preview' number of characters from the text,
             // and then add characters to it until we get to a linebreak or a period.
@@ -367,15 +313,11 @@ public class WeblogPlugin
             //
             boolean hasBeenCutOff = false;
             int cutoff = Math.min(preview, html.length());
-            while (cutoff < html.length())
-            {
-                if (html.charAt(cutoff) == '\r' || html.charAt(cutoff) == '\n')
-                {
+            while (cutoff < html.length()) {
+                if (html.charAt(cutoff) == '\r' || html.charAt(cutoff) == '\n') {
                     hasBeenCutOff = true;
                     break;
-                }
-                else if (html.charAt(cutoff) == '.')
-                {
+                } else if (html.charAt(cutoff) == '.') {
                     // we do want the period
                     cutoff++;
                     hasBeenCutOff = true;
@@ -384,13 +326,10 @@ public class WeblogPlugin
                 cutoff++;
             }
             buffer.append(html.substring(0, cutoff));
-            if (hasBeenCutOff)
-            {
+            if (hasBeenCutOff) {
                 buffer.append(" <a href=\""+entryCtx.getURL(WikiContext.VIEW, entry.getName())+"\">"+rb.getString("weblogentryplugin.more")+"</a>\n");
             }
-        }
-        else
-        {
+        } else {
             buffer.append(html);
         }
         buffer.append("</div>\n");
@@ -402,44 +341,32 @@ public class WeblogPlugin
 
         String author = entry.getAuthor();
 
-        if( author != null )
-        {
-            if( engine.getPageManager().wikiPageExists(author) )
-            {
+        if( author != null ) {
+            if( engine.getPageManager().wikiPageExists(author) ) {
                 author = "<a href=\""+entryCtx.getURL( WikiContext.VIEW, author )+"\">"+engine.getRenderingManager().beautifyTitle(author)+"</a>";
             }
-        }
-        else
-        {
+        } else {
             author = "AnonymousCoward";
         }
 
         buffer.append( MessageFormat.format( rb.getString("weblogentryplugin.postedby"), author));
-        buffer.append( "<a href=\""+entryCtx.getURL(WikiContext.VIEW, entry.getName())+"\">"+rb.getString("weblogentryplugin.permalink")+"</a>" );
-        String commentPageName = TextUtil.replaceString( entry.getName(),
-                                                         "blogentry",
-                                                         "comments" );
+        buffer.append( "<a href=\"" + entryCtx.getURL( WikiContext.VIEW, entry.getName() ) + "\">" + rb.getString("weblogentryplugin.permalink") + "</a>" );
+        final String commentPageName = TextUtil.replaceString( entry.getName(), "blogentry", "comments" );
 
-        if( hasComments )
-        {
+        if( hasComments ) {
             int numComments = guessNumberOfComments( engine, commentPageName );
 
             //
-            //  We add the number of comments to the URL so that
-            //  the user's browsers would realize that the page
-            //  has changed.
+            //  We add the number of comments to the URL so that the user's browsers would realize that the page has changed.
             //
             buffer.append( "&nbsp;&nbsp;" );
 
-            String addcomment = rb.getString("weblogentryplugin.addcomment");
+            final String addcomment = rb.getString("weblogentryplugin.addcomment");
 
             buffer.append( "<a href=\""+
-                       entryCtx.getURL(WikiContext.COMMENT,
-                                       commentPageName,
-                                       "nc="+numComments)+
-                       "\">"+
-                       MessageFormat.format(addcomment, numComments)
-                       +"</a>" );
+                           entryCtx.getURL( WikiContext.COMMENT, commentPageName, "nc=" + numComments ) + "\">" +
+                           MessageFormat.format( addcomment, numComments ) +
+                           "</a>" );
         }
 
         buffer.append("</div>\n");
@@ -468,37 +395,25 @@ public class WeblogPlugin
      *  @param start The date which is the first to be considered
      *  @param end   The end date which is the last to be considered
      *  @return a list of pages with their FIRST revisions.
-     *  @throws ProviderException If something goes wrong
      */
-    public List< WikiPage > findBlogEntries( WikiEngine engine, String baseName, Date start, Date end )
-        throws ProviderException
-    {
-        PageManager mgr = engine.getPageManager();
-        Set< String > allPages = engine.getReferenceManager().findCreated();
-
-        ArrayList<WikiPage> result = new ArrayList<WikiPage>();
+    public List< WikiPage > findBlogEntries( final WikiEngine engine, String baseName, final Date start, final Date end ) {
+        final PageManager mgr = engine.getPageManager();
+        final Set< String > allPages = engine.getReferenceManager().findCreated();
+        final ArrayList<WikiPage> result = new ArrayList<>();
 
         baseName = makeEntryPage( baseName );
 
-        for( Iterator< String > i = allPages.iterator(); i.hasNext(); )
-        {
-            String pageName = i.next();
-
-            if( pageName.startsWith( baseName ) )
-            {
-                try
-                {
-                    WikiPage firstVersion = mgr.getPageInfo( pageName, 1 );
-                    Date d = firstVersion.getLastModified();
+        for( final String pageName : allPages ) {
+            if( pageName.startsWith( baseName ) ) {
+                try {
+                    final WikiPage firstVersion = mgr.getPageInfo( pageName, 1 );
+                    final Date d = firstVersion.getLastModified();
 
-                    if( d.after(start) && d.before(end) )
-                    {
+                    if( d.after( start ) && d.before( end ) ) {
                         result.add( firstVersion );
                     }
-                }
-                catch( Exception e )
-                {
-                    log.debug("Page name :"+pageName+" was suspected as a blog entry but it isn't because of parsing errors",e);
+                } catch( final Exception e ) {
+                    log.debug( "Page name :" + pageName + " was suspected as a blog entry but it isn't because of parsing errors", e );
                 }
             }
         }
@@ -509,25 +424,22 @@ public class WeblogPlugin
     /**
      *  Reverse comparison.
      */
-    private static class PageDateComparator implements Comparator<WikiPage>
-    {
-        public int compare( WikiPage page1, WikiPage page2 )
-        {
-            if( page1 == null || page2 == null )
-            {
+    private static class PageDateComparator implements Comparator< WikiPage > {
+
+        public int compare( final WikiPage page1, final WikiPage page2 ) {
+            if( page1 == null || page2 == null ) {
                 return 0;
             }
-
             return page2.getLastModified().compareTo( page1.getLastModified() );
         }
+
     }
 
     /**
      *  Mark us as being a real weblog.
      *  {@inheritDoc}
      */
-    public void executeParser(PluginContent element, WikiContext context, Map<String, String> params)
-    {
+    public void executeParser( final PluginContent element, final WikiContext context, final Map< String, String > params ) {
         context.getPage().setAttribute( ATTR_ISWEBLOG, "true" );
     }
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 686070c..cd1117a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -26,6 +26,7 @@ import org.apache.log4j.Logger;
 import org.apache.wiki.StringTransmutator;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
+import org.apache.wiki.WikiPage;
 import org.apache.wiki.api.exceptions.FilterException;
 import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.api.exceptions.WikiException;
@@ -270,6 +271,30 @@ public class DefaultRenderingManager implements RenderingManager {
      *  {@inheritDoc}
      */
     @Override
+    public String getHTML( final WikiContext context, final WikiPage page ) {
+        final String pagedata = m_engine.getPageManager().getPureText( page.getName(), page.getVersion() );
+        return textToHTML( context, pagedata );
+    }
+
+    /**
+     *  Returns the converted HTML of the page's specific version. The version must be a positive integer, otherwise the current
+     *  version is returned.
+     *
+     *  @param pagename WikiName of the page to convert.
+     *  @param version Version number to fetch
+     *  @return HTML-rendered page text.
+     */
+    public String getHTML( final String pagename, final int version ) {
+        final WikiPage page = m_engine.getPageManager().getPage( pagename, version );
+        final WikiContext context = new WikiContext( m_engine, page );
+        context.setRequestContext( WikiContext.NONE );
+        return getHTML( context, page );
+    }
+
+    /**
+     *  {@inheritDoc}
+     */
+    @Override
     public String textToHTML( final WikiContext context, String pagedata ) {
         String result = "";
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index ac2c4b0..fabfaaa 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -22,11 +22,13 @@ import org.apache.log4j.Logger;
 import org.apache.wiki.StringTransmutator;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
+import org.apache.wiki.WikiPage;
 import org.apache.wiki.api.exceptions.WikiException;
 import org.apache.wiki.event.WikiEventListener;
 import org.apache.wiki.modules.InternalModule;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.parser.WikiDocument;
+import org.apache.wiki.providers.WikiPageProvider;
 
 import java.io.IOException;
 import java.util.Properties;
@@ -141,6 +143,25 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     String getHTML( WikiContext context, WikiDocument doc ) throws IOException;
 
     /**
+     *  Returns the converted HTML of the page using a different context than the default context.
+     *
+     *  @param  context A WikiContext in which you wish to render this page in.
+     *  @param  page WikiPage reference.
+     *  @return HTML-rendered version of the page.
+     */
+    String getHTML( WikiContext context, WikiPage page );
+
+    /**
+     *  Returns the converted HTML of the page's specific version. The version must be a positive integer, otherwise the current
+     *  version is returned.
+     *
+     *  @param pagename WikiName of the page to convert.
+     *  @param version Version number to fetch
+     *  @return HTML-rendered page text.
+     */
+    String getHTML( String pagename, int version );
+
+    /**
      *   Convenience method for rendering, using the default parser and renderer.  Note that you can't use this method
      *   to do any arbitrary rendering, as the pagedata MUST be the data from the that the WikiContext refers to - this
      *   method caches the HTML internally, and will return the cached version.  If the pagedata is different from what
@@ -162,6 +183,16 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     }
 
     /**
+     *  Returns the converted HTML of the page.
+     *
+     *  @param page WikiName of the page to convert.
+     *  @return HTML-rendered version of the page.
+     */
+    default String getHTML( final String page ) {
+        return getHTML( page, WikiPageProvider.LATEST_VERSION );
+    }
+
+    /**
      *  Converts raw page data to HTML.
      *
      *  @param pagedata Raw page data to convert to HTML
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java b/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
index d4e5687..dfe9391 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/rss/RSSGenerator.java
@@ -204,7 +204,7 @@ public class RSSGenerator {
         else
         {
             buf.append(author+" created this page on "+page.getLastModified()+":<br /><hr /><br />" );
-            buf.append(m_engine.getHTML( page.getName() ));
+            buf.append(m_engine.getRenderingManager().getHTML( page.getName() ));
         }
 
         return buf.toString();
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/InsertPageTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/InsertPageTag.java
index 2f547b6..e932cdd 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/InsertPageTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/InsertPageTag.java
@@ -109,7 +109,7 @@ public class InsertPageTag extends WikiTagBase {
             final WikiPage oldPage = m_wikiContext.setRealPage( insertedPage );
             
             switch( m_mode ) {
-              case HTML: out.print( engine.getHTML( m_wikiContext, insertedPage ) ); break;
+              case HTML: out.print( engine.getRenderingManager().getHTML( m_wikiContext, insertedPage ) ); break;
               case PLAIN: out.print( engine.getPageManager().getText( insertedPage ) ); break;
             }
             
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/MetaWeblogHandler.java b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/MetaWeblogHandler.java
index c726b83..d2d8c80 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/MetaWeblogHandler.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/MetaWeblogHandler.java
@@ -22,7 +22,6 @@ import org.apache.log4j.Logger;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
 import org.apache.wiki.WikiPage;
-import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.attachment.Attachment;
 import org.apache.wiki.attachment.AttachmentManager;
 import org.apache.wiki.auth.AuthenticationManager;
@@ -35,7 +34,6 @@ import org.apache.wiki.plugin.WeblogPlugin;
 import org.apache.xmlrpc.XmlRpcException;
 
 import java.io.ByteArrayInputStream;
-import java.util.Collections;
 import java.util.Date;
 import java.util.Hashtable;
 import java.util.Iterator;
@@ -108,8 +106,7 @@ public class MetaWeblogHandler
     }
 
     /**
-     *  JSPWiki does not support categories, therefore JSPWiki
-     *  always returns an empty list for categories.
+     *  JSPWiki does not support categories, therefore JSPWiki always returns an empty list for categories.
      *
      *  @param blogid The id of the blog.
      *  @param username The username to use
@@ -117,36 +114,25 @@ public class MetaWeblogHandler
      *  @throws XmlRpcException If something goes wrong
      *  @return An empty hashtable.
      */
-    public Hashtable getCategories( String blogid,
-                                    String username,
-                                    String password )
-        throws XmlRpcException
-    {
-        WikiPage page = m_context.getEngine().getPageManager().getPage( blogid );
-
+    public Hashtable getCategories( String blogid, String username, String password )  throws XmlRpcException {
+        final WikiPage page = m_context.getEngine().getPageManager().getPage( blogid );
         checkPermissions( page, username, password, "view" );
-
-        Hashtable ht = new Hashtable();
+        final Hashtable ht = new Hashtable();
 
         return ht;
     }
 
-    private String getURL( String page )
-    {
-        return m_context.getEngine().getURL( WikiContext.VIEW,
-                                             page,
-                                             null,
-                                             true ); // Force absolute urls
+    private String getURL( String page ) {
+        return m_context.getEngine().getURL( WikiContext.VIEW, page,null, true ); // Force absolute urls
     }
 
     /**
-     *  Takes a wiki page, and creates a metaWeblog struct
-     *  out of it.
+     *  Takes a wiki page, and creates a metaWeblog struct out of it.
+     *
      *  @param page The actual entry page
      *  @return A metaWeblog entry struct.
      */
-    private Hashtable<String,Object> makeEntry( WikiPage page )
-    {
+    private Hashtable<String,Object> makeEntry( WikiPage page ) {
         Hashtable<String, Object> ht = new Hashtable<>();
 
         WikiPage firstVersion = m_context.getEngine().getPageManager().getPage( page.getName(), 1 );
@@ -157,19 +143,22 @@ public class MetaWeblogHandler
         ht.put("postid", page.getName());
         ht.put("userid", page.getAuthor());
 
-        String pageText = m_context.getEngine().getPageManager().getText(page.getName());
+        final String pageText = m_context.getEngine().getPageManager().getText(page.getName());
         String title = "";
-        int firstLine = pageText.indexOf('\n');
+        final int firstLine = pageText.indexOf('\n');
 
-        if( firstLine > 0 )
-        {
+        if( firstLine > 0 ) {
             title = pageText.substring( 0, firstLine );
         }
 
-        if( title.trim().length() == 0 ) title = page.getName();
+        if( title.trim().length() == 0 ) {
+            title = page.getName();
+        }
 
         // Remove wiki formatting
-        while( title.startsWith("!") ) title = title.substring(1);
+        while( title.startsWith("!") ) {
+            title = title.substring(1);
+        }
 
         ht.put("title", title);
         ht.put("description", pageText);
@@ -187,16 +176,8 @@ public class MetaWeblogHandler
      *  @throws XmlRpcException If something goes wrong
      *  @return As per MetaweblogAPI specification
      */
-
-    // FIXME: The implementation is suboptimal, as it
-    //        goes through all of the blog entries.
-
-    public Hashtable getRecentPosts( String blogid,
-                                     String username,
-                                     String password,
-                                     int numberOfPosts)
-        throws XmlRpcException
-    {
+    // FIXME: The implementation is suboptimal, as it goes through all of the blog entries.
+    public Hashtable getRecentPosts( String blogid, String username, String password, int numberOfPosts) throws XmlRpcException {
         Hashtable<String, Hashtable<String, Object>> result = new Hashtable<>();
 
         log.info( "metaWeblog.getRecentPosts() called");
@@ -205,29 +186,20 @@ public class MetaWeblogHandler
 
         checkPermissions( page, username, password, "view" );
 
-        try {
-            WeblogPlugin plugin = new WeblogPlugin();
-
-            List<WikiPage> changed = plugin.findBlogEntries(m_context.getEngine(),
-                                                            blogid,
-                                                            new Date(0L),
-                                                            new Date());
-
-            Collections.sort( changed, new PageTimeComparator() );
+        final WeblogPlugin plugin = new WeblogPlugin();
+        final List<WikiPage> changed = plugin.findBlogEntries( m_context.getEngine(), blogid, new Date( 0L ), new Date() );
 
-            int items = 0;
-            for( Iterator< WikiPage > i = changed.iterator(); i.hasNext() && items < numberOfPosts; items++ )
-            {
-                WikiPage p = i.next();
+        changed.sort( new PageTimeComparator() );
 
-                result.put( "entry", makeEntry( p ) );
-            }
+        int items = 0;
+        for( Iterator< WikiPage > i = changed.iterator(); i.hasNext() && items < numberOfPosts; items++ )
+        {
+            WikiPage p = i.next();
 
-        } catch( final ProviderException e ) {
-            log.error( "Failed to list recent posts", e );
-            throw new XmlRpcException( 0, e.getMessage() );
+            result.put( "entry", makeEntry( p ) );
         }
 
+
         return result;
     }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
index ee7ccfb..756a710 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
@@ -199,13 +199,13 @@ public class RPCHandler extends AbstractRPCHandler {
     public byte[] getPageHTML( String pagename ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
-        return toRPCBase64( m_engine.getHTML( pagename ) );
+        return toRPCBase64( m_engine.getRenderingManager().getHTML( pagename ) );
     }
 
     public byte[] getPageHTMLVersion( String pagename, int version ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
-        return toRPCBase64( m_engine.getHTML( pagename, version ) );
+        return toRPCBase64( m_engine.getRenderingManager().getHTML( pagename, version ) );
     }
 
     public Vector< Hashtable< String, String > > listLinks( String pagename ) throws XmlRpcException {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
index fa1a451..a0b323b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
@@ -155,11 +155,11 @@ public class RPCHandlerUTF8 extends AbstractRPCHandler {
     }
 
     public String getPageHTML( final String pagename ) throws XmlRpcException  {
-        return m_engine.getHTML( parsePageCheckCondition( pagename ) );
+        return m_engine.getRenderingManager().getHTML( parsePageCheckCondition( pagename ) );
     }
 
     public String getPageHTMLVersion( final String pagename, final int version ) throws XmlRpcException {
-        return m_engine.getHTML( parsePageCheckCondition( pagename ), version );
+        return m_engine.getRenderingManager().getHTML( parsePageCheckCondition( pagename ), version );
     }
 
     public Vector< Hashtable< String, String > > listLinks( String pagename ) throws XmlRpcException {
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/TestEngine.java b/jspwiki-main/src/test/java/org/apache/wiki/TestEngine.java
index 9aaf8d2..f97fa6e 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/TestEngine.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/TestEngine.java
@@ -395,7 +395,7 @@ public class TestEngine extends WikiEngine
         final WikiPage page = getPageManager().getPage( pagename, WikiPageProvider.LATEST_VERSION );
         final WikiContext context = new WikiContext( this, newHttpRequest(), page );
         context.setRequestContext( WikiContext.NONE );
-        return getHTML( context, page );
+        return getRenderingManager().getHTML( context, page );
     }
 
     public static void trace() {
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java b/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
index 7eb97c2..69d3f0e 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
@@ -101,16 +101,6 @@ public class WikiEngineTest {
     }
 
     @Test
-    public void testGetHTML() throws Exception {
-        final String text = "''Foobar.''";
-        final String name = NAME1;
-        m_engine.saveText( name, text );
-
-        final String data = m_engine.getHTML( name );
-        Assertions.assertEquals( "<i>Foobar.</i>\n", data );
-    }
-
-    @Test
     public void testEncodeNameLatin1() {
         final String name = "abc\u00e5\u00e4\u00f6";
         Assertions.assertEquals( "abc%E5%E4%F6", m_engine.encodeName(name) );
@@ -284,11 +274,10 @@ public class WikiEngineTest {
         Assertions.assertEquals( "puppaa", m_engine.getPageManager().getText("This is a test").trim(), "normal" );
     }
 
-
     @Test
     public void testParsedVariables() throws Exception {
         m_engine.saveText( "TestPage", "[{SET foo=bar}][{SamplePlugin text='{$foo}'}]");
-        final String res = m_engine.getHTML( "TestPage" );
+        final String res = m_engine.getRenderingManager().getHTML( "TestPage" );
 
         Assertions.assertEquals( "bar\n", res );
     }
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/pages/DefaultPageManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/pages/DefaultPageManagerTest.java
index 1897db6..7966f79 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/pages/DefaultPageManagerTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/pages/DefaultPageManagerTest.java
@@ -224,7 +224,7 @@ public class DefaultPageManagerTest {
         props.setProperty( "jspwiki.pageProvider", "org.apache.wiki.providers.VerySimpleProvider" );
         props.setProperty( "jspwiki.usePageCache", "false" );
         final WikiEngine engine = new TestEngine( props );
-        final String p = engine.getHTML( "test", -1 );
+        final String p = engine.getRenderingManager().getHTML( "test", -1 );
         final VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider();
 
         Assertions.assertEquals( "test", vsp.m_latestReq, "wrong page" );
@@ -238,7 +238,7 @@ public class DefaultPageManagerTest {
         props.setProperty( "jspwiki.pageProvider", "org.apache.wiki.providers.VerySimpleProvider" );
         props.setProperty( "jspwiki.usePageCache", "true" );
         final WikiEngine engine = new TestEngine( props );
-        final String p = engine.getHTML( VerySimpleProvider.PAGENAME, -1 );
+        final String p = engine.getRenderingManager().getHTML( VerySimpleProvider.PAGENAME, -1 );
         final CachingProvider cp = (CachingProvider)engine.getPageManager().getProvider();
         final VerySimpleProvider vsp = (VerySimpleProvider) cp.getRealProvider();
 
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/DefaultPluginManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/DefaultPluginManagerTest.java
index ca5aac5..69cf0aa 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/DefaultPluginManagerTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/DefaultPluginManagerTest.java
@@ -147,7 +147,7 @@ public class DefaultPluginManagerTest {
     @Test
     public void testParserPlugin() throws Exception {
         engine.getPageManager().saveText(context, "[{SamplePlugin render=true}]");
-        engine.getHTML( "Testpage" );
+        engine.getRenderingManager().getHTML( "Testpage" );
         Assertions.assertTrue( SamplePlugin.c_rendered );
     }
 
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/GroupsTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/GroupsTest.java
index 529af2c..6979a65 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/GroupsTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/GroupsTest.java
@@ -40,7 +40,7 @@ public class GroupsTest {
 
         testEngine.saveText( "Test", src );
 
-        String res = testEngine.getHTML( "Test" );
+        String res = testEngine.getRenderingManager().getHTML( "Test" );
 
         Assertions.assertEquals( "<a href=\"/test/Group.jsp?group=Admin\">Admin</a>, "
                 + "<a href=\"/test/Group.jsp?group=Art\">Art</a>, "
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/IfPluginTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/IfPluginTest.java
index 90eaff2..8879381 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/IfPluginTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/IfPluginTest.java
@@ -74,7 +74,7 @@ public class IfPluginTest {
         WikiPage page = testEngine.getPageManager().getPage( "Test", WikiPageProvider.LATEST_VERSION );
         WikiContext context = getJanneBasedWikiContextFor( page );
 
-        String res = testEngine.getHTML( context, page );
+        String res = testEngine.getRenderingManager().getHTML( context, page );
         Assertions.assertEquals( expected, res );
     }
 
@@ -95,7 +95,7 @@ public class IfPluginTest {
         WikiPage page = testEngine.getPageManager().getPage( "Test", WikiPageProvider.LATEST_VERSION );
         WikiContext context = getJanneBasedWikiContextFor( page );
 
-        String res = testEngine.getHTML( context, page );
+        String res = testEngine.getRenderingManager().getHTML( context, page );
         Assertions.assertEquals( expected, res );
     }
 
@@ -105,8 +105,7 @@ public class IfPluginTest {
      * @throws WikiException test Assertions.failing.
      */
     @Test
-    public void testIfPluginIPAllowed() throws WikiException
-    {
+    public void testIfPluginIPAllowed() throws WikiException {
         String src = "[{IfPlugin ip='127.0.0.1'\n" +
                      "\n" +
                      "Content visible for 127.0.0.1}]";
@@ -116,7 +115,7 @@ public class IfPluginTest {
         WikiPage page = testEngine.getPageManager().getPage( "Test", WikiPageProvider.LATEST_VERSION );
         WikiContext context = getJanneBasedWikiContextFor( page );
 
-        String res = testEngine.getHTML( context, page );
+        String res = testEngine.getRenderingManager().getHTML( context, page );
         Assertions.assertEquals( expected, res );
     }
 
@@ -126,8 +125,7 @@ public class IfPluginTest {
      * @throws WikiException test Assertions.failing.
      */
     @Test
-    public void testIfPluginIPNotAllowed() throws WikiException
-    {
+    public void testIfPluginIPNotAllowed() throws WikiException {
         String src = "[{IfPlugin ip='!127.0.0.1'\n" +
                      "\n" +
                      "Content NOT visible for 127.0.0.1}]";
@@ -137,7 +135,7 @@ public class IfPluginTest {
         WikiPage page = testEngine.getPageManager().getPage( "Test", WikiPageProvider.LATEST_VERSION );
         WikiContext context = getJanneBasedWikiContextFor( page );
 
-        String res = testEngine.getHTML( context, page );
+        String res = testEngine.getRenderingManager().getHTML( context, page );
         Assertions.assertEquals( expected, res );
     }
 
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/InsertPageTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/InsertPageTest.java
index 5d887cf..82cd0ce 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/InsertPageTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/InsertPageTest.java
@@ -18,14 +18,14 @@
  */
 package org.apache.wiki.plugin;
 
-import java.util.Properties;
-
 import org.apache.wiki.TestEngine;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
+import java.util.Properties;
+
 
 public class InsertPageTest
 {
@@ -57,7 +57,7 @@ public class InsertPageTest
 
         // Just check that it contains a proper error message; don't bother do HTML
         // checking.
-        String res = testEngine.getHTML("ThisPage");
+        String res = testEngine.getRenderingManager().getHTML("ThisPage");
         Assertions.assertTrue( res.indexOf("Circular reference") != -1 );
     }
 
@@ -72,64 +72,56 @@ public class InsertPageTest
 
         // Just check that it contains a proper error message; don't bother do HTML
         // checking.
-        Assertions.assertTrue( testEngine.getHTML("ThisPage").indexOf("Circular reference") != -1 );
+        Assertions.assertTrue( testEngine.getRenderingManager().getHTML("ThisPage").indexOf("Circular reference") != -1 );
     }
 
     @Test
-    public void testMultiInvocation() throws Exception
-    {
+    public void testMultiInvocation() throws Exception {
         String src  = "[{InsertPage page='ThisPage2'}] [{InsertPage page='ThisPage2'}]";
         String src2 = "foo[{ALLOW view Anonymous}]";
 
         testEngine.saveText("ThisPage",src);
         testEngine.saveText("ThisPage2",src2);
 
-        Assertions.assertTrue( testEngine.getHTML("ThisPage").indexOf("Circular reference") == -1, "got circ ref" );
-
-        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div> <div class=\"inserted-page \" >foo\n</div>\n", testEngine.getHTML("ThisPage"), "found != 2" );
-
+        Assertions.assertTrue( testEngine.getRenderingManager().getHTML("ThisPage").indexOf("Circular reference") == -1, "got circ ref" );
+        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div> <div class=\"inserted-page \" >foo\n</div>\n",
+                                 testEngine.getRenderingManager().getHTML("ThisPage"), "found != 2" );
     }
 
     @Test
-    public void testUnderscore() throws Exception
-    {
+    public void testUnderscore() throws Exception {
         String src  = "[{InsertPage page='Test_Page'}]";
         String src2 = "foo[{ALLOW view Anonymous}]";
 
         testEngine.saveText("ThisPage",src);
         testEngine.saveText("Test_Page",src2);
 
-        Assertions.assertTrue( testEngine.getHTML("ThisPage").indexOf("Circular reference") == -1, "got circ ref" );
-
-        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getHTML("ThisPage"), "found != 1" );
+        Assertions.assertTrue( testEngine.getRenderingManager().getHTML("ThisPage").indexOf("Circular reference") == -1, "got circ ref" );
+        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getRenderingManager().getHTML("ThisPage"), "found != 1" );
     }
 
-
     /**
      * a link containing a blank should work if there is a page with exact the
      * same name ('Test Page')
      */
     @Test
-    public void testWithBlanks1() throws Exception
-    {
+    public void testWithBlanks1() throws Exception {
         testEngine.saveText( "ThisPage", "[{InsertPage page='Test Page'}]" );
         testEngine.saveText( "Test Page", "foo[{ALLOW view Anonymous}]" );
 
-        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getHTML( "ThisPage" ), "found != 1" );
+        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getRenderingManager().getHTML( "ThisPage" ), "found != 1" );
     }
 
     /**
-     * same as testWithBlanks1, but it should still work if the page does not
-     * have the blank in it ( 'Test Page' should work if the included page is
-     * called 'TestPage')
+     * same as testWithBlanks1, but it should still work if the page does not have the blank in it ( 'Test Page' should work if the
+     * included page is called 'TestPage')
      */
     @Test
-    public void testWithBlanks2() throws Exception
-    {
+    public void testWithBlanks2() throws Exception {
         testEngine.saveText( "ThisPage", "[{InsertPage page='Test Page'}]" );
         testEngine.saveText( "TestPage", "foo[{ALLOW view Anonymous}]" );
 
-        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getHTML( "ThisPage" ), "found != 1" );
+        Assertions.assertEquals( "<div class=\"inserted-page \" >foo\n</div>\n", testEngine.getRenderingManager().getHTML( "ThisPage" ), "found != 1" );
     }
 
 }
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/plugin/PageViewPluginTest.java b/jspwiki-main/src/test/java/org/apache/wiki/plugin/PageViewPluginTest.java
index d7a8f6b..2073349 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/plugin/PageViewPluginTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/plugin/PageViewPluginTest.java
@@ -71,9 +71,9 @@ public class PageViewPluginTest
         WikiContext context2 = new WikiContext( testEngine, page2 );
 
         // generate counts:
-        testEngine.getHTML( context1, page1 );
-        testEngine.getHTML( context2, page2 );
-        testEngine.getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context1, page1 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
 
         // mind the double \n in the following string:
         String pageViewPageContent = "[{PageViewPlugin show='list''\n\n* {1} ({2} views)\n}]";
@@ -82,7 +82,7 @@ public class PageViewPluginTest
         WikiPage pageviews = testEngine.getPageManager().getPage( "PageViews" );
         WikiContext contextPV = new WikiContext( testEngine, pageviews );
 
-        String result = testEngine.getHTML( contextPV, pageviews );
+        String result = testEngine.getRenderingManager().getHTML( contextPV, pageviews );
 //        System.out.println( result );
 
         Assertions.assertTrue( result.contains( "Test Page 01 (2 views)" ) );
@@ -101,9 +101,9 @@ public class PageViewPluginTest
         WikiContext context2 = new WikiContext( testEngine, page2 );
 
         // generate counts:
-        testEngine.getHTML( context1, page1 );
-        testEngine.getHTML( context2, page2 );
-        testEngine.getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context1, page1 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
 
         // mind the double \n in the following string:
         String pageViewPageContent = "[{PageViewPlugin show='list' exclude='TestPageExcl*' '\n\n* {1} ({2} views)\n}]";
@@ -112,7 +112,7 @@ public class PageViewPluginTest
         WikiPage pageviews = testEngine.getPageManager().getPage( "PageViews" );
         WikiContext contextPV = new WikiContext( testEngine, pageviews );
 
-        String result = testEngine.getHTML( contextPV, pageviews );
+        String result = testEngine.getRenderingManager().getHTML( contextPV, pageviews );
 //        System.out.println( result );
 
         Assertions.assertTrue( result.contains( "Test Page 01" ) );
@@ -132,9 +132,9 @@ public class PageViewPluginTest
         WikiContext context2 = new WikiContext( testEngine, page2 );
 
         // generate counts:
-        testEngine.getHTML( context1, page1 );
-        testEngine.getHTML( context2, page2 );
-        testEngine.getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context1, page1 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
 
         // mind the double \n in the following string:
         String pageViewPageContent = "[{PageViewPlugin show='list' sort=count '\n\n* {1} ({2} views)\n}]";
@@ -143,7 +143,7 @@ public class PageViewPluginTest
         WikiPage pageviews = testEngine.getPageManager().getPage( "PageViews" );
         WikiContext contextPV = new WikiContext( testEngine, pageviews );
 
-        String result = testEngine.getHTML( contextPV, pageviews );
+        String result = testEngine.getRenderingManager().getHTML( contextPV, pageviews );
 //        System.out.println( result );
 
         int start1 = result.indexOf( "Test Page 01" );
@@ -170,11 +170,11 @@ public class PageViewPluginTest
         WikiContext context4 = new WikiContext( testEngine, page4 );
 
         // generate counts:
-        testEngine.getHTML( context1, page1 );
-        testEngine.getHTML( context2, page2 );
-        testEngine.getHTML( context2, page2 );
-        testEngine.getHTML( context3, page3 );
-        testEngine.getHTML( context4, page4 );
+        testEngine.getRenderingManager().getHTML( context1, page1 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context2, page2 );
+        testEngine.getRenderingManager().getHTML( context3, page3 );
+        testEngine.getRenderingManager().getHTML( context4, page4 );
 
         // mind the double \n in the following string:
         String pageViewPageContent = "[{PageViewPlugin show='list' entries=3'\n\n* {1} ({2} views)\n}]";
@@ -183,7 +183,7 @@ public class PageViewPluginTest
         WikiPage pageviews = testEngine.getPageManager().getPage( "PageViews" );
         WikiContext contextPV = new WikiContext( testEngine, pageviews );
 
-        String result = testEngine.getHTML( contextPV, pageviews );
+        String result = testEngine.getRenderingManager().getHTML( contextPV, pageviews );
 //        System.out.println( result );
 
         Assertions.assertTrue( result.contains( "Test Page 03" ) );
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
index 3ba8e6d..436427a 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
@@ -85,6 +85,16 @@ public class RenderingManagerTest {
         Assertions.assertEquals("This Is A Page", m_engine.getRenderingManager().beautifyTitle( src ) );
     }
 
+    @Test
+    public void testGetHTML() throws Exception {
+        final String text = "''Foobar.''";
+        final String name = "Test1";
+        m_engine.saveText( name, text );
+
+        final String data = m_engine.getRenderingManager().getHTML( name );
+        Assertions.assertEquals( "<i>Foobar.</i>\n", data );
+    }
+
     /**
      * Tests the relative speed of the DOM cache with respect to
      * page being parsed every single time.
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/stress/MassiveRepositoryTest.java b/jspwiki-main/src/test/java/org/apache/wiki/stress/MassiveRepositoryTest.java
index 0957019..b6cbe09 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/stress/MassiveRepositoryTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/stress/MassiveRepositoryTest.java
@@ -161,7 +161,7 @@ public class MassiveRepositoryTest {
         {
             String page = getName( random.nextInt( numPages ) );
             
-            String content = engine.getHTML( page, WikiProvider.LATEST_VERSION );
+            String content = engine.getRenderingManager().getHTML( page, WikiProvider.LATEST_VERSION );
               
             Assertions.assertNotNull(content);
             


[jspwiki] 18/26: JSPWIKI-120: moved textToHtml(..) methods from WikiEngine to RenderingManager

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 3729e43d8bd1e352ffdeca8571e7e5cadd7d394b
Author: juanpablo <ju...@apache.org>
AuthorDate: Wed Jan 15 00:12:43 2020 +0100

    JSPWIKI-120: moved textToHtml(..) methods from WikiEngine to RenderingManager
    
    also, constant PROP_RUNFILTERS from WikiEngine moved to VariableManager as VAR_RUNFILTERS
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  | 114 +--------------------
 .../org/apache/wiki/plugin/TableOfContents.java    |   3 +-
 .../wiki/references/DefaultReferenceManager.java   |  15 ++-
 .../wiki/render/DefaultRenderingManager.java       |  67 ++++++++++++
 .../org/apache/wiki/render/RenderingManager.java   |  55 ++++++++++
 .../org/apache/wiki/variables/VariableManager.java |   3 +
 .../java/org/apache/wiki/xmlrpc/RPCHandler.java    |  87 +++++++---------
 .../org/apache/wiki/xmlrpc/RPCHandlerUTF8.java     |   2 +-
 8 files changed, 174 insertions(+), 172 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
index fb9bdc5..9f9895b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -43,7 +43,6 @@ import org.apache.wiki.event.WikiPageEvent;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.pages.PageManager;
 import org.apache.wiki.parser.MarkupParser;
-import org.apache.wiki.parser.WikiDocument;
 import org.apache.wiki.providers.WikiPageProvider;
 import org.apache.wiki.references.ReferenceManager;
 import org.apache.wiki.render.RenderingManager;
@@ -67,7 +66,6 @@ import javax.servlet.ServletConfig;
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import java.io.File;
-import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
 import java.net.URL;
@@ -160,9 +158,6 @@ public class WikiEngine  {
     /** Property name for setting the url generator instance */
     public static final String PROP_URLCONSTRUCTOR = "jspwiki.urlConstructor";
 
-    /** If this property is set to false, all filters are disabled when translating. */
-    public static final String PROP_RUNFILTERS   = "jspwiki.runFilters";
-
     /** Does the work in renaming pages. */
     private PageRenamer    m_pageRenamer = null;
 
@@ -976,7 +971,7 @@ public class WikiEngine  {
     public String textToHTML( final WikiContext context, String pagedata ) {
         String result = "";
 
-        final boolean runFilters = "true".equals(m_variableManager.getValue(context,PROP_RUNFILTERS,"true"));
+        final boolean runFilters = "true".equals(m_variableManager.getValue(context,VariableManager.VAR_RUNFILTERS,"true"));
 
         final StopWatch sw = new StopWatch();
         sw.start();
@@ -1012,113 +1007,6 @@ public class WikiEngine  {
     }
 
     /**
-     *  Just convert WikiText to HTML.
-     *
-     *  @param context The WikiContext in which to do the conversion
-     *  @param pagedata The data to render
-     *  @param localLinkHook Is called whenever a wiki link is found
-     *  @param extLinkHook   Is called whenever an external link is found
-     *
-     *  @return HTML-rendered page text.
-     */
-
-    public String textToHTML( final WikiContext context,
-                              final String pagedata,
-                              final StringTransmutator localLinkHook,
-                              final StringTransmutator extLinkHook ) {
-        return textToHTML( context, pagedata, localLinkHook, extLinkHook, null, true, false );
-    }
-
-    /**
-     *  Just convert WikiText to HTML.
-     *
-     *  @param context The WikiContext in which to do the conversion
-     *  @param pagedata The data to render
-     *  @param localLinkHook Is called whenever a wiki link is found
-     *  @param extLinkHook   Is called whenever an external link is found
-     *  @param attLinkHook   Is called whenever an attachment link is found
-     *  @return HTML-rendered page text.
-     */
-
-    public String textToHTML( final WikiContext context,
-                              final String pagedata,
-                              final StringTransmutator localLinkHook,
-                              final StringTransmutator extLinkHook,
-                              final StringTransmutator attLinkHook ) {
-        return textToHTML( context, pagedata, localLinkHook, extLinkHook, attLinkHook, true, false );
-    }
-
-    /**
-     *  Helper method for doing the HTML translation.
-     *
-     *  @param context The WikiContext in which to do the conversion
-     *  @param pagedata The data to render
-     *  @param localLinkHook Is called whenever a wiki link is found
-     *  @param extLinkHook   Is called whenever an external link is found
-     *  @param parseAccessRules Parse the access rules if we encounter them
-     *  @param justParse Just parses the pagedata, does not actually render.  In this case, this methods an empty string.
-     *  @return HTML-rendered page text.
-     */
-    public String textToHTML( final WikiContext context,
-                              String pagedata,
-                              final StringTransmutator localLinkHook,
-                              final StringTransmutator extLinkHook,
-                              final StringTransmutator attLinkHook,
-                              final boolean            parseAccessRules,
-                              final boolean            justParse ) {
-        String result = "";
-
-        if( pagedata == null ) {
-            log.error("NULL pagedata to textToHTML()");
-            return null;
-        }
-
-        final boolean runFilters = "true".equals(m_variableManager.getValue(context,PROP_RUNFILTERS,"true"));
-
-        try {
-            final StopWatch sw = new StopWatch();
-            sw.start();
-
-            if( runFilters && m_filterManager != null ) {
-                pagedata = m_filterManager.doPreTranslateFiltering( context, pagedata );
-            }
-
-            final MarkupParser mp = m_renderingManager.getParser( context, pagedata );
-            mp.addLocalLinkHook( localLinkHook );
-            mp.addExternalLinkHook( extLinkHook );
-            mp.addAttachmentLinkHook( attLinkHook );
-
-            if( !parseAccessRules ) {
-                mp.disableAccessRules();
-            }
-
-            final WikiDocument doc = mp.parse();
-
-            //  In some cases it's better just to parse, not to render
-            if( !justParse ) {
-                result = m_renderingManager.getHTML( context, doc );
-
-                if( runFilters && m_filterManager != null ) {
-                    result = m_filterManager.doPostTranslateFiltering( context, result );
-                }
-            }
-
-            sw.stop();
-
-            if( log.isDebugEnabled() ) {
-                log.debug( "Page " + context.getRealPage().getName() + " rendered, took " + sw );
-            }
-        } catch( final IOException e ) {
-            log.error( "Failed to scan page data: ", e );
-        } catch( final FilterException e ) {
-        	log.error( "page filter threw exception: ", e );
-            // FIXME: Don't yet know what to do
-        }
-
-        return result;
-    }
-
-    /**
      *  Returns this object's ReferenceManager.
      *  @return The current ReferenceManager instance.
      *
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/TableOfContents.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/TableOfContents.java
index ff21a4b..79bc6c2 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/TableOfContents.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/TableOfContents.java
@@ -31,6 +31,7 @@ import org.apache.wiki.parser.HeadingListener;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.preferences.Preferences;
 import org.apache.wiki.util.TextUtil;
+import org.apache.wiki.variables.VariableManager;
 
 import java.io.IOException;
 import java.util.Map;
@@ -216,7 +217,7 @@ public class TableOfContents
 
         try {
             String wikiText = engine.getPageManager().getPureText( page );
-            final boolean runFilters = "true".equals( engine.getVariableManager().getValue( context, WikiEngine.PROP_RUNFILTERS, "true" ) );
+            final boolean runFilters = "true".equals( engine.getVariableManager().getValue( context, VariableManager.VAR_RUNFILTERS, "true" ) );
 
             if( runFilters ) {
 				try {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/references/DefaultReferenceManager.java b/jspwiki-main/src/main/java/org/apache/wiki/references/DefaultReferenceManager.java
index 803484f..e073b7f 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/references/DefaultReferenceManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/references/DefaultReferenceManager.java
@@ -428,14 +428,13 @@ public class DefaultReferenceManager extends BasicPageFilter implements Referenc
      */
     public Collection< String > scanWikiLinks( final WikiPage page, final String pagedata ) {
         final LinkCollector localCollector = new LinkCollector();
-
-        m_engine.textToHTML( new WikiContext( m_engine, page ),
-                pagedata,
-                localCollector,
-                null,
-                localCollector,
-                false,
-                true );
+        m_engine.getRenderingManager().textToHTML( new WikiContext( m_engine, page ),
+                                                   pagedata,
+                                                   localCollector,
+                                                   null,
+                                                   localCollector,
+                                                   false,
+                                                   true );
 
         return localCollector.getLinks();
     }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 4aa40dc..331ad7d 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -21,9 +21,12 @@ package org.apache.wiki.render;
 import net.sf.ehcache.Cache;
 import net.sf.ehcache.CacheManager;
 import net.sf.ehcache.Element;
+import org.apache.commons.lang3.time.StopWatch;
 import org.apache.log4j.Logger;
+import org.apache.wiki.StringTransmutator;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
+import org.apache.wiki.api.exceptions.FilterException;
 import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.api.exceptions.WikiException;
 import org.apache.wiki.attachment.Attachment;
@@ -38,6 +41,7 @@ import org.apache.wiki.parser.WikiDocument;
 import org.apache.wiki.providers.WikiPageProvider;
 import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.TextUtil;
+import org.apache.wiki.variables.VariableManager;
 
 import java.io.IOException;
 import java.io.StringReader;
@@ -266,6 +270,69 @@ public class DefaultRenderingManager implements RenderingManager {
      *  {@inheritDoc}
      */
     @Override
+    public String textToHTML( final WikiContext context,
+                              String pagedata,
+                              final StringTransmutator localLinkHook,
+                              final StringTransmutator extLinkHook,
+                              final StringTransmutator attLinkHook,
+                              final boolean parseAccessRules,
+                              final boolean justParse ) {
+        String result = "";
+
+        if( pagedata == null ) {
+            log.error("NULL pagedata to textToHTML()");
+            return null;
+        }
+
+        final boolean runFilters = "true".equals( m_engine.getVariableManager().getValue( context, VariableManager.VAR_RUNFILTERS,"true" ) );
+
+        try {
+            final StopWatch sw = new StopWatch();
+            sw.start();
+
+            if( runFilters && m_engine.getFilterManager() != null ) {
+                pagedata = m_engine.getFilterManager().doPreTranslateFiltering( context, pagedata );
+            }
+
+            final MarkupParser mp = getParser( context, pagedata );
+            mp.addLocalLinkHook( localLinkHook );
+            mp.addExternalLinkHook( extLinkHook );
+            mp.addAttachmentLinkHook( attLinkHook );
+
+            if( !parseAccessRules ) {
+                mp.disableAccessRules();
+            }
+
+            final WikiDocument doc = mp.parse();
+
+            //  In some cases it's better just to parse, not to render
+            if( !justParse ) {
+                result = getHTML( context, doc );
+
+                if( runFilters && m_engine.getFilterManager() != null ) {
+                    result = m_engine.getFilterManager().doPostTranslateFiltering( context, result );
+                }
+            }
+
+            sw.stop();
+
+            if( log.isDebugEnabled() ) {
+                log.debug( "Page " + context.getRealPage().getName() + " rendered, took " + sw );
+            }
+        } catch( final IOException e ) {
+            log.error( "Failed to scan page data: ", e );
+        } catch( final FilterException e ) {
+            log.error( "page filter threw exception: ", e );
+            // FIXME: Don't yet know what to do
+        }
+
+        return result;
+    }
+
+    /**
+     *  {@inheritDoc}
+     */
+    @Override
     public WikiRenderer getRenderer( final WikiContext context, final WikiDocument doc ) {
         final Object[] params = { context, doc };
         return getRenderer( params, m_rendererConstructor );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index b46e628..937fce7 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -19,6 +19,7 @@
 package org.apache.wiki.render;
 
 import org.apache.log4j.Logger;
+import org.apache.wiki.StringTransmutator;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
 import org.apache.wiki.api.exceptions.WikiException;
@@ -160,4 +161,58 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
         return null;
     }
 
+    /**
+     *  Helper method for doing the HTML translation.
+     *
+     *  @param context The WikiContext in which to do the conversion
+     *  @param pagedata The data to render
+     *  @param localLinkHook Is called whenever a wiki link is found
+     *  @param extLinkHook   Is called whenever an external link is found
+     *  @param parseAccessRules Parse the access rules if we encounter them
+     *  @param justParse Just parses the pagedata, does not actually render.  In this case, this methods an empty string.
+     *  @return HTML-rendered page text.
+     */
+    String textToHTML( WikiContext context,
+                       String pagedata,
+                       StringTransmutator localLinkHook,
+                       StringTransmutator extLinkHook,
+                       StringTransmutator attLinkHook,
+                       boolean parseAccessRules,
+                       boolean justParse );
+
+    /**
+     *  Just convert WikiText to HTML.
+     *
+     *  @param context The WikiContext in which to do the conversion
+     *  @param pagedata The data to render
+     *  @param localLinkHook Is called whenever a wiki link is found
+     *  @param extLinkHook   Is called whenever an external link is found
+     *
+     *  @return HTML-rendered page text.
+     */
+    default String textToHTML( final WikiContext context,
+                               final String pagedata,
+                               final StringTransmutator localLinkHook,
+                               final StringTransmutator extLinkHook ) {
+        return textToHTML( context, pagedata, localLinkHook, extLinkHook, null, true, false );
+    }
+
+    /**
+     *  Just convert WikiText to HTML.
+     *
+     *  @param context The WikiContext in which to do the conversion
+     *  @param pagedata The data to render
+     *  @param localLinkHook Is called whenever a wiki link is found
+     *  @param extLinkHook   Is called whenever an external link is found
+     *  @param attLinkHook   Is called whenever an attachment link is found
+     *  @return HTML-rendered page text.
+     */
+    default String textToHTML( final WikiContext context,
+                               final String pagedata,
+                               final StringTransmutator localLinkHook,
+                               final StringTransmutator extLinkHook,
+                               final StringTransmutator attLinkHook ) {
+        return textToHTML( context, pagedata, localLinkHook, extLinkHook, attLinkHook, true, false );
+    }
+
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java b/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
index 92cfab3..bb94598 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/variables/VariableManager.java
@@ -32,6 +32,9 @@ public interface VariableManager {
     String VAR_ERROR = "error";
     String VAR_MSG   = "msg";
 
+    /** If this variable is set to false, all filters are disabled when translating. */
+    String VAR_RUNFILTERS   = "jspwiki.runFilters";
+
     /**
      *  Parses the link and finds a value.  This is essentially used once
      *  {@link org.apache.wiki.parser.LinkParsingOperations#isVariableLink(String) LinkParsingOperations#isVariableLink(String)}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
index b197d1d..ee7ccfb 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java
@@ -50,7 +50,7 @@ public class RPCHandler extends AbstractRPCHandler {
     /**
      *  Converts Java string into RPC string.
      */
-    private String toRPCString( String src )
+    private String toRPCString( final String src )
     {
         return TextUtil.urlEncodeUTF8( src );
     }
@@ -58,7 +58,7 @@ public class RPCHandler extends AbstractRPCHandler {
     /**
      *  Converts RPC string (UTF-8, url encoded) into Java string.
      */
-    private String fromRPCString( String src )
+    private String fromRPCString( final String src )
     {
         return TextUtil.urlDecodeUTF8( src );
     }
@@ -66,7 +66,7 @@ public class RPCHandler extends AbstractRPCHandler {
     /**
      *  Transforms a Java string into UTF-8.
      */
-    private byte[] toRPCBase64( String src )
+    private byte[] toRPCBase64( final String src )
     {
         return src.getBytes( StandardCharsets.UTF_8 );
     }
@@ -76,10 +76,10 @@ public class RPCHandler extends AbstractRPCHandler {
         return toRPCString(m_engine.getApplicationName());
     }
 
-    public Vector getAllPages() {
+    public Vector< String > getAllPages() {
         checkPermission( PagePermission.VIEW );
-        Collection< WikiPage > pages = m_engine.getPageManager().getRecentChanges();
-        Vector<String> result = new Vector<>();
+        final Collection< WikiPage > pages = m_engine.getPageManager().getRecentChanges();
+        final Vector< String > result = new Vector<>();
 
         for( final WikiPage p : pages ) {
             if( !( p instanceof Attachment ) ) {
@@ -94,13 +94,11 @@ public class RPCHandler extends AbstractRPCHandler {
      *  Encodes a single wiki page info into a Hashtable.
      */
     @Override
-    protected Hashtable<String,Object> encodeWikiPage( WikiPage page )
-    {
-        Hashtable<String, Object> ht = new Hashtable<>();
-
+    protected Hashtable<String,Object> encodeWikiPage( final WikiPage page ) {
+        final Hashtable<String, Object> ht = new Hashtable<>();
         ht.put( "name", toRPCString(page.getName()) );
 
-        Date d = page.getLastModified();
+        final Date d = page.getLastModified();
 
         //
         //  Here we reset the DST and TIMEZONE offsets of the
@@ -109,25 +107,27 @@ public class RPCHandler extends AbstractRPCHandler {
         //  from the XML-RPC thingy, except to manually adjust the date.
         //
 
-        Calendar cal = Calendar.getInstance();
+        final Calendar cal = Calendar.getInstance();
         cal.setTime( d );
         cal.add( Calendar.MILLISECOND,
                  - (cal.get( Calendar.ZONE_OFFSET ) +
-                    (cal.getTimeZone().inDaylightTime( d ) ? cal.get( Calendar.DST_OFFSET ) : 0 )) );
+                    (cal.getTimeZone().inDaylightTime( d ) ? cal.get( Calendar.DST_OFFSET ) : 0 ) ) );
 
         ht.put( "lastModified", cal.getTime() );
         ht.put( "version", page.getVersion() );
 
-        if( page.getAuthor() != null )
-        {
-            ht.put( "author", toRPCString(page.getAuthor()) );
+        if( page.getAuthor() != null ) {
+            ht.put( "author", toRPCString( page.getAuthor() ) );
         }
 
         return ht;
     }
 
+    /**
+     * {@inheritDoc}
+     */
     @Override
-    public Vector getRecentChanges( Date since ) {
+    public Vector< Hashtable< String, Object > > getRecentChanges( Date since ) {
         checkPermission( PagePermission.VIEW );
         final Set< WikiPage > pages = m_engine.getPageManager().getRecentChanges();
         final Vector< Hashtable< String, Object > > result = new Vector<>();
@@ -160,33 +160,26 @@ public class RPCHandler extends AbstractRPCHandler {
      *  @return Real page name, as Java string.
      *  @throws XmlRpcException, if there is something wrong with the page.
      */
-    private String parsePageCheckCondition( String pagename )
-        throws XmlRpcException
-    {
+    private String parsePageCheckCondition( String pagename ) throws XmlRpcException {
         pagename = fromRPCString( pagename );
 
-        if( !m_engine.getPageManager().wikiPageExists(pagename) )
-        {
+        if( !m_engine.getPageManager().wikiPageExists(pagename) ) {
             throw new XmlRpcException( ERR_NOPAGE, "No such page '"+pagename+"' found, o master." );
         }
 
-        WikiPage p = m_engine.getPageManager().getPage( pagename );
+        final WikiPage p = m_engine.getPageManager().getPage( pagename );
 
         checkPermission( PermissionFactory.getPagePermission( p, PagePermission.VIEW_ACTION ) );
 
         return pagename;
     }
 
-    public Hashtable getPageInfo( String pagename )
-        throws XmlRpcException
-    {
+    public Hashtable getPageInfo( String pagename ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
         return encodeWikiPage( m_engine.getPageManager().getPage(pagename) );
     }
 
-    public Hashtable getPageInfoVersion( String pagename, int version )
-        throws XmlRpcException
-    {
+    public Hashtable getPageInfoVersion( String pagename, int version ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
         return encodeWikiPage( m_engine.getPageManager().getPage( pagename, version ) );
@@ -197,17 +190,13 @@ public class RPCHandler extends AbstractRPCHandler {
         return toRPCBase64( text );
     }
 
-    public byte[] getPageVersion( String pagename, int version )
-        throws XmlRpcException
-    {
+    public byte[] getPageVersion( String pagename, final int version ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
         return toRPCBase64( m_engine.getPageManager().getPureText( pagename, version ) );
     }
 
-    public byte[] getPageHTML( String pagename )
-        throws XmlRpcException
-    {
+    public byte[] getPageHTML( String pagename ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
         return toRPCBase64( m_engine.getHTML( pagename ) );
@@ -219,28 +208,28 @@ public class RPCHandler extends AbstractRPCHandler {
         return toRPCBase64( m_engine.getHTML( pagename, version ) );
     }
 
-    public Vector listLinks( String pagename ) throws XmlRpcException {
+    public Vector< Hashtable< String, String > > listLinks( String pagename ) throws XmlRpcException {
         pagename = parsePageCheckCondition( pagename );
 
-        WikiPage page = m_engine.getPageManager().getPage( pagename );
-        String pagedata = m_engine.getPageManager().getPureText( page );
+        final WikiPage page = m_engine.getPageManager().getPage( pagename );
+        final String pagedata = m_engine.getPageManager().getPureText( page );
 
-        LinkCollector localCollector = new LinkCollector();
-        LinkCollector extCollector   = new LinkCollector();
-        LinkCollector attCollector   = new LinkCollector();
+        final LinkCollector localCollector = new LinkCollector();
+        final LinkCollector extCollector   = new LinkCollector();
+        final LinkCollector attCollector   = new LinkCollector();
 
-        WikiContext context = new WikiContext( m_engine, page );
+        final WikiContext context = new WikiContext( m_engine, page );
         context.setVariable( WikiEngine.PROP_REFSTYLE, "absolute" );
 
-        m_engine.textToHTML( context, pagedata, localCollector, extCollector, attCollector );
+        m_engine.getRenderingManager().textToHTML( context, pagedata, localCollector, extCollector, attCollector );
 
-        Vector<Hashtable<String, String>> result = new Vector<>();
+        final Vector< Hashtable< String, String > > result = new Vector<>();
 
         //
         //  Add local links.
         //
         for( final String link : localCollector.getLinks() ) {
-            Hashtable<String, String> ht = new Hashtable<>();
+            final Hashtable< String, String > ht = new Hashtable<>();
             ht.put( "page", toRPCString( link ) );
             ht.put( "type", LINK_LOCAL );
 
@@ -266,8 +255,8 @@ public class RPCHandler extends AbstractRPCHandler {
         //
         // Add links to inline attachments
         //
-        for( String link : attCollector.getLinks() ) {
-            Hashtable<String, String> ht = new Hashtable<>();
+        for( final String link : attCollector.getLinks() ) {
+            final Hashtable<String, String> ht = new Hashtable<>();
             ht.put( "page", toRPCString( link ) );
             ht.put( "type", LINK_LOCAL );
             ht.put( "href", context.getURL( WikiContext.ATTACH, link ) );
@@ -277,8 +266,8 @@ public class RPCHandler extends AbstractRPCHandler {
         //
         // External links don't need to be changed into XML-RPC strings, simply because URLs are by definition ASCII.
         //
-        for( String link : extCollector.getLinks() ) {
-            Hashtable<String, String> ht = new Hashtable<>();
+        for( final String link : extCollector.getLinks() ) {
+            final Hashtable<String, String> ht = new Hashtable<>();
             ht.put( "page", link );
             ht.put( "type", LINK_EXTERNAL );
             ht.put( "href", link );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
index b5a5c0f..fa1a451 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/xmlrpc/RPCHandlerUTF8.java
@@ -175,7 +175,7 @@ public class RPCHandlerUTF8 extends AbstractRPCHandler {
         final WikiContext context = new WikiContext( m_engine, page );
         context.setVariable( WikiEngine.PROP_REFSTYLE, "absolute" );
 
-        m_engine.textToHTML( context, pagedata, localCollector, extCollector, attCollector );
+        m_engine.getRenderingManager().textToHTML( context, pagedata, localCollector, extCollector, attCollector );
 
         final Vector< Hashtable< String, String > > result = new Vector<>();
 


[jspwiki] 09/26: move WikiEngine renderer-related property names to RenderingManager

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit f2c5378a22230d5c15474286727832ef2dcef5e7
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 00:27:48 2020 +0100

    move WikiEngine renderer-related property names to RenderingManager
    
    also, move default values of those properties for DefaultRenderingManager down to DefaultRenderingManager
---
 .../org/apache/wiki/render/DefaultRenderingManager.java     | 10 +++++++---
 .../main/java/org/apache/wiki/render/RenderingManager.java  | 13 ++++++-------
 2 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 5e63df5..4f55840 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -66,9 +66,13 @@ public class DefaultRenderingManager implements RenderingManager {
     /** The capacity of the caches, if you want something else, tweak ehcache.xml. */
     private static final int    DEFAULT_CACHESIZE     = 1_000;
     private static final String VERSION_DELIMITER     = "::";
-    private static final String PROP_PARSER           = "jspwiki.renderingManager.markupParser";
-    private static final String PROP_RENDERER         = "jspwiki.renderingManager.renderer";
-    private static final String PROP_WYSIWYG_RENDERER = "jspwiki.renderingManager.renderer.wysiwyg";
+
+    /** The name of the default renderer. */
+    private static final String DEFAULT_PARSER = JSPWikiMarkupParser.class.getName();
+    /** The name of the default renderer. */
+    private static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
+    /** The name of the default WYSIWYG renderer. */
+    private static final String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
 
     /** Stores the WikiDocuments that have been cached. */
     private Cache m_documentCache;
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index ea0d0e6..ad209cc 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -24,7 +24,6 @@ import org.apache.wiki.WikiEngine;
 import org.apache.wiki.api.exceptions.WikiException;
 import org.apache.wiki.event.WikiEventListener;
 import org.apache.wiki.modules.InternalModule;
-import org.apache.wiki.parser.JSPWikiMarkupParser;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.parser.WikiDocument;
 
@@ -44,14 +43,14 @@ import java.util.Properties;
  */
 public interface RenderingManager extends WikiEventListener, InternalModule {
 
-    /** The name of the default renderer. */
-    String DEFAULT_PARSER = JSPWikiMarkupParser.class.getName();
+    /** markup parser property. */
+    String PROP_PARSER           = "jspwiki.renderingManager.markupParser";
 
-    /** The name of the default renderer. */
-    String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
+    /** default renderer property. */
+    String PROP_RENDERER         = "jspwiki.renderingManager.renderer";
 
-    /** The name of the default WYSIWYG renderer. */
-    String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
+    /** default wysiwyg renderer property. */
+    String PROP_WYSIWYG_RENDERER = "jspwiki.renderingManager.renderer.wysiwyg";
 
     /** Name of the regular page cache. */
     String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";


[jspwiki] 04/26: small fix suggested by intellij

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit bee886f2be9bcc8e9ec2644280d82daaeadf269e
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Jan 11 22:47:25 2020 +0100

    small fix suggested by intellij
---
 jspwiki-main/src/main/java/org/apache/wiki/LinkCollector.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/LinkCollector.java b/jspwiki-main/src/main/java/org/apache/wiki/LinkCollector.java
index 1a83d07..1800b0d 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/LinkCollector.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/LinkCollector.java
@@ -40,7 +40,7 @@ public class LinkCollector implements StringTransmutator {
     /**
      * {@inheritDoc}
      */
-    public String mutate( WikiContext context, String in ) {
+    public String mutate( final WikiContext context, final String in ) {
         m_items.add( in );
         return in;
     }


[jspwiki] 12/26: JSPWIKI-120: move beautifyTitle and beautifyTitleNoBreak from WikiEngine to PageManager

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 1683e30e960db97addabf47b7292dd176fadb328
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 21:52:36 2020 +0100

    JSPWIKI-120: move beautifyTitle and beautifyTitleNoBreak from WikiEngine to PageManager
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  | 54 -------------
 .../apache/wiki/plugin/AbstractReferralPlugin.java |  2 +-
 .../org/apache/wiki/plugin/PageViewPlugin.java     |  2 +-
 .../apache/wiki/plugin/RecentChangesPlugin.java    | 93 ++++++++++------------
 .../main/java/org/apache/wiki/plugin/Search.java   | 20 ++---
 .../java/org/apache/wiki/plugin/WeblogPlugin.java  |  2 +-
 .../wiki/render/DefaultRenderingManager.java       | 40 ++++++++++
 .../org/apache/wiki/render/RenderingManager.java   | 26 +++++-
 .../java/org/apache/wiki/tags/PageNameTag.java     | 30 +++----
 .../org/apache/wiki/tags/ParentPageNameTag.java    | 48 +++++------
 .../test/java/org/apache/wiki/WikiEngineTest.java  | 45 -----------
 .../wiki/parser/JSPWikiMarkupParserTest.java       | 24 +++---
 .../apache/wiki/render/RenderingManagerTest.java   | 45 +++++++++++
 13 files changed, 204 insertions(+), 227 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
index 0cae15a..fb9bdc5 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -28,7 +28,6 @@ import org.apache.wiki.api.engine.PluginManager;
 import org.apache.wiki.api.exceptions.FilterException;
 import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.api.exceptions.WikiException;
-import org.apache.wiki.attachment.Attachment;
 import org.apache.wiki.attachment.AttachmentManager;
 import org.apache.wiki.auth.AuthenticationManager;
 import org.apache.wiki.auth.AuthorizationManager;
@@ -62,12 +61,6 @@ import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.PropertyReader;
 import org.apache.wiki.util.TextUtil;
 import org.apache.wiki.variables.VariableManager;
-import org.apache.wiki.workflow.Decision;
-import org.apache.wiki.workflow.DecisionRequiredException;
-import org.apache.wiki.workflow.Fact;
-import org.apache.wiki.workflow.Step;
-import org.apache.wiki.workflow.Workflow;
-import org.apache.wiki.workflow.WorkflowBuilder;
 import org.apache.wiki.workflow.WorkflowManager;
 
 import javax.servlet.ServletConfig;
@@ -82,7 +75,6 @@ import java.net.URLDecoder;
 import java.net.URLEncoder;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
-import java.security.Principal;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Date;
@@ -149,9 +141,6 @@ public class WikiEngine  {
     /** The name for the property which allows you to set the current reference style.  The value is {@value}. */
     public static final String PROP_REFSTYLE     = "jspwiki.referenceStyle";
 
-    /** Property name for the "spaces in titles" -hack. */
-    public static final String PROP_BEAUTIFYTITLE = "jspwiki.breakTitleWithSpaces";
-
     /** Property name for where the jspwiki work directory should be.
         If not specified, reverts to ${java.tmpdir}. */
     public static final String PROP_WORKDIR      = "jspwiki.workDir";
@@ -491,7 +480,6 @@ public class WikiEngine  {
 
         m_saveUserInfo   = TextUtil.getBooleanProperty( props, PROP_STOREUSERNAME, m_saveUserInfo );
         m_useUTF8        = StandardCharsets.UTF_8.name().equals( TextUtil.getStringProperty( props, PROP_ENCODING, StandardCharsets.ISO_8859_1.name() ) );
-        m_beautifyTitle  = TextUtil.getBooleanProperty( props, PROP_BEAUTIFYTITLE, m_beautifyTitle );
         m_templateDir    = TextUtil.getStringProperty( props, PROP_TEMPLATEDIR, "default" );
         enforceValidTemplateDirectory();
         m_frontPage      = TextUtil.getStringProperty( props, PROP_FRONTPAGE,   "Main" );
@@ -875,48 +863,6 @@ public class WikiEngine  {
     }
 
     /**
-     *  Beautifies the title of the page by appending spaces in suitable places, if the user has so decreed in the properties when
-     *  constructing this WikiEngine.  However, attachment names are only beautified by the name.
-     *
-     *  @param title The title to beautify
-     *  @return A beautified title (or, if beautification is off, returns the title without modification)
-     *  @since 1.7.11
-     */
-    public String beautifyTitle( final String title ) {
-        if( m_beautifyTitle ) {
-            try {
-                final Attachment att = m_attachmentManager.getAttachmentInfo( title );
-                if( att == null ) {
-                    return TextUtil.beautifyString( title );
-                }
-
-                final String parent = TextUtil.beautifyString( att.getParentName() );
-                return parent + "/" + att.getFileName();
-            } catch( final ProviderException e ) {
-                return title;
-            }
-        }
-
-        return title;
-    }
-
-    /**
-     *  Beautifies the title of the page by appending non-breaking spaces in suitable places.  This is really suitable only for HTML output,
-     *  as it uses the &amp;nbsp; -character.
-     *
-     *  @param title The title to beautify
-     *  @return A beautified title.
-     *  @since 2.1.127
-     */
-    public String beautifyTitleNoBreak( final String title ) {
-        if( m_beautifyTitle ) {
-            return TextUtil.beautifyString( title, "&nbsp;" );
-        }
-
-        return title;
-    }
-
-    /**
      *  Returns the correct page name, or null, if no such page can be found.  Aliases are considered. This method simply delegates to
      *  {@link org.apache.wiki.ui.CommandResolver#getFinalPageName(String)}.
      *  @since 2.0
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/AbstractReferralPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/AbstractReferralPlugin.java
index 5bc2871..3260cb8 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/AbstractReferralPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/AbstractReferralPlugin.java
@@ -385,7 +385,7 @@ public abstract class AbstractReferralPlugin implements WikiPlugin
             output.append( m_before );
 
             // Make a Wiki markup link. See TranslatorReader.
-            output.append( "[" + m_engine.beautifyTitle(value) + "|" + value + "]" );
+            output.append( "[" + m_engine.getRenderingManager().beautifyTitle(value) + "|" + value + "]" );
             count++;
         }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
index 266297a..12f312b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/PageViewPlugin.java
@@ -506,7 +506,7 @@ public class PageViewPlugin extends AbstractReferralPlugin implements WikiPlugin
 
                             if( use )
                             {
-                                args[1] = engine.beautifyTitle( name );
+                                args[1] = engine.getRenderingManager().beautifyTitle( name );
                                 args[2] = entry.getValue();
 
                                 fmt.format( args, buf, null );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/RecentChangesPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/RecentChangesPlugin.java
index f768f2a..d68b0db 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/RecentChangesPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/RecentChangesPlugin.java
@@ -40,7 +40,6 @@ import java.util.Calendar;
 import java.util.Collection;
 import java.util.Date;
 import java.util.GregorianCalendar;
-import java.util.Iterator;
 import java.util.Map;
 
 
@@ -75,26 +74,26 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
     /**
      * {@inheritDoc}
      */
-    public String execute( WikiContext context, Map<String, String> params ) throws PluginException {
-        int since = TextUtil.parseIntParameter( params.get( "since" ), DEFAULT_DAYS );
-        String   spacing  = "4";
-        boolean  showAuthor = true;
-        boolean  showChangenote = true;
-        String   tablewidth = "4";
+    public String execute( final WikiContext context, final Map< String, String > params ) throws PluginException {
+        final int since = TextUtil.parseIntParameter( params.get( "since" ), DEFAULT_DAYS );
+        String spacing  = "4";
+        boolean showAuthor = true;
+        boolean showChangenote = true;
+        String tablewidth = "4";
         
-        WikiEngine engine = context.getEngine();
+        final WikiEngine engine = context.getEngine();
 
         //
         //  Which format we want to see?
         //
-        if( "compact".equals( params.get(PARAM_FORMAT) ) ) {
+        if( "compact".equals( params.get( PARAM_FORMAT ) ) ) {
             spacing  = "0";
             showAuthor = false;
             showChangenote = false;
             tablewidth = "2";
         }
 
-        Calendar sincedate = new GregorianCalendar();
+        final Calendar sincedate = new GregorianCalendar();
         sincedate.add( Calendar.DAY_OF_MONTH, -since );
 
         log.debug("Calculating recent changes from "+sincedate.getTime());
@@ -107,24 +106,23 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
         if ( changes != null ) {
             Date olddate = new Date( 0 );
 
-            DateFormat fmt = getDateFormat( context, params );
-            DateFormat tfmt = getTimeFormat( context, params );
+            final DateFormat fmt = getDateFormat( context, params );
+            final DateFormat tfmt = getTimeFormat( context, params );
 
-            Element rt = XhtmlUtil.element( XHTML.table );
+            final Element rt = XhtmlUtil.element( XHTML.table );
             rt.setAttribute( XHTML.ATTR_class, "recentchanges" );
             rt.setAttribute( XHTML.ATTR_cellpadding, spacing );
-        
-            for( Iterator< WikiPage > i = changes.iterator(); i.hasNext(); ) {
-                WikiPage pageref = i.next();
-                Date lastmod = pageref.getLastModified();
+
+            for( final WikiPage pageref : changes ) {
+                final Date lastmod = pageref.getLastModified();
 
                 if( lastmod.before( sincedate.getTime() ) ) {
                     break;
                 }
-                
+
                 if( !isSameDay( lastmod, olddate ) ) {
-                    Element row = XhtmlUtil.element( XHTML.tr );
-                    Element col = XhtmlUtil.element( XHTML.td );
+                    final Element row = XhtmlUtil.element( XHTML.tr );
+                    final Element col = XhtmlUtil.element( XHTML.td );
                     col.setAttribute( XHTML.ATTR_colspan, tablewidth );
                     col.setAttribute( XHTML.ATTR_class, "date" );
                     col.addContent( XhtmlUtil.element( XHTML.b, fmt.format( lastmod ) ) );
@@ -134,16 +132,13 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
                     olddate = lastmod;
                 }
 
-                String href = context.getURL( pageref instanceof Attachment ? WikiContext.ATTACH : WikiContext.VIEW, 
-                                              pageref.getName() ) ;
-
-                Element link = XhtmlUtil.link( href, engine.beautifyTitle( pageref.getName() ) );
-
-                Element row = XhtmlUtil.element( XHTML.tr );
-                Element col = XhtmlUtil.element( XHTML.td );
+                final String href = context.getURL( pageref instanceof Attachment ? WikiContext.ATTACH : WikiContext.VIEW, pageref.getName() );
+                Element link = XhtmlUtil.link( href, engine.getRenderingManager().beautifyTitle( pageref.getName() ) );
+                final Element row = XhtmlUtil.element( XHTML.tr );
+                final Element col = XhtmlUtil.element( XHTML.td );
                 col.setAttribute( XHTML.ATTR_width, "30%" );
                 col.addContent( link );
-                
+
                 //
                 //  Add the direct link to the attachment info.
                 //
@@ -151,7 +146,7 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
                     link = XhtmlUtil.link( context.getURL( WikiContext.INFO, pageref.getName() ), null );
                     link.setAttribute( XHTML.ATTR_class, "infolink" );
 
-                    Element img = XhtmlUtil.img( context.getURL( WikiContext.NONE, "images/attachment_small.png" ), null );
+                    final Element img = XhtmlUtil.img( context.getURL( WikiContext.NONE, "images/attachment_small.png" ), null );
                     link.addContent( img );
 
                     col.addContent( link );
@@ -159,28 +154,28 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
 
                 row.addContent( col );
                 rt.addContent( row );
-                
+
                 if( pageref instanceof Attachment ) {
-                    Element td = XhtmlUtil.element( XHTML.td, tfmt.format( lastmod ) );
+                    final Element td = XhtmlUtil.element( XHTML.td, tfmt.format( lastmod ) );
                     td.setAttribute( XHTML.ATTR_class, "lastchange" );
                     row.addContent( td );
                 } else {
-                    Element infocol = XhtmlUtil.element( XHTML.td );
+                    final Element infocol = XhtmlUtil.element( XHTML.td );
                     infocol.setAttribute( XHTML.ATTR_class, "lastchange" );
-                    infocol.addContent( XhtmlUtil.link( context.getURL( WikiContext.DIFF, pageref.getName(), "r1=-1" ), tfmt.format( lastmod ) ) );
+                    infocol.addContent( XhtmlUtil.link( context.getURL( WikiContext.DIFF, pageref.getName(), "r1=-1" ),
+                                                        tfmt.format( lastmod ) ) );
                     row.addContent( infocol );
                 }
 
                 //
                 //  Display author information.
                 //
-
                 if( showAuthor ) {
-                    String author = pageref.getAuthor();
+                    final String author = pageref.getAuthor();
 
-                    Element authorinfo = XhtmlUtil.element( XHTML.td );
+                    final Element authorinfo = XhtmlUtil.element( XHTML.td );
                     authorinfo.setAttribute( XHTML.ATTR_class, "author" );
-                    
+
                     if( author != null ) {
                         if( engine.getPageManager().wikiPageExists( author ) ) {
                             authorinfo.addContent( XhtmlUtil.link( context.getURL( WikiContext.VIEW, author ), author ) );
@@ -189,7 +184,7 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
                         }
                     } else {
                         authorinfo.addContent( Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE )
-                                                          .getString( "common.unknownauthor" ) );
+                                .getString( "common.unknownauthor" ) );
                     }
 
                     row.addContent( authorinfo );
@@ -202,7 +197,7 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
                     td_changenote.setAttribute( XHTML.ATTR_class, "changenote" );
                     row.addContent( td_changenote );
                 }
-                
+
                 //  Revert note
 /*                
                 if( context.hasAdminPermissions() )
@@ -217,9 +212,9 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
     }
 
     
-    private boolean isSameDay( Date a, Date b ) {
-        Calendar aa = Calendar.getInstance(); aa.setTime( a );
-        Calendar bb = Calendar.getInstance(); bb.setTime( b );
+    private boolean isSameDay( final Date a, final Date b ) {
+        final Calendar aa = Calendar.getInstance(); aa.setTime( a );
+        final Calendar bb = Calendar.getInstance(); bb.setTime( b );
 
         return aa.get( Calendar.YEAR ) == bb.get( Calendar.YEAR ) 
             && aa.get( Calendar.DAY_OF_YEAR ) == bb.get( Calendar.DAY_OF_YEAR );
@@ -230,9 +225,8 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
     // locale, but that is at odds with the 1st version of this plugin. We seek to preserve the
     // behaviour of that first version, so to get the default format, the user must explicitly do
     // something like: dateFormat='' timeformat='' which is a odd, but probably okay.
-    private DateFormat getTimeFormat( WikiContext context, Map<String, String> params ) {
-        String formatString = get( params, DEFAULT_TIME_FORMAT, PARAM_TIME_FORMAT );
-
+    private DateFormat getTimeFormat( final WikiContext context, final Map< String, String > params ) {
+        final String formatString = get( params, DEFAULT_TIME_FORMAT, PARAM_TIME_FORMAT );
         if( StringUtils.isBlank( formatString ) ) {
             return Preferences.getDateFormat( context, TimeFormat.TIME );
         }
@@ -240,9 +234,8 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
         return new SimpleDateFormat( formatString );
     }
 
-    private DateFormat getDateFormat( WikiContext context, Map< String, String > params ) {
-        String formatString = get( params, DEFAULT_DATE_FORMAT, PARAM_DATE_FORMAT );
-        
+    private DateFormat getDateFormat( final WikiContext context, final Map< String, String > params ) {
+        final String formatString = get( params, DEFAULT_DATE_FORMAT, PARAM_DATE_FORMAT );
         if( StringUtils.isBlank( formatString ) ) {
             return Preferences.getDateFormat( context, TimeFormat.DATE );
         }
@@ -250,8 +243,8 @@ public class RecentChangesPlugin extends AbstractReferralPlugin implements WikiP
         return new SimpleDateFormat( formatString );
     }
     
-    private String get( Map< String, String > params, String defaultValue, String paramName ) {
-        String value = params.get( paramName );
+    private String get( final Map< String, String > params, final String defaultValue, final String paramName ) {
+        final String value = params.get( paramName );
         return value == null ? defaultValue : value;
     }
     
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/Search.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/Search.java
index c8ffb3b..571189d 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/Search.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/Search.java
@@ -46,32 +46,28 @@ import java.util.Map;
  *
  *  @since
  */
-public class Search implements WikiPlugin
-{
-    static Logger log = Logger.getLogger(Search.class);
+public class Search implements WikiPlugin {
+
+    private static final Logger log = Logger.getLogger(Search.class);
 
     /** Parameter name for setting the query string.  Value is <tt>{@value}</tt>. */
     public static final String PARAM_QUERY = "query";
 
-    /** Parameter name for setting the name of the set where the results are stored.
-     *  Value is <tt>{@value}</tt>.
-     */
+    /** Parameter name for setting the name of the set where the results are stored. Value is <tt>{@value}</tt>. */
     public static final String PARAM_SET   = "set";
 
     /** The default name of the result set. */
     public static final String DEFAULT_SETNAME = "_defaultSet";
 
-    /** The parameter name for setting the how many results will be fetched.
-     *  Value is <tt>{@value}</tt>.
-     */
+    /** The parameter name for setting the how many results will be fetched. Value is <tt>{@value}</tt>. */
     public static final String PARAM_MAX   = "max";
 
     /**
      * {@inheritDoc}
      */
     @SuppressWarnings("unchecked")
-    public String execute( WikiContext context, Map<String, String> params ) throws PluginException
-    {
+    @Override
+    public String execute( WikiContext context, Map<String, String> params ) throws PluginException {
         int maxItems = Integer.MAX_VALUE;
         Collection<SearchResult> results = null;
 
@@ -150,7 +146,7 @@ public class Search implements WikiPlugin
             name.setAttribute(XHTML.ATTR_width,"30%");
 
             name.addContent( XhtmlUtil.link(context.getURL( WikiContext.VIEW, sr.getPage().getName()),
-                    engine.beautifyTitle(sr.getPage().getName())) );
+                    engine.getRenderingManager().beautifyTitle(sr.getPage().getName())) );
 
             row.addContent(name);
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
index cb719e3..b62b58b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/WeblogPlugin.java
@@ -406,7 +406,7 @@ public class WeblogPlugin
         {
             if( engine.getPageManager().wikiPageExists(author) )
             {
-                author = "<a href=\""+entryCtx.getURL( WikiContext.VIEW, author )+"\">"+engine.beautifyTitle(author)+"</a>";
+                author = "<a href=\""+entryCtx.getURL( WikiContext.VIEW, author )+"\">"+engine.getRenderingManager().beautifyTitle(author)+"</a>";
             }
         }
         else
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 4f55840..d34405a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -24,7 +24,9 @@ import net.sf.ehcache.Element;
 import org.apache.log4j.Logger;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
+import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.api.exceptions.WikiException;
+import org.apache.wiki.attachment.Attachment;
 import org.apache.wiki.event.WikiEvent;
 import org.apache.wiki.event.WikiEventListener;
 import org.apache.wiki.event.WikiEventUtils;
@@ -35,6 +37,7 @@ import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.parser.WikiDocument;
 import org.apache.wiki.providers.WikiPageProvider;
 import org.apache.wiki.util.ClassUtil;
+import org.apache.wiki.util.TextUtil;
 
 import java.io.IOException;
 import java.io.StringReader;
@@ -62,6 +65,8 @@ public class DefaultRenderingManager implements RenderingManager {
 
     private WikiEngine m_engine;
     private boolean m_useCache = true;
+    /** If true, all titles will be cleaned. */
+    private boolean m_beautifyTitle = false;
 
     /** The capacity of the caches, if you want something else, tweak ehcache.xml. */
     private static final int    DEFAULT_CACHESIZE     = 1_000;
@@ -95,6 +100,7 @@ public class DefaultRenderingManager implements RenderingManager {
         log.info( "Using " + m_markupParserClass + " as markup parser." );
 
         m_useCache = "true".equals( properties.getProperty( PageManager.PROP_USECACHE ) );
+        m_beautifyTitle  = TextUtil.getBooleanProperty( properties, PROP_BEAUTIFYTITLE, m_beautifyTitle );
 
         if( m_useCache ) {
             final String documentCacheName = engine.getApplicationName() + "." + DOCUMENTCACHE_NAME;
@@ -138,6 +144,40 @@ public class DefaultRenderingManager implements RenderingManager {
     }
 
     /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String beautifyTitle( final String title ) {
+        if( m_beautifyTitle ) {
+            try {
+                final Attachment att = m_engine.getAttachmentManager().getAttachmentInfo( title );
+                if( att == null ) {
+                    return TextUtil.beautifyString( title );
+                }
+
+                final String parent = TextUtil.beautifyString( att.getParentName() );
+                return parent + "/" + att.getFileName();
+            } catch( final ProviderException e ) {
+                return title;
+            }
+        }
+
+        return title;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String beautifyTitleNoBreak( final String title ) {
+        if( m_beautifyTitle ) {
+            return TextUtil.beautifyString( title, "&nbsp;" );
+        }
+
+        return title;
+    }
+
+    /**
      *  {@inheritDoc}
      */
     @Override
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index ad209cc..36fef32 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -44,14 +44,16 @@ import java.util.Properties;
 public interface RenderingManager extends WikiEventListener, InternalModule {
 
     /** markup parser property. */
-    String PROP_PARSER           = "jspwiki.renderingManager.markupParser";
+    String PROP_PARSER = "jspwiki.renderingManager.markupParser";
 
     /** default renderer property. */
-    String PROP_RENDERER         = "jspwiki.renderingManager.renderer";
+    String PROP_RENDERER = "jspwiki.renderingManager.renderer";
 
     /** default wysiwyg renderer property. */
     String PROP_WYSIWYG_RENDERER = "jspwiki.renderingManager.renderer.wysiwyg";
 
+    String PROP_BEAUTIFYTITLE = "jspwiki.breakTitleWithSpaces";
+
     /** Name of the regular page cache. */
     String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
 
@@ -68,6 +70,26 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     void initialize( WikiEngine engine, Properties properties ) throws WikiException;
 
     /**
+     *  Beautifies the title of the page by appending spaces in suitable places, if the user has so decreed in the properties when
+     *  constructing this WikiEngine.  However, attachment names are only beautified by the name.
+     *
+     *  @param title The title to beautify
+     *  @return A beautified title (or, if beautification is off, returns the title without modification)
+     *  @since 1.7.11, moved to PageManager on 2.11.0
+     */
+    String beautifyTitle( final String title );
+
+    /**
+     *  Beautifies the title of the page by appending non-breaking spaces in suitable places.  This is really suitable only for HTML output,
+     *  as it uses the &amp;nbsp; -character.
+     *
+     *  @param title The title to beautify
+     *  @return A beautified title.
+     *  @since 2.1.127
+     */
+    String beautifyTitleNoBreak( final String title );
+
+    /**
      *  Returns the wiki Parser
      *  @param pagedata the page data
      *  @return A MarkupParser instance.
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/PageNameTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/PageNameTag.java
index 7727d1e..4372b04 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/PageNameTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/PageNameTag.java
@@ -18,41 +18,35 @@
  */
 package org.apache.wiki.tags;
 
-import java.io.IOException;
-
 import org.apache.wiki.WikiEngine;
 import org.apache.wiki.WikiPage;
 import org.apache.wiki.attachment.Attachment;
 import org.apache.wiki.util.TextUtil;
 
+import java.io.IOException;
+
 /**
  *  Returns the currently requested page name.
  *
  *  @since 2.0
  */
-public class PageNameTag
-    extends WikiTagBase
-{
+public class PageNameTag extends WikiTagBase {
+
     private static final long serialVersionUID = 0L;
 
-    public final int doWikiStartTag()
-        throws IOException
-    {
-        WikiEngine engine = m_wikiContext.getEngine();
-        WikiPage   page   = m_wikiContext.getPage();
+    public final int doWikiStartTag() throws IOException {
+        final WikiEngine engine = m_wikiContext.getEngine();
+        final WikiPage page = m_wikiContext.getPage();
 
-        if( page != null )
-        {
-            if( page instanceof Attachment )
-            {
+        if( page != null ) {
+            if( page instanceof Attachment ) {
                 pageContext.getOut().print( TextUtil.replaceEntities( ((Attachment)page).getFileName() ) );
-            }
-            else
-            {
-                pageContext.getOut().print( engine.beautifyTitle( m_wikiContext.getName() ) );
+            } else {
+                pageContext.getOut().print( engine.getRenderingManager().beautifyTitle( m_wikiContext.getName() ) );
             }
         }
 
         return SKIP_BODY;
     }
+
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/ParentPageNameTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/ParentPageNameTag.java
index 87fa96e..6f32d83 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/ParentPageNameTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/ParentPageNameTag.java
@@ -18,61 +18,49 @@
  */
 package org.apache.wiki.tags;
 
-import java.io.IOException;
-
 import org.apache.wiki.WikiEngine;
 import org.apache.wiki.WikiPage;
 import org.apache.wiki.attachment.Attachment;
 
+import java.io.IOException;
+
 /**
- *  Returns the parent of the currently requested page.  Weblog entries are recognized
- *  as subpages of the weblog page.
+ *  Returns the parent of the currently requested page.  Weblog entries are recognized as subpages of the weblog page.
  *
  *  @since 2.0
  */
-public class ParentPageNameTag
-    extends WikiTagBase
-{
+public class ParentPageNameTag extends WikiTagBase {
+
     private static final long serialVersionUID = 0L;
     
     /**
      * {@inheritDoc}
      */
     @Override
-    public final int doWikiStartTag()
-        throws IOException
-    {
-        WikiEngine engine = m_wikiContext.getEngine();
-        WikiPage   page   = m_wikiContext.getPage();
+    public final int doWikiStartTag() throws IOException {
+        final WikiEngine engine = m_wikiContext.getEngine();
+        final WikiPage page = m_wikiContext.getPage();
 
-        if( page != null )
-        {
-            if( page instanceof Attachment )
-            {
-                pageContext.getOut().print( engine.beautifyTitle( ((Attachment)page).getParentName()) );
-            }
-            else
-            {
+        if( page != null ) {
+            if( page instanceof Attachment ) {
+                pageContext.getOut().print( engine.getRenderingManager().beautifyTitle( ((Attachment)page).getParentName()) );
+            } else {
                 String name = page.getName();
-
-                int entrystart = name.indexOf("_blogentry_");
-
-                if( entrystart != -1 )
-                {
+                final int entrystart = name.indexOf("_blogentry_");
+                if( entrystart != -1 ) {
                     name = name.substring( 0, entrystart );
                 }
 
-                int commentstart = name.indexOf("_comments_");
-
-                if( commentstart != -1 )
-                {
+                final int commentstart = name.indexOf("_comments_");
+                if( commentstart != -1 ) {
                     name = name.substring( 0, commentstart );
                 }
 
-                pageContext.getOut().print( engine.beautifyTitle(name) );
+                pageContext.getOut().print( engine.getRenderingManager().beautifyTitle(name) );
             }
         }
 
         return SKIP_BODY;
     }
+
 }
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java b/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
index 779e7d7..7eb97c2 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/WikiEngineTest.java
@@ -125,51 +125,6 @@ public class WikiEngineTest {
         Assertions.assertEquals( "A%E2%89%A2%CE%91.", engine.encodeName(name) );
     }
 
-    @Test
-    public void testBeautifyTitle() {
-        final String src = "WikiNameThingy";
-        Assertions.assertEquals("Wiki Name Thingy", m_engine.beautifyTitle( src ) );
-    }
-
-    /**
-     *  Acronyms should be treated wisely.
-     */
-    @Test
-    public void testBeautifyTitleAcronym() {
-        final String src = "JSPWikiPage";
-        Assertions.assertEquals("JSP Wiki Page", m_engine.beautifyTitle( src ) );
-    }
-
-    /**
-     *  Acronyms should be treated wisely.
-     */
-    @Test
-    public void testBeautifyTitleAcronym2() {
-        final String src = "DELETEME";
-        Assertions.assertEquals("DELETEME", m_engine.beautifyTitle( src ) );
-    }
-
-    @Test
-    public void testBeautifyTitleAcronym3() {
-        final String src = "JSPWikiFAQ";
-        Assertions.assertEquals("JSP Wiki FAQ", m_engine.beautifyTitle( src ) );
-    }
-
-    @Test
-    public void testBeautifyTitleNumbers() {
-        final String src = "TestPage12";
-        Assertions.assertEquals("Test Page 12", m_engine.beautifyTitle( src ) );
-    }
-
-    /**
-     *  English articles too.
-     */
-    @Test
-    public void testBeautifyTitleArticle() {
-        final String src = "ThisIsAPage";
-        Assertions.assertEquals("This Is A Page", m_engine.beautifyTitle( src ) );
-    }
-
     /**
      *  Checks, if ReferenceManager is informed of new attachments.
      */
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/parser/JSPWikiMarkupParserTest.java b/jspwiki-main/src/test/java/org/apache/wiki/parser/JSPWikiMarkupParserTest.java
index b7c864a..36894d3 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/parser/JSPWikiMarkupParserTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/parser/JSPWikiMarkupParserTest.java
@@ -18,17 +18,7 @@
  */
 package org.apache.wiki.parser;
 
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Properties;
-import java.util.Vector;
-
-import javax.servlet.ServletException;
-
+import net.sf.ehcache.CacheManager;
 import org.apache.wiki.LinkCollector;
 import org.apache.wiki.TestEngine;
 import org.apache.wiki.WikiContext;
@@ -46,7 +36,15 @@ import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-import net.sf.ehcache.CacheManager;
+import javax.servlet.ServletException;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.Vector;
 
 public class JSPWikiMarkupParserTest
 {
@@ -806,7 +804,7 @@ public class JSPWikiMarkupParserTest
 
         testEngine2.getAttachmentManager().storeAttachment( att, testEngine.makeAttachmentFile() );
 
-        String src = "["+testEngine2.beautifyTitle("TestPage/TestAtt.txt")+"]";
+        String src = "["+testEngine2.getRenderingManager().beautifyTitle("TestPage/TestAtt.txt")+"]";
 
         Assertions.assertEquals( "<a class=\"attachment\" href=\"/test/attach/TestPage/TestAtt.txt\">Test Page/TestAtt.txt</a>"+
                       "<a href=\"/test/PageInfo.jsp?page=TestPage/TestAtt.txt\" class=\"infolink\"><img src=\"/test/images/attachment_small.png\" border=\"0\" alt=\"(info)\" /></a>",
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
index 35e2948..3ba8e6d 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/render/RenderingManagerTest.java
@@ -40,6 +40,51 @@ public class RenderingManagerTest {
         CacheManager.getInstance().removeAllCaches();
     }
 
+    @Test
+    public void testBeautifyTitle() {
+        final String src = "WikiNameThingy";
+        Assertions.assertEquals("Wiki Name Thingy", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
+    /**
+     *  Acronyms should be treated wisely.
+     */
+    @Test
+    public void testBeautifyTitleAcronym() {
+        final String src = "JSPWikiPage";
+        Assertions.assertEquals("JSP Wiki Page", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
+    /**
+     *  Acronyms should be treated wisely.
+     */
+    @Test
+    public void testBeautifyTitleAcronym2() {
+        final String src = "DELETEME";
+        Assertions.assertEquals("DELETEME", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
+    @Test
+    public void testBeautifyTitleAcronym3() {
+        final String src = "JSPWikiFAQ";
+        Assertions.assertEquals("JSP Wiki FAQ", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
+    @Test
+    public void testBeautifyTitleNumbers() {
+        final String src = "TestPage12";
+        Assertions.assertEquals("Test Page 12", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
+    /**
+     *  English articles too.
+     */
+    @Test
+    public void testBeautifyTitleArticle() {
+        final String src = "ThisIsAPage";
+        Assertions.assertEquals("This Is A Page", m_engine.getRenderingManager().beautifyTitle( src ) );
+    }
+
     /**
      * Tests the relative speed of the DOM cache with respect to
      * page being parsed every single time.


[jspwiki] 24/26: moved MarkupParser#cleanLink( String, String ) to TextUtil.cleanString( String, String )

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit b39c263a418ec38f91db66871868617ae9db1ed7
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 23:58:37 2020 +0100

    moved MarkupParser#cleanLink( String, String ) to TextUtil.cleanString( String, String )
    
    also moved constants PUNCTUATION_CHARS_ALLOWED and LEGACY_CHARS_ALLOWED from MarkupParser to TextUtil. The objetive of this move is to be able to break package / class cycles between WikiEngine and MarkupParser
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  |   3 +-
 .../java/org/apache/wiki/parser/MarkupParser.java  |  67 +-----
 .../apache/wiki/search/LuceneSearchProvider.java   | 264 ++++++++-------------
 .../main/java/org/apache/wiki/util/TextUtil.java   |  72 +++++-
 4 files changed, 175 insertions(+), 231 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
index 9b522e4..2189371 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -40,7 +40,6 @@ import org.apache.wiki.event.WikiEventManager;
 import org.apache.wiki.event.WikiPageEvent;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.pages.PageManager;
-import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.references.ReferenceManager;
 import org.apache.wiki.render.RenderingManager;
 import org.apache.wiki.rss.RSSGenerator;
@@ -848,7 +847,7 @@ public class WikiEngine  {
     // FIXME: Should use servlet context as a default instead of a constant.
     public String getApplicationName() {
         final String appName = TextUtil.getStringProperty( m_properties, PROP_APPNAME, Release.APPNAME );
-        return MarkupParser.cleanLink( appName );
+        return TextUtil.cleanString( appName, TextUtil.PUNCTUATION_CHARS_ALLOWED );
     }
 
     /**
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
index 0bcdad6..4acb8a7 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
@@ -26,6 +26,7 @@ import org.apache.oro.text.regex.PatternCompiler;
 import org.apache.wiki.StringTransmutator;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
+import org.apache.wiki.util.TextUtil;
 import org.jdom2.Element;
 
 import java.io.BufferedReader;
@@ -80,13 +81,6 @@ public abstract class MarkupParser {
     /** If set to "true", all external links are tagged with 'rel="nofollow"' */
     public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow";
 
-    /** Lists all punctuation characters allowed in WikiMarkup. These will not be cleaned away. This is for compatibility for older versions
-        of JSPWiki. */
-    protected static final String LEGACY_CHARS_ALLOWED = "._";
-
-    /** Lists all punctuation characters allowed in page names. */
-    public static final String PUNCTUATION_CHARS_ALLOWED = " ()&+,-=._$";
-
     public static final String HASHLINK = "hashlink";
 
     /** Name of the outlink image; relative path to the JSPWiki directory. */
@@ -341,7 +335,7 @@ public abstract class MarkupParser {
      *  @since 2.0
      */
     public static String cleanLink( final String link ) {
-        return cleanLink( link, PUNCTUATION_CHARS_ALLOWED );
+        return TextUtil.cleanString( link, TextUtil.PUNCTUATION_CHARS_ALLOWED );
     }
 
     /**
@@ -354,62 +348,7 @@ public abstract class MarkupParser {
      *  @since 2.6
      */
     public static String wikifyLink( final String link ) {
-        return cleanLink( link, LEGACY_CHARS_ALLOWED );
-    }
-
-    /**
-     *  Cleans a Wiki name based on a list of characters.  Also, any multiple whitespace is collapsed into a single space, and any
-     *  leading or trailing space is removed.
-     *
-     *  @param link Link to be cleared. Null is safe, and causes this to return null.
-     *  @param allowedChars Characters which are allowed in the string.
-     *  @return A cleaned link.
-     *
-     *  @since 2.6
-     */
-    public static String cleanLink( String link, final String allowedChars ) {
-        if( link == null ) {
-            return null;
-        }
-
-        link = link.trim();
-        final StringBuilder clean = new StringBuilder( link.length() );
-
-        //  Remove non-alphanumeric characters that should not be put inside WikiNames.  Note that all valid Unicode letters are
-        //  considered okay for WikiNames. It is the problem of the WikiPageProvider to take care of actually storing that information.
-        //
-        //  Also capitalize things, if necessary.
-
-        boolean isWord = true;  // If true, we've just crossed a word boundary
-        boolean wasSpace = false;
-        for( int i = 0; i < link.length(); i++ ) {
-            char ch = link.charAt(i);
-
-            //  Cleans away repetitive whitespace and only uses the first one.
-            if( Character.isWhitespace(ch) ) {
-                if( wasSpace ) {
-                    continue;
-                }
-
-                wasSpace = true;
-            } else {
-                wasSpace = false;
-            }
-
-            //  Check if it is allowed to use this char, and capitalize, if necessary.
-            if( Character.isLetterOrDigit( ch ) || allowedChars.indexOf( ch ) != -1 ) {
-                // Is a letter
-                if( isWord ) {
-                    ch = Character.toUpperCase( ch );
-                }
-                clean.append( ch );
-                isWord = false;
-            } else {
-                isWord = true;
-            }
-        }
-
-        return clean.toString();
+        return TextUtil.cleanString( link, TextUtil.LEGACY_CHARS_ALLOWED );
     }
 
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java
index e6e4711..1cfcc30 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java
@@ -59,7 +59,6 @@ import org.apache.wiki.attachment.Attachment;
 import org.apache.wiki.attachment.AttachmentManager;
 import org.apache.wiki.auth.AuthorizationManager;
 import org.apache.wiki.auth.permissions.PagePermission;
-import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.providers.WikiPageProvider;
 import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.FileUtil;
@@ -98,13 +97,12 @@ public class LuceneSearchProvider implements SearchProvider {
 
     /** Which analyzer to use.  Default is StandardAnalyzer. */
     public static final String PROP_LUCENE_ANALYZER      = "jspwiki.lucene.analyzer";
-
     private static final String PROP_LUCENE_INDEXDELAY   = "jspwiki.lucene.indexdelay";
     private static final String PROP_LUCENE_INITIALDELAY = "jspwiki.lucene.initialdelay";
 
     private String m_analyzerClass = "org.apache.lucene.analysis.standard.ClassicAnalyzer";
 
-    private static final String LUCENE_DIR             = "lucene";
+    private static final String LUCENE_DIR = "lucene";
 
     /** These attachment file suffixes will be indexed. */
     public static final String[] SEARCHABLE_FILE_SUFFIXES = new String[] { ".txt", ".ini", ".xml", ".html", "htm", ".mm", ".htm",
@@ -118,8 +116,8 @@ public class LuceneSearchProvider implements SearchProvider {
     protected static final String LUCENE_PAGE_NAME     = "name";
     protected static final String LUCENE_PAGE_KEYWORDS = "keywords";
 
-    private String           m_luceneDirectory;
-    protected List<Object[]> m_updates = Collections.synchronizedList( new ArrayList<>() ); 
+    private String m_luceneDirectory;
+    protected final List< Object[] > m_updates = Collections.synchronizedList( new ArrayList<>() );
 
     /** Maximum number of fragments from search matches. */
     private static final int MAX_FRAGMENTS = 3;
@@ -127,60 +125,49 @@ public class LuceneSearchProvider implements SearchProvider {
     /** The maximum number of hits to return from searches. */
     public static final int MAX_SEARCH_HITS = 99_999;
     
-    private static String c_punctuationSpaces = StringUtils.repeat(" ", MarkupParser.PUNCTUATION_CHARS_ALLOWED.length() );
+    private static String c_punctuationSpaces = StringUtils.repeat(" ", TextUtil.PUNCTUATION_CHARS_ALLOWED.length() );
 
     /**
      *  {@inheritDoc}
      */
     @Override
-    public void initialize(WikiEngine engine, Properties props)
-            throws NoRequiredPropertyException, IOException
-    {
+    public void initialize( final WikiEngine engine, final Properties props ) throws NoRequiredPropertyException, IOException  {
         m_engine = engine;
         searchExecutor = Executors.newCachedThreadPool();
 
         m_luceneDirectory = engine.getWorkDir()+File.separator+LUCENE_DIR;
 
-        int initialDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY );
-        int indexDelay   = TextUtil.getIntegerProperty( props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY );
+        final int initialDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY );
+        final int indexDelay   = TextUtil.getIntegerProperty( props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY );
 
         m_analyzerClass = TextUtil.getStringProperty( props, PROP_LUCENE_ANALYZER, m_analyzerClass );
         // FIXME: Just to be simple for now, we will do full reindex
         // only if no files are in lucene directory.
 
-        File dir = new File(m_luceneDirectory);
-
+        final File dir = new File(m_luceneDirectory);
         log.info("Lucene enabled, cache will be in: "+dir.getAbsolutePath());
-
-        try
-        {
-            if( !dir.exists() )
-            {
+        try {
+            if( !dir.exists() ) {
                 dir.mkdirs();
             }
 
-            if( !dir.exists() || !dir.canWrite() || !dir.canRead() )
-            {
+            if( !dir.exists() || !dir.canWrite() || !dir.canRead() ) {
                 log.error("Cannot write to Lucene directory, disabling Lucene: "+dir.getAbsolutePath());
                 throw new IOException( "Invalid Lucene directory." );
             }
 
-            String[] filelist = dir.list();
-
-            if( filelist == null )
-            {
+            final String[] filelist = dir.list();
+            if( filelist == null ) {
                 throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath());
             }
-        }
-        catch ( IOException e )
-        {
+        } catch( final IOException e ) {
             log.error("Problem while creating Lucene index - not using Lucene.", e);
         }
 
         // Start the Lucene update thread, which waits first
         // for a little while before starting to go through
         // the Lucene "pages that need updating".
-        LuceneUpdater updater = new LuceneUpdater( m_engine, this, initialDelay, indexDelay );
+        final LuceneUpdater updater = new LuceneUpdater( m_engine, this, initialDelay, indexDelay );
         updater.start();
     }
 
@@ -200,10 +187,8 @@ public class LuceneSearchProvider implements SearchProvider {
      *  @throws IOException If there's a problem during indexing
      */
     protected void doFullLuceneReindex() throws IOException {
-        File dir = new File(m_luceneDirectory);
-
-        String[] filelist = dir.list();
-
+        final File dir = new File(m_luceneDirectory);
+        final String[] filelist = dir.list();
         if( filelist == null ) {
             throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath());
         }
@@ -213,47 +198,45 @@ public class LuceneSearchProvider implements SearchProvider {
                 //
                 //  No files? Reindex!
                 //
-                Date start = new Date();
+                final Date start = new Date();
 
                 log.info("Starting Lucene reindexing, this can take a couple of minutes...");
 
-                Directory luceneDir = new SimpleFSDirectory( dir.toPath() );
-                try( IndexWriter writer = getIndexWriter( luceneDir ) )
-                {
-                    Collection< WikiPage > allPages = m_engine.getPageManager().getAllPages();
-                    for( WikiPage page : allPages ) {
-                        
+                final Directory luceneDir = new SimpleFSDirectory( dir.toPath() );
+                try( final IndexWriter writer = getIndexWriter( luceneDir ) ) {
+                    final Collection< WikiPage > allPages = m_engine.getPageManager().getAllPages();
+                    for( final WikiPage page : allPages ) {
                         try {
-                            String text = m_engine.getPageManager().getPageText( page.getName(), WikiProvider.LATEST_VERSION );
+                            final String text = m_engine.getPageManager().getPageText( page.getName(), WikiProvider.LATEST_VERSION );
                             luceneIndexPage( page, text, writer );
-                        } catch( IOException e ) {
+                        } catch( final IOException e ) {
                             log.warn( "Unable to index page " + page.getName() + ", continuing to next ", e );
                         }
                     }
 
-                    Collection< Attachment > allAttachments = m_engine.getAttachmentManager().getAllAttachments();
-                    for( Attachment att : allAttachments ) {
+                    final Collection< Attachment > allAttachments = m_engine.getAttachmentManager().getAllAttachments();
+                    for( final Attachment att : allAttachments ) {
                         try {
-                            String text = getAttachmentContent( att.getName(), WikiProvider.LATEST_VERSION );
+                            final String text = getAttachmentContent( att.getName(), WikiProvider.LATEST_VERSION );
                             luceneIndexPage( att, text, writer );
-                        } catch( IOException e ) {
+                        } catch( final IOException e ) {
                             log.warn( "Unable to index attachment " + att.getName() + ", continuing to next", e );
                         }
                     }
 
                 }
 
-                Date end = new Date();
+                final Date end = new Date();
                 log.info( "Full Lucene index finished in " + (end.getTime() - start.getTime()) + " milliseconds." );
             } else {
                 log.info("Files found in Lucene directory, not reindexing.");
             }
-        } catch ( IOException e ) {
+        } catch ( final IOException e ) {
             log.error("Problem while creating Lucene index - not using Lucene.", e);
-        } catch ( ProviderException e ) {
+        } catch ( final ProviderException e ) {
             log.error("Problem reading pages while creating Lucene index (JSPWiki won't start.)", e);
             throw new IllegalArgumentException("unable to create Lucene index");
-        } catch( Exception e ) {
+        } catch( final Exception e ) {
             log.error("Unable to start lucene",e);
         }
 
@@ -268,24 +251,17 @@ public class LuceneSearchProvider implements SearchProvider {
      *  
      *  @return the content of the Attachment as a String.
      */
-    protected String getAttachmentContent( String attachmentName, int version )
-    {
-        AttachmentManager mgr = m_engine.getAttachmentManager();
-
-        try
-        {
-            Attachment att = mgr.getAttachmentInfo( attachmentName, version );
+    protected String getAttachmentContent( final String attachmentName, final int version ) {
+        final AttachmentManager mgr = m_engine.getAttachmentManager();
+        try {
+            final Attachment att = mgr.getAttachmentInfo( attachmentName, version );
             //FIXME: Find out why sometimes att is null
-            if(att != null)
-            {
+            if( att != null ) {
                 return getAttachmentContent( att );
             }
-        }
-        catch (ProviderException e)
-        {
+        } catch( final ProviderException e ) {
             log.error("Attachment cannot be loaded", e);
         }
-        // Something was wrong, no result is returned.
         return null;
     }
 
@@ -295,29 +271,26 @@ public class LuceneSearchProvider implements SearchProvider {
      * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing.
      * This should be replaced /moved to Attachment search providers or some other 'pluggable' way to search attachments
      */
-    protected String getAttachmentContent( Attachment att )
-    {
-        AttachmentManager mgr = m_engine.getAttachmentManager();
+    protected String getAttachmentContent( final Attachment att ) {
+        final AttachmentManager mgr = m_engine.getAttachmentManager();
         //FIXME: Add attachment plugin structure
 
-        String filename = att.getFileName();
+        final String filename = att.getFileName();
 
         boolean searchSuffix = false;
-        for( String suffix : SEARCHABLE_FILE_SUFFIXES )
-        {
-            if( filename.endsWith( suffix ) )
-            {
+        for( final String suffix : SEARCHABLE_FILE_SUFFIXES ) {
+            if( filename.endsWith( suffix ) ) {
                 searchSuffix = true;
+                break;
             }
         }
 
         String out = filename;
-        if( searchSuffix )
-        {
+        if( searchSuffix ) {
             try( final InputStream attStream = mgr.getAttachmentStream( att ); final StringWriter sout = new StringWriter() ) {
                 FileUtil.copyContents( new InputStreamReader( attStream ), sout );
                 out = out + " " + sout.toString();
-            } catch( ProviderException | IOException e ) {
+            } catch( final ProviderException | IOException e ) {
                 log.error("Attachment cannot be loaded", e);
             }
         }
@@ -350,19 +323,13 @@ public class LuceneSearchProvider implements SearchProvider {
         log.debug("Done updating Lucene index for page '" + page.getName() + "'.");
     }
 
-
-    private Analyzer getLuceneAnalyzer() throws ProviderException
-    {
-        try
-        {
-            Class< ? > clazz = ClassUtil.findClass( "", m_analyzerClass );
-            Constructor< ? > constructor = clazz.getConstructor();
-            Analyzer analyzer = (Analyzer) constructor.newInstance();
-            return analyzer;
-        }
-        catch( Exception e )
-        {
-            String msg = "Could not get LuceneAnalyzer class " + m_analyzerClass + ", reason: ";
+    private Analyzer getLuceneAnalyzer() throws ProviderException {
+        try {
+            final Class< ? > clazz = ClassUtil.findClass( "", m_analyzerClass );
+            final Constructor< ? > constructor = clazz.getConstructor();
+            return ( Analyzer )constructor.newInstance();
+        } catch( final Exception e ) {
+            final String msg = "Could not get LuceneAnalyzer class " + m_analyzerClass + ", reason: ";
             log.error( msg, e );
             throw new ProviderException( msg + e );
         }
@@ -399,13 +366,8 @@ public class LuceneSearchProvider implements SearchProvider {
         doc.add( field );
 
         // Allow searching by page name. Both beautified and raw
-        final String unTokenizedTitle = StringUtils.replaceChars( page.getName(),
-                                                                  MarkupParser.PUNCTUATION_CHARS_ALLOWED,
-                                                                  c_punctuationSpaces );
-
-        field = new Field( LUCENE_PAGE_NAME,
-                           TextUtil.beautifyString( page.getName() ) + " " + unTokenizedTitle,
-                           TextField.TYPE_STORED );
+        final String unTokenizedTitle = StringUtils.replaceChars( page.getName(), TextUtil.PUNCTUATION_CHARS_ALLOWED, c_punctuationSpaces );
+        field = new Field( LUCENE_PAGE_NAME, TextUtil.beautifyString( page.getName() ) + " " + unTokenizedTitle, TextField.TYPE_STORED );
         doc.add( field );
 
         // Allow searching by authorname
@@ -446,7 +408,7 @@ public class LuceneSearchProvider implements SearchProvider {
     @Override
     public void pageRemoved( final WikiPage page ) {
         try( final Directory luceneDir = new SimpleFSDirectory( new File( m_luceneDirectory ).toPath() );
-             final IndexWriter writer = getIndexWriter( luceneDir ); ) {
+             final IndexWriter writer = getIndexWriter( luceneDir ) ) {
             final Query query = new TermQuery( new Term( LUCENE_ID, page.getName() ) );
             writer.deleteDocuments( query );
         } catch ( final Exception e ) {
@@ -454,13 +416,10 @@ public class LuceneSearchProvider implements SearchProvider {
         }
     }
     
-    IndexWriter getIndexWriter( Directory luceneDir ) throws IOException, ProviderException {
-        IndexWriterConfig writerConfig = new IndexWriterConfig( getLuceneAnalyzer() );
+    IndexWriter getIndexWriter(final  Directory luceneDir ) throws IOException, ProviderException {
+        final IndexWriterConfig writerConfig = new IndexWriterConfig( getLuceneAnalyzer() );
         writerConfig.setOpenMode( OpenMode.CREATE_OR_APPEND );
-        IndexWriter writer = new IndexWriter( luceneDir, writerConfig );
-        
-        // writer.setInfoStream( System.out );
-        return writer;
+        return new IndexWriter( luceneDir, writerConfig );
     }
     
     /**
@@ -469,12 +428,11 @@ public class LuceneSearchProvider implements SearchProvider {
      *  @param page WikiPage to add to the update queue.
      */
     @Override
-    public void reindexPage( WikiPage page ) {
+    public void reindexPage( final WikiPage page ) {
         if( page != null ) {
-            String text;
+            final String text;
 
             // TODO: Think if this was better done in the thread itself?
-
             if( page instanceof Attachment ) {
                 text = getAttachmentContent( (Attachment) page );
             } else {
@@ -483,10 +441,10 @@ public class LuceneSearchProvider implements SearchProvider {
 
             if( text != null ) {
                 // Add work item to m_updates queue.
-                Object[] pair = new Object[2];
+                final Object[] pair = new Object[2];
                 pair[0] = page;
                 pair[1] = text;
-                m_updates.add(pair);
+                m_updates.add( pair );
                 log.debug("Scheduling page " + page.getName() + " for index update");
             }
         }
@@ -496,7 +454,7 @@ public class LuceneSearchProvider implements SearchProvider {
      *  {@inheritDoc}
      */
     @Override
-    public Collection< SearchResult > findPages( String query, WikiContext wikiContext ) throws ProviderException {
+    public Collection< SearchResult > findPages( final String query, final WikiContext wikiContext ) throws ProviderException {
         return findPages( query, FLAG_CONTEXTS, wikiContext );
     }
 
@@ -528,44 +486,40 @@ public class LuceneSearchProvider implements SearchProvider {
             if( (flags & FLAG_CONTEXTS) != 0 ) {
                 highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"),
                                               new SimpleHTMLEncoder(),
-                                              new QueryScorer(luceneQuery));
+                                              new QueryScorer( luceneQuery ) );
             }
 
             final ScoreDoc[] hits = searcher.search(luceneQuery, MAX_SEARCH_HITS).scoreDocs;
             final AuthorizationManager mgr = m_engine.getAuthorizationManager();
 
             list = new ArrayList<>(hits.length);
-            for ( int curr = 0; curr < hits.length; curr++ ) {
-                int docID = hits[curr].doc;
-                Document doc = searcher.doc( docID );
-                String pageName = doc.get(LUCENE_ID);
-                WikiPage page = m_engine.getPageManager().getPage(pageName, WikiPageProvider.LATEST_VERSION);
+            for( final ScoreDoc hit : hits ) {
+                final int docID = hit.doc;
+                final Document doc = searcher.doc( docID );
+                final String pageName = doc.get( LUCENE_ID );
+                final WikiPage page = m_engine.getPageManager().getPage( pageName, WikiPageProvider.LATEST_VERSION );
 
                 if( page != null ) {
-                    if( page instanceof Attachment ) {
-                        // Currently attachments don't look nice on the search-results page
-                        // When the search-results are cleaned up this can be enabled again.
-                    }
-
                     final PagePermission pp = new PagePermission( page, PagePermission.VIEW_ACTION );
-	                if( mgr.checkPermission( wikiContext.getWikiSession(), pp ) ) {
-                        final int score = (int)(hits[curr].score * 100);
-
-	                    // Get highlighted search contexts
-	                    final String text = doc.get(LUCENE_PAGE_CONTENTS);
-	
-	                    String[] fragments = new String[0];
-	                    if( text != null && highlighter != null ) {
-	                        TokenStream tokenStream = getLuceneAnalyzer().tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text));
-	                        fragments = highlighter.getBestFragments(tokenStream, text, MAX_FRAGMENTS);
-	                    }
+                    if( mgr.checkPermission( wikiContext.getWikiSession(), pp ) ) {
+                        final int score = ( int )( hit.score * 100 );
+
+                        // Get highlighted search contexts
+                        final String text = doc.get( LUCENE_PAGE_CONTENTS );
+
+                        String[] fragments = new String[ 0 ];
+                        if( text != null && highlighter != null ) {
+                            final TokenStream tokenStream = getLuceneAnalyzer()
+                                    .tokenStream( LUCENE_PAGE_CONTENTS, new StringReader( text ) );
+                            fragments = highlighter.getBestFragments( tokenStream, text, MAX_FRAGMENTS );
+                        }
 
                         final SearchResult result = new SearchResultImpl( page, score, fragments );
-	                    list.add(result);
-	                }
+                        list.add( result );
+                    }
                 } else {
-                    log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache");
-                    pageRemoved(new WikiPage( m_engine, pageName ));
+                    log.error( "Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache" );
+                    pageRemoved( new WikiPage( m_engine, pageName ) );
                 }
             }
         } catch( final IOException e ) {
@@ -592,8 +546,7 @@ public class LuceneSearchProvider implements SearchProvider {
     /**
      * Updater thread that updates Lucene indexes.
      */
-    private static final class LuceneUpdater extends WikiBackgroundThread
-    {
+    private static final class LuceneUpdater extends WikiBackgroundThread {
         protected static final int INDEX_DELAY    = 5;
         protected static final int INITIAL_DELAY = 60;
         private final LuceneSearchProvider m_provider;
@@ -602,47 +555,39 @@ public class LuceneSearchProvider implements SearchProvider {
 
         private WatchDog m_watchdog;
 
-        private LuceneUpdater( WikiEngine engine, LuceneSearchProvider provider,
-                               int initialDelay, int indexDelay )
-        {
+        private LuceneUpdater( final WikiEngine engine, final LuceneSearchProvider provider, final int initialDelay, final int indexDelay ) {
             super( engine, indexDelay );
             m_provider = provider;
+            m_initialDelay = initialDelay;
             setName("JSPWiki Lucene Indexer");
         }
 
         @Override
-        public void startupTask() throws Exception
-        {
+        public void startupTask() throws Exception {
             m_watchdog = getEngine().getCurrentWatchDog();
 
             // Sleep initially...
-            try
-            {
+            try {
                 Thread.sleep( m_initialDelay * 1000L );
-            }
-            catch( InterruptedException e )
-            {
+            } catch( final InterruptedException e ) {
                 throw new InternalWikiException("Interrupted while waiting to start.", e);
             }
 
-            m_watchdog.enterState("Full reindex");
+            m_watchdog.enterState( "Full reindex" );
             // Reindex everything
             m_provider.doFullLuceneReindex();
             m_watchdog.exitState();
         }
 
         @Override
-        public void backgroundTask() throws Exception
-        {
+        public void backgroundTask() {
             m_watchdog.enterState("Emptying index queue", 60);
 
-            synchronized ( m_provider.m_updates )
-            {
-                while( m_provider.m_updates.size() > 0 )
-                {
-                    Object[] pair = m_provider.m_updates.remove(0);
-                    WikiPage page = ( WikiPage ) pair[0];
-                    String text = ( String ) pair[1];
+            synchronized ( m_provider.m_updates ) {
+                while( m_provider.m_updates.size() > 0 ) {
+                    final Object[] pair = m_provider.m_updates.remove(0);
+                    final WikiPage page = ( WikiPage ) pair[0];
+                    final String text = ( String ) pair[1];
                     m_provider.updateLuceneIndex(page, text);
                 }
             }
@@ -653,16 +598,14 @@ public class LuceneSearchProvider implements SearchProvider {
     }
 
     // FIXME: This class is dumb; needs to have a better implementation
-    private static class SearchResultImpl
-        implements SearchResult
-    {
+    private static class SearchResultImpl implements SearchResult {
+
         private WikiPage m_page;
         private int      m_score;
         private String[] m_contexts;
 
-        public SearchResultImpl( WikiPage page, int score, String[] contexts )
-        {
-            m_page  = page;
+        public SearchResultImpl( final WikiPage page, final int score, final String[] contexts ) {
+            m_page = page;
             m_score = score;
             m_contexts = contexts != null ? contexts.clone() : null;
         }
@@ -689,4 +632,5 @@ public class LuceneSearchProvider implements SearchProvider {
             return m_contexts;
         }
     }
+
 }
diff --git a/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java b/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
index 31bf8a1..b50fee6 100644
--- a/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
+++ b/jspwiki-util/src/main/java/org/apache/wiki/util/TextUtil.java
@@ -43,6 +43,13 @@ public final class TextUtil {
     /** Length of password. {@link #generateRandomPassword() */
     public static final int PASSWORD_LENGTH = 8;
 
+    /** Lists all punctuation characters allowed in WikiMarkup. These will not be cleaned away. This is for compatibility for older versions
+     of JSPWiki. */
+    public static final String LEGACY_CHARS_ALLOWED = "._";
+
+    /** Lists all punctuation characters allowed in page names. */
+    public static final String PUNCTUATION_CHARS_ALLOWED = " ()&+,-=._$";
+
     /** Private constructor prevents instantiation. */
     private TextUtil() {}
 
@@ -579,6 +586,61 @@ public final class TextUtil {
     }
 
     /**
+     *  Cleans a Wiki name based on a list of characters.  Also, any multiple whitespace is collapsed into a single space, and any
+     *  leading or trailing space is removed.
+     *
+     *  @param text text to be cleared. Null is safe, and causes this to return null.
+     *  @param allowedChars Characters which are allowed in the string.
+     *  @return A cleaned text.
+     *
+     *  @since 2.6
+     */
+    public static String cleanString( String text, final String allowedChars ) {
+        if( text == null ) {
+            return null;
+        }
+
+        text = text.trim();
+        final StringBuilder clean = new StringBuilder( text.length() );
+
+        //  Remove non-alphanumeric characters that should not be put inside WikiNames.  Note that all valid Unicode letters are
+        //  considered okay for WikiNames. It is the problem of the WikiPageProvider to take care of actually storing that information.
+        //
+        //  Also capitalize things, if necessary.
+
+        boolean isWord = true;  // If true, we've just crossed a word boundary
+        boolean wasSpace = false;
+        for( int i = 0; i < text.length(); i++ ) {
+            char ch = text.charAt( i );
+
+            //  Cleans away repetitive whitespace and only uses the first one.
+            if( Character.isWhitespace( ch ) ) {
+                if( wasSpace ) {
+                    continue;
+                }
+
+                wasSpace = true;
+            } else {
+                wasSpace = false;
+            }
+
+            //  Check if it is allowed to use this char, and capitalize, if necessary.
+            if( Character.isLetterOrDigit( ch ) || allowedChars.indexOf( ch ) != -1 ) {
+                // Is a letter
+                if( isWord ) {
+                    ch = Character.toUpperCase( ch );
+                }
+                clean.append( ch );
+                isWord = false;
+            } else {
+                isWord = true;
+            }
+        }
+
+        return clean.toString();
+    }
+
+    /**
      *  Creates a Properties object based on an array which contains alternatively a key and a value.  It is useful
      *  for generating default mappings. For example:
      *  <pre>
@@ -720,11 +782,11 @@ public final class TextUtil {
      * @return A String representation
      * @since 2.3.87
      */
-    public static String toHexString( byte[] bytes ) {
+    public static String toHexString( final byte[] bytes ) {
         final StringBuilder sb = new StringBuilder( bytes.length * 2 );
-        for( int i = 0; i < bytes.length; i++ ) {
-            sb.append( toHex( bytes[i] >> 4 ) );
-            sb.append( toHex( bytes[i] ) );
+        for( final byte aByte : bytes ) {
+            sb.append( toHex( aByte >> 4 ) );
+            sb.append( toHex( aByte ) );
         }
 
         return sb.toString();
@@ -766,7 +828,7 @@ public final class TextUtil {
     public static String generateRandomPassword() {
         String pw = "";
         for( int i = 0; i < PASSWORD_LENGTH; i++ ) {
-            int index = ( int )( RANDOM.nextDouble() * PWD_BASE.length() );
+            final int index = ( int )( RANDOM.nextDouble() * PWD_BASE.length() );
             pw += PWD_BASE.substring( index, index + 1 );
         }
         return pw;


[jspwiki] 01/26: rename RenderingManager as DefaultRenderingManager and extract new interface RenderingManager from it

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit e7ba61c134596fa463e87d55facd686a4e3235ce
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Jan 11 01:30:35 2020 +0100

    rename RenderingManager as DefaultRenderingManager and extract new interface RenderingManager from it
---
 ...ngManager.java => DefaultRenderingManager.java} | 108 ++-------
 .../org/apache/wiki/render/RenderingManager.java   | 241 ++-------------------
 .../src/main/resources/ini/classmappings.xml       |   2 +-
 3 files changed, 38 insertions(+), 313 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
similarity index 71%
copy from jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
copy to jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 8a59271..cb9969f 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -29,7 +29,6 @@ import org.apache.wiki.event.WikiEvent;
 import org.apache.wiki.event.WikiEventListener;
 import org.apache.wiki.event.WikiEventUtils;
 import org.apache.wiki.event.WikiPageEvent;
-import org.apache.wiki.modules.InternalModule;
 import org.apache.wiki.pages.PageManager;
 import org.apache.wiki.parser.JSPWikiMarkupParser;
 import org.apache.wiki.parser.MarkupParser;
@@ -54,9 +53,9 @@ import java.util.Properties;
  *
  *  @since  2.4
  */
-public class RenderingManager implements WikiEventListener, InternalModule {
+public class DefaultRenderingManager implements RenderingManager {
 
-    private static final Logger log = Logger.getLogger( RenderingManager.class );
+    private static final Logger log = Logger.getLogger( DefaultRenderingManager.class );
 
     private final int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
     private final CacheManager m_cacheManager = CacheManager.getInstance();
@@ -65,53 +64,23 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     private boolean m_useCache = true;
 
     /** The capacity of the caches, if you want something else, tweak ehcache.xml. */
-    private static final int    DEFAULT_CACHESIZE     = 1000;
+    private static final int    DEFAULT_CACHESIZE     = 1_000;
     private static final String VERSION_DELIMITER     = "::";
     private static final String PROP_PARSER           = "jspwiki.renderingManager.markupParser";
     private static final String PROP_RENDERER         = "jspwiki.renderingManager.renderer";
     private static final String PROP_WYSIWYG_RENDERER = "jspwiki.renderingManager.renderer.wysiwyg";
 
-    /** The name of the default renderer. */
-    public static final String DEFAULT_PARSER = JSPWikiMarkupParser.class.getName();
-
-    /** The name of the default renderer. */
-    public  static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
-
-    /** The name of the default WYSIWYG renderer. */
-    public  static final String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
-
     /** Stores the WikiDocuments that have been cached. */
     private Cache m_documentCache;
 
-    /** Name of the regular page cache. */
-    public static final String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
-
     private Constructor< ? > m_rendererConstructor;
     private Constructor< ? > m_rendererWysiwygConstructor;
     private String m_markupParserClass = DEFAULT_PARSER;
 
     /**
-     *  Name of the WikiContext variable which is set to Boolean.TRUE or Boolean.FALSE
-     *  depending on whether WYSIWYG is currently in effect.
-     */
-    public static final String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
-
-    /**
-     *  Variable name which tells whether plugins should be executed or not.  Value can be either
-     *  {@code Boolean.TRUE} or {@code Boolean.FALSE}. While not set it's value is {@code null}
-     */
-    public static final String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
-
-    /**
-     *  Initializes the RenderingManager.
-     *  Checks for cache size settings, initializes the document cache.
-     *  Looks for alternative WikiRenderers, initializes one, or the default
-     *  XHTMLRenderer, for use.
-     *
-     *  @param engine A WikiEngine instance.
-     *  @param properties A list of properties to get parameters from.
-     *  @throws WikiException If the manager could not be initialized.
+     *  {@inheritDoc}
      */
+    @Override
     public void initialize( final WikiEngine engine, final Properties properties ) throws WikiException {
         m_engine = engine;
         m_markupParserClass = properties.getProperty( PROP_PARSER, DEFAULT_PARSER );
@@ -165,10 +134,9 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     }
 
     /**
-     *  Returns the wiki Parser
-     *  @param pagedata the page data
-     *  @return A MarkupParser instance.
+     *  {@inheritDoc}
      */
+    @Override
     public MarkupParser getParser( final WikiContext context, final String pagedata ) {
     	try {
 			return ClassUtil.getMappedObject( m_markupParserClass, context, new StringReader( pagedata ) );
@@ -179,17 +147,14 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     }
 
     /**
-     *  Returns a cached document, if one is found.
-     *
-     * @param context the wiki context
-     * @param pagedata the page data
-     * @return the rendered wiki document
+     *  {@inheritDoc}
      */
+    @Override
     // FIXME: The cache management policy is not very good: deleted/changed pages should be detected better.
-    protected WikiDocument getRenderedDocument( final WikiContext context, final String pagedata ) {
+    public WikiDocument getRenderedDocument( final WikiContext context, final String pagedata ) {
         final String pageid = context.getRealPage().getName() + VERSION_DELIMITER +
                               context.getRealPage().getVersion() + VERSION_DELIMITER +
-                              context.getVariable( RenderingManager.VAR_EXECUTE_PLUGINS );
+                              context.getVariable( DefaultRenderingManager.VAR_EXECUTE_PLUGINS );
 
         if( useCache( context ) ) {
             final Element element = m_documentCache.get( pageid );
@@ -231,16 +196,9 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     }
 
     /**
-     *  Simply renders a WikiDocument to a String.  This version does not get the document from the cache - in fact, it does
-     *  not cache the document at all.  This is very useful, if you have something that you want to render outside the caching
-     *  routines.  Because the cache is based on full pages, and the cache keys are based on names, use this routine if you're
-     *  rendering anything for yourself.
-     *
-     *  @param context The WikiContext to render in
-     *  @param doc A proper WikiDocument
-     *  @return Rendered HTML.
-     *  @throws IOException If the WikiDocument is poorly formed.
+     *  {@inheritDoc}
      */
+    @Override
     public String getHTML( final WikiContext context, final WikiDocument doc ) throws IOException {
         final Boolean wysiwygVariable = ( Boolean )context.getVariable( WYSIWYG_EDITOR_MODE );
         final boolean wysiwygEditorMode;
@@ -260,27 +218,18 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     }
 
     /**
-     * Returns a WikiRenderer instance, initialized with the given context and doc. The object is an XHTMLRenderer,
-     * unless overridden in jspwiki.properties with PROP_RENDERER.
-     *
-     * @param context The WikiContext
-     * @param doc The document to render
-     * @return A WikiRenderer for this document, or null, if no such renderer could be instantiated.
+     *  {@inheritDoc}
      */
+    @Override
     public WikiRenderer getRenderer( final WikiContext context, final WikiDocument doc ) {
         final Object[] params = { context, doc };
         return getRenderer( params, m_rendererConstructor );
     }
 
     /**
-     * Returns a WikiRenderer instance meant for WYSIWYG editing, initialized with the given
-     * context and doc. The object is an WysiwygEditingRenderer, unless overridden
-     * in jspwiki.properties with PROP_WYSIWYG_RENDERER.
-     *
-     * @param context The WikiContext
-     * @param doc The document to render
-     * @return A WikiRenderer instance meant for WYSIWYG editing, for this document, or null, if no such renderer could be instantiated.
+     *  {@inheritDoc}
      */
+    @Override
     public WikiRenderer getWysiwygRenderer( final WikiContext context, final WikiDocument doc ) {
         final Object[] params = { context, doc };
         return getRenderer( params, m_rendererWysiwygConstructor );
@@ -297,32 +246,11 @@ public class RenderingManager implements WikiEventListener, InternalModule {
     }
 
     /**
-     *   Convenience method for rendering, using the default parser and renderer.  Note that you can't use this method
-     *   to do any arbitrary rendering, as the pagedata MUST be the data from the that the WikiContext refers to - this
-     *   method caches the HTML internally, and will return the cached version.  If the pagedata is different from what
-     *   was cached, will re-render and store the pagedata into the internal cache.
-     *
-     *   @param context the wiki context
-     *   @param pagedata the page data
-     *   @return XHTML data.
-     */
-    public String getHTML( final WikiContext context, final String pagedata ) {
-        try {
-            final WikiDocument doc = getRenderedDocument( context, pagedata );
-            return getHTML( context, doc );
-        } catch( final IOException e ) {
-            log.error("Unable to parse",e);
-        }
-
-        return null;
-    }
-
-    /**
      * {@inheritDoc}
      *
      * <p>Flushes the document cache in response to a POST_SAVE_BEGIN event.
      *
-     * @see org.apache.wiki.event.WikiEventListener#actionPerformed(org.apache.wiki.event.WikiEvent)
+     * @see WikiEventListener#actionPerformed(WikiEvent)
      */
     @Override
     public void actionPerformed( final WikiEvent event ) {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index 8a59271..e80dbfa 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -18,29 +18,17 @@
  */
 package org.apache.wiki.render;
 
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
 import org.apache.log4j.Logger;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiEngine;
 import org.apache.wiki.api.exceptions.WikiException;
-import org.apache.wiki.event.WikiEvent;
 import org.apache.wiki.event.WikiEventListener;
-import org.apache.wiki.event.WikiEventUtils;
-import org.apache.wiki.event.WikiPageEvent;
 import org.apache.wiki.modules.InternalModule;
-import org.apache.wiki.pages.PageManager;
 import org.apache.wiki.parser.JSPWikiMarkupParser;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.parser.WikiDocument;
-import org.apache.wiki.providers.WikiPageProvider;
-import org.apache.wiki.util.ClassUtil;
 
 import java.io.IOException;
-import java.io.StringReader;
-import java.lang.reflect.Constructor;
-import java.util.Collection;
 import java.util.Properties;
 
 
@@ -54,53 +42,31 @@ import java.util.Properties;
  *
  *  @since  2.4
  */
-public class RenderingManager implements WikiEventListener, InternalModule {
-
-    private static final Logger log = Logger.getLogger( RenderingManager.class );
-
-    private final int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
-    private final CacheManager m_cacheManager = CacheManager.getInstance();
-
-    private WikiEngine m_engine;
-    private boolean m_useCache = true;
-
-    /** The capacity of the caches, if you want something else, tweak ehcache.xml. */
-    private static final int    DEFAULT_CACHESIZE     = 1000;
-    private static final String VERSION_DELIMITER     = "::";
-    private static final String PROP_PARSER           = "jspwiki.renderingManager.markupParser";
-    private static final String PROP_RENDERER         = "jspwiki.renderingManager.renderer";
-    private static final String PROP_WYSIWYG_RENDERER = "jspwiki.renderingManager.renderer.wysiwyg";
+public interface RenderingManager extends WikiEventListener, InternalModule {
 
     /** The name of the default renderer. */
-    public static final String DEFAULT_PARSER = JSPWikiMarkupParser.class.getName();
+    String DEFAULT_PARSER = JSPWikiMarkupParser.class.getName();
 
     /** The name of the default renderer. */
-    public  static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
+    String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
 
     /** The name of the default WYSIWYG renderer. */
-    public  static final String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
-
-    /** Stores the WikiDocuments that have been cached. */
-    private Cache m_documentCache;
+    String DEFAULT_WYSIWYG_RENDERER = WysiwygEditingRenderer.class.getName();
 
     /** Name of the regular page cache. */
-    public static final String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
-
-    private Constructor< ? > m_rendererConstructor;
-    private Constructor< ? > m_rendererWysiwygConstructor;
-    private String m_markupParserClass = DEFAULT_PARSER;
+    String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
 
     /**
-     *  Name of the WikiContext variable which is set to Boolean.TRUE or Boolean.FALSE
-     *  depending on whether WYSIWYG is currently in effect.
+     *  Name of the WikiContext variable which is set to Boolean.TRUE or Boolean.FALSE depending on whether WYSIWYG is currently
+     *  in effect.
      */
-    public static final String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
+    String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
 
     /**
-     *  Variable name which tells whether plugins should be executed or not.  Value can be either
-     *  {@code Boolean.TRUE} or {@code Boolean.FALSE}. While not set it's value is {@code null}
+     *  Variable name which tells whether plugins should be executed or not.  Value can be either {@code Boolean.TRUE} or
+     *  {@code Boolean.FALSE}. While not set it's value is {@code null}.
      */
-    public static final String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
+    String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
 
     /**
      *  Initializes the RenderingManager.
@@ -112,71 +78,14 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      *  @param properties A list of properties to get parameters from.
      *  @throws WikiException If the manager could not be initialized.
      */
-    public void initialize( final WikiEngine engine, final Properties properties ) throws WikiException {
-        m_engine = engine;
-        m_markupParserClass = properties.getProperty( PROP_PARSER, DEFAULT_PARSER );
-        if( !ClassUtil.assignable( m_markupParserClass, MarkupParser.class.getName() ) ) {
-        	log.warn( m_markupParserClass + " does not subclass " + MarkupParser.class.getName() + " reverting to default markup parser." );
-        	m_markupParserClass = DEFAULT_PARSER;
-        }
-        log.info( "Using " + m_markupParserClass + " as markup parser." );
-
-        m_useCache = "true".equals( properties.getProperty( PageManager.PROP_USECACHE ) );
-
-        if( m_useCache ) {
-            final String documentCacheName = engine.getApplicationName() + "." + DOCUMENTCACHE_NAME;
-            if (m_cacheManager.cacheExists(documentCacheName)) {
-                m_documentCache = m_cacheManager.getCache(documentCacheName);
-            } else {
-                log.info( "cache with name " + documentCacheName + " not found in ehcache.xml, creating it with defaults." );
-                m_documentCache = new Cache( documentCacheName, DEFAULT_CACHESIZE, false, false, m_cacheExpiryPeriod, m_cacheExpiryPeriod );
-                m_cacheManager.addCache( m_documentCache );
-            }
-        }
-
-        final String renderImplName = properties.getProperty( PROP_RENDERER, DEFAULT_RENDERER );
-        final String renderWysiwygImplName = properties.getProperty( PROP_WYSIWYG_RENDERER, DEFAULT_WYSIWYG_RENDERER );
-
-        final Class< ? >[] rendererParams = { WikiContext.class, WikiDocument.class };
-        m_rendererConstructor = initRenderer( renderImplName, rendererParams );
-        m_rendererWysiwygConstructor = initRenderer( renderWysiwygImplName, rendererParams );
-
-        log.info( "Rendering content with " + renderImplName + "." );
-
-        WikiEventUtils.addWikiEventListener(m_engine, WikiPageEvent.POST_SAVE_BEGIN, this);
-    }
-
-    private Constructor< ? > initRenderer( final String renderImplName, final Class< ? >[] rendererParams ) throws WikiException {
-        Constructor< ? > c = null;
-        try {
-            final Class< ? > clazz = Class.forName( renderImplName );
-            c = clazz.getConstructor( rendererParams );
-        } catch( final ClassNotFoundException e ) {
-            log.error( "Unable to find WikiRenderer implementation " + renderImplName );
-        } catch( final SecurityException e ) {
-            log.error( "Unable to access the WikiRenderer(WikiContext,WikiDocument) constructor for "  + renderImplName );
-        } catch( final NoSuchMethodException e ) {
-            log.error( "Unable to locate the WikiRenderer(WikiContext,WikiDocument) constructor for "  + renderImplName );
-        }
-        if( c == null ) {
-            throw new WikiException( "Failed to get WikiRenderer '" + renderImplName + "'." );
-        }
-        return c;
-    }
+    void initialize( WikiEngine engine, Properties properties ) throws WikiException;
 
     /**
      *  Returns the wiki Parser
      *  @param pagedata the page data
      *  @return A MarkupParser instance.
      */
-    public MarkupParser getParser( final WikiContext context, final String pagedata ) {
-    	try {
-			return ClassUtil.getMappedObject( m_markupParserClass, context, new StringReader( pagedata ) );
-		} catch( final ReflectiveOperationException | IllegalArgumentException e ) {
-			log.error( "unable to get an instance of " + m_markupParserClass + " (" + e.getMessage() + "), returning default markup parser.", e );
-			return new JSPWikiMarkupParser( context, new StringReader( pagedata ) );
-		}
-    }
+    MarkupParser getParser( WikiContext context, String pagedata );
 
     /**
      *  Returns a cached document, if one is found.
@@ -185,50 +94,7 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      * @param pagedata the page data
      * @return the rendered wiki document
      */
-    // FIXME: The cache management policy is not very good: deleted/changed pages should be detected better.
-    protected WikiDocument getRenderedDocument( final WikiContext context, final String pagedata ) {
-        final String pageid = context.getRealPage().getName() + VERSION_DELIMITER +
-                              context.getRealPage().getVersion() + VERSION_DELIMITER +
-                              context.getVariable( RenderingManager.VAR_EXECUTE_PLUGINS );
-
-        if( useCache( context ) ) {
-            final Element element = m_documentCache.get( pageid );
-            if ( element != null ) {
-                final WikiDocument doc = ( WikiDocument )element.getObjectValue();
-
-                //
-                //  This check is needed in case the different filters have actually changed the page data.
-                //  FIXME: Figure out a faster method
-                if( pagedata.equals( doc.getPageData() ) ) {
-                    if( log.isDebugEnabled() ) {
-                        log.debug( "Using cached HTML for page " + pageid );
-                    }
-                    return doc;
-                }
-            } else if( log.isDebugEnabled() ) {
-                log.debug( "Re-rendering and storing " + pageid );
-            }
-        }
-
-        //  Refresh the data content
-        try {
-            final MarkupParser parser = getParser( context, pagedata );
-            final WikiDocument doc = parser.parse();
-            doc.setPageData( pagedata );
-            if( useCache( context ) ) {
-                m_documentCache.put( new Element( pageid, doc ) );
-            }
-            return doc;
-        } catch( final IOException ex ) {
-            log.error( "Unable to parse", ex );
-        }
-
-        return null;
-    }
-
-    boolean useCache( final WikiContext context ) {
-        return m_useCache && WikiContext.VIEW.equals( context.getRequestContext() );
-    }
+    WikiDocument getRenderedDocument( WikiContext context, String pagedata );
 
     /**
      *  Simply renders a WikiDocument to a String.  This version does not get the document from the cache - in fact, it does
@@ -241,23 +107,7 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      *  @return Rendered HTML.
      *  @throws IOException If the WikiDocument is poorly formed.
      */
-    public String getHTML( final WikiContext context, final WikiDocument doc ) throws IOException {
-        final Boolean wysiwygVariable = ( Boolean )context.getVariable( WYSIWYG_EDITOR_MODE );
-        final boolean wysiwygEditorMode;
-        if( wysiwygVariable != null ) {
-            wysiwygEditorMode = wysiwygVariable;
-        } else {
-            wysiwygEditorMode = false;
-        }
-        final WikiRenderer rend;
-        if( wysiwygEditorMode ) {
-            rend = getWysiwygRenderer( context, doc );
-        } else {
-            rend = getRenderer( context, doc );
-        }
-
-        return rend.getString();
-    }
+    String getHTML( WikiContext context, WikiDocument doc ) throws IOException;
 
     /**
      * Returns a WikiRenderer instance, initialized with the given context and doc. The object is an XHTMLRenderer,
@@ -267,10 +117,7 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      * @param doc The document to render
      * @return A WikiRenderer for this document, or null, if no such renderer could be instantiated.
      */
-    public WikiRenderer getRenderer( final WikiContext context, final WikiDocument doc ) {
-        final Object[] params = { context, doc };
-        return getRenderer( params, m_rendererConstructor );
-    }
+    WikiRenderer getRenderer( WikiContext context, WikiDocument doc );
 
     /**
      * Returns a WikiRenderer instance meant for WYSIWYG editing, initialized with the given
@@ -281,20 +128,7 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      * @param doc The document to render
      * @return A WikiRenderer instance meant for WYSIWYG editing, for this document, or null, if no such renderer could be instantiated.
      */
-    public WikiRenderer getWysiwygRenderer( final WikiContext context, final WikiDocument doc ) {
-        final Object[] params = { context, doc };
-        return getRenderer( params, m_rendererWysiwygConstructor );
-    }
-
-    @SuppressWarnings("unchecked")
-    private < T extends WikiRenderer > T getRenderer( final Object[] params, final Constructor<?> rendererConstructor ) {
-        try {
-            return ( T )rendererConstructor.newInstance( params );
-        } catch( final Exception e ) {
-            log.error( "Unable to create WikiRenderer", e );
-        }
-        return null;
-    }
+    WikiRenderer getWysiwygRenderer( WikiContext context, WikiDocument doc );
 
     /**
      *   Convenience method for rendering, using the default parser and renderer.  Note that you can't use this method
@@ -306,52 +140,15 @@ public class RenderingManager implements WikiEventListener, InternalModule {
      *   @param pagedata the page data
      *   @return XHTML data.
      */
-    public String getHTML( final WikiContext context, final String pagedata ) {
+    default String getHTML( final WikiContext context, final String pagedata ) {
         try {
             final WikiDocument doc = getRenderedDocument( context, pagedata );
             return getHTML( context, doc );
         } catch( final IOException e ) {
-            log.error("Unable to parse",e);
+            Logger.getLogger( RenderingManager.class ).error("Unable to parse", e );
         }
 
         return null;
     }
 
-    /**
-     * {@inheritDoc}
-     *
-     * <p>Flushes the document cache in response to a POST_SAVE_BEGIN event.
-     *
-     * @see org.apache.wiki.event.WikiEventListener#actionPerformed(org.apache.wiki.event.WikiEvent)
-     */
-    @Override
-    public void actionPerformed( final WikiEvent event ) {
-        log.debug( "event received: " + event.toString() );
-        if( m_useCache ) {
-            if( ( event instanceof WikiPageEvent ) && ( event.getType() == WikiPageEvent.POST_SAVE_BEGIN ) ) {
-                if( m_documentCache != null ) {
-                    final String pageName = ( ( WikiPageEvent ) event ).getPageName();
-                    m_documentCache.remove( pageName );
-                    final Collection< String > referringPages = m_engine.getReferenceManager().findReferrers( pageName );
-
-                    //
-                    //  Flush also those pages that refer to this page (if an nonexistent page
-                    //  appears, we need to flush the HTML that refers to the now-existent page)
-                    //
-                    if( referringPages != null ) {
-                        for( final String page : referringPages ) {
-                            if( log.isDebugEnabled() ) {
-                                log.debug( "Flushing latest version of " + page );
-                            }
-                            // as there is a new version of the page expire both plugin and pluginless versions of the old page
-                            m_documentCache.remove( page + VERSION_DELIMITER + WikiPageProvider.LATEST_VERSION  + VERSION_DELIMITER + Boolean.FALSE );
-                            m_documentCache.remove( page + VERSION_DELIMITER + WikiPageProvider.LATEST_VERSION  + VERSION_DELIMITER + Boolean.TRUE );
-                            m_documentCache.remove( page + VERSION_DELIMITER + WikiPageProvider.LATEST_VERSION  + VERSION_DELIMITER + null );
-                        }
-                    }
-                }
-            }
-        }
-    }
-
 }
diff --git a/jspwiki-main/src/main/resources/ini/classmappings.xml b/jspwiki-main/src/main/resources/ini/classmappings.xml
index e005819..bc6f1e0 100644
--- a/jspwiki-main/src/main/resources/ini/classmappings.xml
+++ b/jspwiki-main/src/main/resources/ini/classmappings.xml
@@ -105,7 +105,7 @@
   </mapping>
   <mapping>
     <requestedClass>org.apache.wiki.render.RenderingManager</requestedClass>
-    <mappedClass>org.apache.wiki.render.RenderingManager</mappedClass>
+    <mappedClass>org.apache.wiki.render.DefaultRenderingManager</mappedClass>
   </mapping>
   <mapping>
     <requestedClass>org.apache.wiki.search.SearchManager</requestedClass>


[jspwiki] 05/26: move RenderingManager#VAR_EXECUTE_PLUGINS constant to WikiContext

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 13f2d0df7c10a6ce0f07731735879b0ecbd03e11
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Jan 11 22:48:17 2020 +0100

    move RenderingManager#VAR_EXECUTE_PLUGINS constant to WikiContext
---
 .../src/main/java/org/apache/wiki/WikiContext.java |   6 +
 .../apache/wiki/auth/acl/DefaultAclManager.java    | 138 +++++++++------------
 .../java/org/apache/wiki/parser/PluginContent.java |  14 +--
 .../wiki/render/DefaultRenderingManager.java       |   2 +-
 .../org/apache/wiki/render/RenderingManager.java   |   6 -
 5 files changed, 71 insertions(+), 95 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
index ace5764..4b9a1d6 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
@@ -71,6 +71,12 @@ public class WikiContext implements Cloneable, Command {
 
     public static final String ATTR_CONTEXT = "jspwiki.context";
 
+    /**
+     *  Variable name which tells whether plugins should be executed or not. Value can be either {@code Boolean.TRUE} or
+     *  {@code Boolean.FALSE}. While not set it's value is {@code null}.
+     */
+    public static final String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
+
     /** Name of the variable which is set to Boolean.TRUE or Boolean.FALSE depending on whether WYSIWYG is currently in effect. */
     public static final String VAR_WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
index 860eafa..d5ff97f 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java
@@ -31,12 +31,10 @@ import org.apache.wiki.auth.permissions.PagePermission;
 import org.apache.wiki.auth.permissions.PermissionFactory;
 import org.apache.wiki.pages.PageLock;
 import org.apache.wiki.pages.PageManager;
-import org.apache.wiki.render.RenderingManager;
 
 import java.security.Permission;
 import java.security.Principal;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
 import java.util.Map;
@@ -73,72 +71,66 @@ public class DefaultAclManager implements AclManager {
      * the second is the list of Principals separated by commas. The overall match is
      * the ACL string from [{ to }].
      */
-    public static final Pattern ACL_PATTERN = Pattern.compile(ACL_REGEX);
+    public static final Pattern ACL_PATTERN = Pattern.compile( ACL_REGEX );
 
     /**
      * Initializes the AclManager with a supplied wiki engine and properties.
      *
      * @param engine the wiki engine
      * @param props  the initialization properties
-     * @see org.apache.wiki.auth.acl.AclManager#initialize(org.apache.wiki.WikiEngine,
-     *      java.util.Properties)
+     * @see org.apache.wiki.auth.acl.AclManager#initialize(org.apache.wiki.WikiEngine, java.util.Properties)
      */
-    public void initialize(WikiEngine engine, Properties props) {
+    public void initialize( final WikiEngine engine, final Properties props ) {
         m_auth = engine.getAuthorizationManager();
         m_engine = engine;
     }
 
     /**
-     * A helper method for parsing textual AccessControlLists. The line is in
-     * form "ALLOW <permission> <principal>, <principal>, <principal>". This
-     * method was moved from Authorizer.
+     * A helper method for parsing textual AccessControlLists. The line is in form
+     * {@code ALLOW <permission> <principal>, <principal>, <principal>}. This method was moved from Authorizer.
      *
-     * @param page     The current wiki page. If the page already has an ACL, it
-     *                 will be used as a basis for this ACL in order to avoid the
-     *                 creation of a new one.
+     * @param page The current wiki page. If the page already has an ACL, it will be used as a basis for this ACL in order to avoid the
+     *             creation of a new one.
      * @param ruleLine The rule line, as described above.
      * @return A valid Access Control List. May be empty.
      * @throws WikiSecurityException if the ruleLine was faulty somehow.
      * @since 2.1.121
      */
-    public Acl parseAcl(WikiPage page, String ruleLine) throws WikiSecurityException {
+    public Acl parseAcl( final WikiPage page, final String ruleLine ) throws WikiSecurityException {
         Acl acl = page.getAcl();
         if (acl == null) {
             acl = new AclImpl();
         }
 
         try {
-            StringTokenizer fieldToks = new StringTokenizer(ruleLine);
+            final StringTokenizer fieldToks = new StringTokenizer(ruleLine);
             fieldToks.nextToken();
-            String actions = fieldToks.nextToken();
-            page.getName();
+            final String actions = fieldToks.nextToken();
 
-            while (fieldToks.hasMoreTokens()) {
-                String principalName = fieldToks.nextToken(",").trim();
-                Principal principal = m_auth.resolvePrincipal(principalName);
-                AclEntry oldEntry = acl.getEntry(principal);
+            while( fieldToks.hasMoreTokens() ) {
+                final String principalName = fieldToks.nextToken(",").trim();
+                final Principal principal = m_auth.resolvePrincipal(principalName);
+                final AclEntry oldEntry = acl.getEntry(principal);
 
-                if (oldEntry != null) {
-                    log.debug("Adding to old acl list: " + principal + ", " + actions);
-                    oldEntry.addPermission(PermissionFactory.getPagePermission(page, actions));
+                if( oldEntry != null ) {
+                    log.debug( "Adding to old acl list: " + principal + ", " + actions );
+                    oldEntry.addPermission( PermissionFactory.getPagePermission( page, actions ) );
                 } else {
-                    log.debug("Adding new acl entry for " + actions);
-                    AclEntry entry = new AclEntryImpl();
+                    log.debug( "Adding new acl entry for " + actions );
+                    final AclEntry entry = new AclEntryImpl();
+                    entry.setPrincipal( principal );
+                    entry.addPermission( PermissionFactory.getPagePermission( page, actions ) );
 
-                    entry.setPrincipal(principal);
-                    entry.addPermission(PermissionFactory.getPagePermission(page, actions));
-
-                    acl.addEntry(entry);
+                    acl.addEntry( entry );
                 }
             }
 
-            page.setAcl(acl);
-
-            log.debug(acl.toString());
-        } catch (NoSuchElementException nsee) {
-            log.warn("Invalid access rule: " + ruleLine + " - defaults will be used.");
-            throw new WikiSecurityException("Invalid access rule: " + ruleLine, nsee);
-        } catch (IllegalArgumentException iae) {
+            page.setAcl( acl );
+            log.debug( acl.toString() );
+        } catch( final NoSuchElementException nsee ) {
+            log.warn( "Invalid access rule: " + ruleLine + " - defaults will be used." );
+            throw new WikiSecurityException( "Invalid access rule: " + ruleLine, nsee );
+        } catch( final IllegalArgumentException iae ) {
             throw new WikiSecurityException("Invalid permission type: " + ruleLine, iae);
         }
 
@@ -159,28 +151,19 @@ public class DefaultAclManager implements AclManager {
      * @since 2.2.121
      */
     public Acl getPermissions( final WikiPage page ) {
-        //
         //  Does the page already have cached ACLs?
-        //
         Acl acl = page.getAcl();
-        log.debug("page=" + page.getName() + "\n" + acl);
+        log.debug( "page=" + page.getName() + "\n" + acl );
 
-        if (acl == null) {
-            //
+        if( acl == null ) {
             //  If null, try the parent.
-            //
             if( page instanceof Attachment ) {
                 final WikiPage parent = m_engine.getPageManager().getPage( ( ( Attachment ) page ).getParentName() );
-
                 acl = getPermissions(parent);
             } else {
-                //
                 //  Or, try parsing the page
-                //
-                final WikiContext ctx = new WikiContext(m_engine, page);
-
-                ctx.setVariable(RenderingManager.VAR_EXECUTE_PLUGINS, Boolean.FALSE);
-
+                final WikiContext ctx = new WikiContext( m_engine, page );
+                ctx.setVariable( WikiContext.VAR_EXECUTE_PLUGINS, Boolean.FALSE );
                 m_engine.getHTML(ctx, page);
 
                 if (page.getAcl() == null) {
@@ -234,47 +217,44 @@ public class DefaultAclManager implements AclManager {
      * @param acl the ACL
      * @return the ACL string
      */
-    protected static String printAcl(Acl acl) {
+    protected static String printAcl( final Acl acl ) {
         // Extract the ACL entries into a Map with keys == permissions, values == principals
-        Map<String, List<Principal>> permissionPrincipals = new TreeMap<String, List<Principal>>();
-        Enumeration<AclEntry> entries = acl.entries();
-        while (entries.hasMoreElements()) {
-            AclEntry entry = entries.nextElement();
-            Principal principal = entry.getPrincipal();
-            Enumeration<Permission> permissions = entry.permissions();
-            while (permissions.hasMoreElements()) {
-                Permission permission = permissions.nextElement();
-                List<Principal> principals = permissionPrincipals.get(permission.getActions());
+        final Map< String, List< Principal > > permissionPrincipals = new TreeMap<>();
+        final Enumeration< AclEntry > entries = acl.entries();
+        while( entries.hasMoreElements() ) {
+            final AclEntry entry = entries.nextElement();
+            final Principal principal = entry.getPrincipal();
+            final Enumeration< Permission > permissions = entry.permissions();
+            while( permissions.hasMoreElements() ) {
+                final Permission permission = permissions.nextElement();
+                List< Principal > principals = permissionPrincipals.get( permission.getActions() );
                 if (principals == null) {
-                    principals = new ArrayList<Principal>();
-                    String action = permission.getActions();
-                    if (action.indexOf(',') != -1) {
+                    principals = new ArrayList<>();
+                    final String action = permission.getActions();
+                    if( action.indexOf(',') != -1 ) {
                         throw new IllegalStateException("AclEntry permission cannot have multiple targets.");
                     }
-                    permissionPrincipals.put(action, principals);
+                    permissionPrincipals.put( action, principals );
                 }
-                principals.add(principal);
+                principals.add( principal );
             }
         }
 
         // Now, iterate through each permission in the map and generate an ACL string
-
-        StringBuilder s = new StringBuilder();
-        for (Map.Entry<String, List<Principal>> entry : permissionPrincipals.entrySet()) {
-            String action = entry.getKey();
-            List<Principal> principals = entry.getValue();
-            Collections.sort(principals, new PrincipalComparator());
-            s.append("[{ALLOW ");
-            s.append(action);
-            s.append(" ");
-            for (int i = 0; i < principals.size(); i++) {
-                Principal principal = principals.get(i);
-                s.append(principal.getName());
-                if (i < (principals.size() - 1)) {
-                    s.append(",");
+        final StringBuilder s = new StringBuilder();
+        for( final Map.Entry< String, List< Principal > > entry : permissionPrincipals.entrySet() ) {
+            final String action = entry.getKey();
+            final List< Principal > principals = entry.getValue();
+            principals.sort( new PrincipalComparator() );
+            s.append( "[{ALLOW " ).append( action ).append( " " );
+            for( int i = 0; i < principals.size(); i++ ) {
+                final Principal principal = principals.get( i );
+                s.append( principal.getName() );
+                if( i < ( principals.size() - 1 ) ) {
+                    s.append( "," );
                 }
             }
-            s.append("}]\n");
+            s.append( "}]\n" );
         }
         return s.toString();
     }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
index 56b9c30..1fa4947 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/PluginContent.java
@@ -30,7 +30,6 @@ import org.apache.wiki.api.exceptions.PluginException;
 import org.apache.wiki.api.plugin.ParserStagePlugin;
 import org.apache.wiki.api.plugin.WikiPlugin;
 import org.apache.wiki.preferences.Preferences;
-import org.apache.wiki.render.RenderingManager;
 import org.jdom2.Text;
 
 import java.io.IOException;
@@ -44,13 +43,10 @@ import java.util.ResourceBundle;
 /**
  * Stores the contents of a plugin in a WikiDocument DOM tree.
  * <p/>
- * If the RenderingManager.WYSIWYG_EDITOR_MODE is set to Boolean.TRUE in the context,
- * then the plugin
- * is rendered as WikiMarkup.  This allows an HTML editor to work without
- * rendering the plugin each time as well.
+ * If the WikiContext.VAR_WYSIWYG_EDITOR_MODE is set to Boolean.TRUE in the context, then the plugin is rendered as WikiMarkup.
+ * This allows an HTML editor to work without rendering the plugin each time as well.
  * <p/>
- * If RenderingManager.VAR_EXECUTE_PLUGINS is set to Boolean.FALSE, then
- * the plugin is not executed.
+ * If WikiContext.VAR_EXECUTE_PLUGINS is set to Boolean.FALSE, then the plugin is not executed.
  *
  * @since 2.4
  */
@@ -176,7 +172,7 @@ public class PluginContent extends Text {
                 final String cmdLine = m_params.get( CMDLINE ).replaceAll( LINEBREAK, ELEMENT_BR );
                 result = result + cmdLine + PLUGIN_END;
             } else {
-                final Boolean b = ( Boolean )context.getVariable(RenderingManager.VAR_EXECUTE_PLUGINS );
+                final Boolean b = ( Boolean )context.getVariable( WikiContext.VAR_EXECUTE_PLUGINS );
                 if (b != null && !b ) {
                     return BLANK;
                 }
@@ -222,7 +218,7 @@ public class PluginContent extends Text {
             final Map< String, String > params = getParameters();
             final WikiPlugin plugin = pm.newWikiPlugin( getPluginName(), rb );
             try {
-                if( plugin != null && plugin instanceof ParserStagePlugin ) {
+                if( plugin instanceof ParserStagePlugin ) {
                     ( ( ParserStagePlugin )plugin ).executeParser(this, context, params );
                 }
             } catch( final ClassCastException e ) {
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
index 989a7ba..5e63df5 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/DefaultRenderingManager.java
@@ -154,7 +154,7 @@ public class DefaultRenderingManager implements RenderingManager {
     public WikiDocument getRenderedDocument( final WikiContext context, final String pagedata ) {
         final String pageid = context.getRealPage().getName() + VERSION_DELIMITER +
                               context.getRealPage().getVersion() + VERSION_DELIMITER +
-                              context.getVariable( DefaultRenderingManager.VAR_EXECUTE_PLUGINS );
+                              context.getVariable( WikiContext.VAR_EXECUTE_PLUGINS );
 
         if( useCache( context ) ) {
             final Element element = m_documentCache.get( pageid );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
index 12564dc..ea0d0e6 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/RenderingManager.java
@@ -57,12 +57,6 @@ public interface RenderingManager extends WikiEventListener, InternalModule {
     String DOCUMENTCACHE_NAME = "jspwiki.renderingCache";
 
     /**
-     *  Variable name which tells whether plugins should be executed or not.  Value can be either {@code Boolean.TRUE} or
-     *  {@code Boolean.FALSE}. While not set it's value is {@code null}.
-     */
-    String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
-
-    /**
      *  Initializes the RenderingManager.
      *  Checks for cache size settings, initializes the document cache.
      *  Looks for alternative WikiRenderers, initializes one, or the default


[jspwiki] 22/26: refactor add*LinkHook( StringTransmutator ) common behaviour

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit df2e164cb5b413537c59d4fb649e0270e77b7291
Author: juanpablo <ju...@apache.org>
AuthorDate: Thu Jan 16 22:27:36 2020 +0100

    refactor add*LinkHook( StringTransmutator ) common behaviour
    
    also, apply format and fixes suggested by IntelliJ to MarkupParser
---
 .../java/org/apache/wiki/parser/MarkupParser.java  | 202 ++++++++-------------
 1 file changed, 74 insertions(+), 128 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
index f2c6dab..5450a8b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
@@ -54,11 +54,11 @@ public abstract class MarkupParser
     protected WikiContext    m_context;
 
     /** Optionally stores internal wikilinks */
-    protected ArrayList<StringTransmutator>      m_localLinkMutatorChain    = new ArrayList<>();
-    protected ArrayList<StringTransmutator>      m_externalLinkMutatorChain = new ArrayList<>();
-    protected ArrayList<StringTransmutator>      m_attachmentLinkMutatorChain = new ArrayList<>();
-    protected ArrayList<HeadingListener>         m_headingListenerChain     = new ArrayList<>();
-    protected ArrayList<StringTransmutator>      m_linkMutators             = new ArrayList<>();
+    protected ArrayList< StringTransmutator >      m_localLinkMutatorChain    = new ArrayList<>();
+    protected ArrayList< StringTransmutator >      m_externalLinkMutatorChain = new ArrayList<>();
+    protected ArrayList< StringTransmutator >      m_attachmentLinkMutatorChain = new ArrayList<>();
+    protected ArrayList< HeadingListener >         m_headingListenerChain     = new ArrayList<>();
+    protected ArrayList< StringTransmutator >      m_linkMutators             = new ArrayList<>();
 
     protected boolean        m_inlineImages     = true;
     protected boolean        m_parseAccessRules = true;
@@ -142,14 +142,12 @@ public abstract class MarkupParser
    };
 
     /**
-     *  Constructs a MarkupParser.  The subclass must call this constructor
-     *  to set up the necessary bits and pieces.
+     *  Constructs a MarkupParser.  The subclass must call this constructor to set up the necessary bits and pieces.
      *
      *  @param context The WikiContext.
      *  @param in The reader from which we are reading the bytes from.
      */
-    protected MarkupParser( WikiContext context, Reader in )
-    {
+    protected MarkupParser( final WikiContext context, final Reader in ) {
         m_engine = context.getEngine();
         m_context = context;
         m_linkParsingOperations = new LinkParsingOperations( m_context );
@@ -158,64 +156,45 @@ public abstract class MarkupParser
 
     /**
      *  Replaces the current input character stream with a new one.
+     *
      *  @param in New source for input.  If null, this method does nothing.
      *  @return the old stream
      */
-    public Reader setInputReader( Reader in )
-    {
-        Reader old = m_in;
-
-        if( in != null )
-        {
-            m_in = new PushbackReader( new BufferedReader( in ),
-                                       PUSHBACK_BUFFER_SIZE );
+    public Reader setInputReader( final Reader in ) {
+        final Reader old = m_in;
+        if( in != null ) {
+            m_in = new PushbackReader( new BufferedReader( in ), PUSHBACK_BUFFER_SIZE );
         }
 
         return old;
     }
 
     /**
-     *  Adds a hook for processing link texts.  This hook is called
-     *  when the link text is written into the output stream, and
-     *  you may use it to modify the text.  It does not affect the
-     *  actual link, only the user-visible text.
+     *  Adds a hook for processing link texts.  This hook is called when the link text is written into the output stream, and
+     *  you may use it to modify the text.  It does not affect the actual link, only the user-visible text.
      *
      *  @param mutator The hook to call.  Null is safe.
      */
-    public void addLinkTransmutator( StringTransmutator mutator )
-    {
-        if( mutator != null )
-        {
-            m_linkMutators.add( mutator );
-        }
+    public void addLinkTransmutator( final StringTransmutator mutator ) {
+        addLinkHook( m_linkMutators, mutator );
     }
 
     /**
-     *  Adds a hook for processing local links.  The engine
-     *  transforms both non-existing and existing page links.
+     *  Adds a hook for processing local links.  The engine transforms both non-existing and existing page links.
      *
      *  @param mutator The hook to call.  Null is safe.
      */
-    public void addLocalLinkHook( StringTransmutator mutator )
-    {
-        if( mutator != null )
-        {
-            m_localLinkMutatorChain.add( mutator );
-        }
+    public void addLocalLinkHook( final StringTransmutator mutator ) {
+        addLinkHook( m_localLinkMutatorChain, mutator );
     }
 
     /**
-     *  Adds a hook for processing external links.  This includes
-     *  all http:// ftp://, etc. links, including inlined images.
+     *  Adds a hook for processing external links.  This includes all http:// ftp://, etc. links, including inlined images.
      *
      *  @param mutator The hook to call.  Null is safe.
      */
-    public void addExternalLinkHook( StringTransmutator mutator )
-    {
-        if( mutator != null )
-        {
-            m_externalLinkMutatorChain.add( mutator );
-        }
+    public void addExternalLinkHook( final StringTransmutator mutator ) {
+        addLinkHook( m_externalLinkMutatorChain, mutator );
     }
 
     /**
@@ -223,24 +202,23 @@ public abstract class MarkupParser
      *
      *  @param mutator The hook to call.  Null is safe.
      */
-    public void addAttachmentLinkHook( StringTransmutator mutator )
-    {
-        if( mutator != null )
-        {
-            m_attachmentLinkMutatorChain.add( mutator );
+    public void addAttachmentLinkHook( final StringTransmutator mutator ) {
+        addLinkHook( m_attachmentLinkMutatorChain, mutator );
+    }
+
+    void addLinkHook( final List< StringTransmutator > mutatorChain, final StringTransmutator mutator ) {
+        if( mutator != null ) {
+            mutatorChain.add( mutator );
         }
     }
 
     /**
-     *  Adds a HeadingListener to the parser chain.  It will be called whenever
-     *  a parsed header is found.
+     *  Adds a HeadingListener to the parser chain.  It will be called whenever a parsed header is found.
      *
      *  @param listener The listener to add.
      */
-    public void addHeadingListener( HeadingListener listener )
-    {
-        if( listener != null )
-        {
+    public void addHeadingListener( final HeadingListener listener ) {
+        if( listener != null ) {
             m_headingListenerChain.add( listener );
         }
     }
@@ -260,12 +238,13 @@ public abstract class MarkupParser
 
     /**
      *  Use this to turn on or off image inlining.
+     *
      *  @param toggle If true, images are inlined (as per set in jspwiki.properties)
      *                If false, then images won't be inlined; instead, they will be
      *                treated as standard hyperlinks.
      *  @since 2.2.9
      */
-    public void enableImageInlining( boolean toggle )
+    public void enableImageInlining( final boolean toggle )
     {
         m_inlineImages = toggle;
     }
@@ -274,21 +253,17 @@ public abstract class MarkupParser
         return m_inlineImages;
     }
 
-    @SuppressWarnings( "unchecked" )
     protected final void initInlineImagePatterns() {
-		PatternCompiler compiler = new GlobCompiler();
-        //
+		final PatternCompiler compiler = new GlobCompiler();
+
         //  We cache compiled patterns in the engine, since their creation is really expensive
-        //
         List< Pattern > compiledpatterns = m_engine.getAttribute( INLINE_IMAGE_PATTERNS );
 
         if( compiledpatterns == null ) {
             compiledpatterns = new ArrayList< >( 20 );
-            Collection< String > ptrns = m_engine.getAllInlinedImagePatterns();
+            final Collection< String > ptrns = m_engine.getAllInlinedImagePatterns();
 
-            //
             //  Make them into Regexp Patterns.  Unknown patterns are ignored.
-            //
             for( final String pattern : ptrns ) {
                 try {
                     compiledpatterns.add( compiler.compile( pattern, GlobCompiler.DEFAULT_MASK | GlobCompiler.READ_ONLY_MASK ) );
@@ -312,15 +287,15 @@ public abstract class MarkupParser
 
     /**
      *  Parses the document.
+     *
      *  @return the parsed document, as a WikiDocument
      *  @throws IOException If something goes wrong.
      */
-    public abstract WikiDocument parse()
-         throws IOException;
+    public abstract WikiDocument parse() throws IOException;
 
     /**
-     *  Return the current position in the reader stream.
-     *  The value will be -1 prior to reading.
+     *  Return the current position in the reader stream. The value will be -1 prior to reading.
+     *
      * @return the reader position as an int.
      */
     public int getPosition()
@@ -329,55 +304,44 @@ public abstract class MarkupParser
     }
 
     /**
-     * Returns the next token in the stream.  This is the most called method
-     * in the entire parser, so it needs to be lean and mean.
+     * Returns the next token in the stream.  This is the most called method in the entire parser, so it needs to be lean and mean.
      *
      * @return The next token in the stream; or, if the stream is ended, -1.
      * @throws IOException If something bad happens
      * @throws NullPointerException If you have not yet created an input document.
      */
-    protected final int nextToken()
-        throws IOException, NullPointerException
-    {
+    protected final int nextToken() throws IOException, NullPointerException {
         // if( m_in == null ) return -1;
         m_pos++;
         return m_in.read();
     }
 
     /**
-     *  Push back any character to the current input.  Does not
-     *  push back a read EOF, though.
+     *  Push back any character to the current input.  Does not push back a read EOF, though.
      *
      *  @param c Character to push back.
      *  @throws IOException In case the character cannot be pushed back.
      */
-    protected void pushBack( int c )
-        throws IOException
-    {
-        if( c != -1 && m_in != null )
-        {
+    protected void pushBack( final int c ) throws IOException {
+        if( c != -1 && m_in != null ) {
             m_pos--;
             m_in.unread( c );
         }
     }
 
     /**
-     *  Writes HTML for error message.  Does not add it to the document, you
-     *  have to do it yourself.
+     *  Writes HTML for error message.  Does not add it to the document, you have to do it yourself.
      *
      *  @param error The error string.
      *  @return An Element containing the error.
      */
-
-    public static Element makeError( String error )
-    {
-        return new Element("span").setAttribute("class","error").addContent(error);
+    public static Element makeError( final String error ) {
+        return new Element( "span" ).setAttribute( "class", "error" ).addContent( error );
     }
 
     /**
-     *  Cleans a Wiki name.  The functionality of this method was changed in 2.6
-     *  so that the list of allowed characters is much larger.  Use wikifyLink()
-     *  to get the legacy behaviour.
+     *  Cleans a Wiki name.  The functionality of this method was changed in 2.6 so that the list of allowed characters is much larger.
+     *  Use {@link #wikifyLink(String)} to get the legacy behaviour.
      *  <P>
      *  [ This is a link ] -&gt; This is a link
      *
@@ -386,15 +350,13 @@ public abstract class MarkupParser
      *
      *  @since 2.0
      */
-    public static String cleanLink( String link )
-    {
-        return cleanLink(link, PUNCTUATION_CHARS_ALLOWED);
+    public static String cleanLink( final String link ) {
+        return cleanLink( link, PUNCTUATION_CHARS_ALLOWED );
     }
 
     /**
-     *  Cleans a Wiki name based on a list of characters.  Also, any multiple
-     *  whitespace is collapsed into a single space, and any leading or trailing
-     *  space is removed.
+     *  Cleans a Wiki name based on a list of characters.  Also, any multiple whitespace is collapsed into a single space, and any
+     *  leading or trailing space is removed.
      *
      *  @param link Link to be cleared. Null is safe, and causes this to return null.
      *  @param allowedChars Characters which are allowed in the string.
@@ -402,58 +364,44 @@ public abstract class MarkupParser
      *
      *  @since 2.6
      */
-    public static String cleanLink( String link, String allowedChars )
-    {
-        if( link == null ) return null;
+    public static String cleanLink( String link, final String allowedChars ) {
+        if( link == null ) {
+            return null;
+        }
 
         link = link.trim();
-        StringBuilder clean = new StringBuilder(link.length());
+        final StringBuilder clean = new StringBuilder( link.length() );
 
-        //
-        //  Remove non-alphanumeric characters that should not
-        //  be put inside WikiNames.  Note that all valid
-        //  Unicode letters are considered okay for WikiNames.
-        //  It is the problem of the WikiPageProvider to take
-        //  care of actually storing that information.
+        //  Remove non-alphanumeric characters that should not be put inside WikiNames.  Note that all valid Unicode letters are
+        //  considered okay for WikiNames. It is the problem of the WikiPageProvider to take care of actually storing that information.
         //
         //  Also capitalize things, if necessary.
-        //
 
         boolean isWord = true;  // If true, we've just crossed a word boundary
         boolean wasSpace = false;
-
-        for( int i = 0; i < link.length(); i++ )
-        {
+        for( int i = 0; i < link.length(); i++ ) {
             char ch = link.charAt(i);
 
-            //
             //  Cleans away repetitive whitespace and only uses the first one.
-            //
-            if( Character.isWhitespace(ch) )
-            {
-                if( wasSpace )
+            if( Character.isWhitespace(ch) ) {
+                if( wasSpace ) {
                     continue;
+                }
 
                 wasSpace = true;
-            }
-            else
-            {
+            } else {
                 wasSpace = false;
             }
 
-            //
             //  Check if it is allowed to use this char, and capitalize, if necessary.
-            //
-            if( Character.isLetterOrDigit( ch ) || allowedChars.indexOf(ch) != -1 )
-            {
+            if( Character.isLetterOrDigit( ch ) || allowedChars.indexOf( ch ) != -1 ) {
                 // Is a letter
-
-                if( isWord ) ch = Character.toUpperCase( ch );
+                if( isWord ) {
+                    ch = Character.toUpperCase( ch );
+                }
                 clean.append( ch );
                 isWord = false;
-            }
-            else
-            {
+            } else {
                 isWord = true;
             }
         }
@@ -462,8 +410,7 @@ public abstract class MarkupParser
     }
 
     /**
-     *  Cleans away extra legacy characters.  This method functions exactly
-     *  like pre-2.6 cleanLink()
+     *  Cleans away extra legacy characters.  This method functions exactly like pre-2.6 cleanLink()
      *  <P>
      *  [ This is a link ] -&gt; ThisIsALink
      *
@@ -471,8 +418,7 @@ public abstract class MarkupParser
      *  @return A cleaned link.
      *  @since 2.6
      */
-    public static String wikifyLink( final String link )
-    {
+    public static String wikifyLink( final String link ) {
         return MarkupParser.cleanLink(link, LEGACY_CHARS_ALLOWED);
     }
 


[jspwiki] 13/26: apply suggested intellij format

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 835e73793f9e2ee7154162e43ad7044ee5653f54
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 22:48:45 2020 +0100

    apply suggested intellij format
---
 .../src/main/java/org/apache/wiki/Release.java     | 62 ++++++++++------------
 1 file changed, 27 insertions(+), 35 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/Release.java b/jspwiki-main/src/main/java/org/apache/wiki/Release.java
index dde8024..6520655 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/Release.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/Release.java
@@ -24,15 +24,14 @@ import org.apache.commons.lang3.StringUtils;
 
 /**
  *  Contains release and version information.  You may also invoke this class directly, in which case it prints
- *  out the version string.  This is a handy way of checking which JSPWiki version you have - just type
- *  from a command line:
+ *  out the version string.  This is a handy way of checking which JSPWiki version you have - just type from a command line:
  *  <pre>
  *  % java -cp JSPWiki.jar org.apache.wiki.Release
  *  2.5.38
  *  </pre>
  *  <p>
- *  As a historical curiosity, this is the oldest JSPWiki file.  According to the CVS history, it dates from 6.7.2001,
- *  and it really hasn't changed much since.
+ *  As a historical curiosity, this is the oldest JSPWiki file.  According to the CVS history, it dates from 6.7.2001, and it really hasn't
+ *  changed much since.
  *  </p>
  *  @since  1.0
  */
@@ -46,9 +45,8 @@ public final class Release {
     public static final String     APPNAME       = "JSPWiki";
 
     /**
-     *  This should be empty when doing a release - otherwise keep it as "cvs" so that whenever someone checks
-     *  out the code, they know it is a bleeding-edge version.  Other possible values are "alpha" and "beta" for
-     *  alpha and beta versions, respectively.
+     *  This should be empty when doing a release - otherwise keep it as "cvs" so that whenever someone checks out the code, they know
+     *  it is a bleeding-edge version.  Other possible values are "alpha" and "beta" for alpha and beta versions, respectively.
      *  <p>
      *  If the POSTFIX is empty, it is not added to the version string.
      */
@@ -63,9 +61,8 @@ public final class Release {
     /** The minor revision.  */
     public static final int        MINORREVISION = 0;
 
-    /** The build number/identifier.  This is a String as opposed to an integer, just so that people can add
-     *  other identifiers to it.  The build number is incremented every time a committer checks in code, and reset
-     *  when the a release is made.
+    /** The build number/identifier.  This is a String as opposed to an integer, just so that people can add other identifiers to it.
+     * The build number is incremented every time a committer checks in code, and reset when the a release is made.
      *  <p>
      *  If you are a person who likes to build his own releases, we recommend that you add your initials to this
      *  identifier (e.g. "13-jj", or 49-aj").
@@ -78,18 +75,18 @@ public final class Release {
      *  This is the generic version string you should use when printing out the version.  It is of
      *  the form "VERSION.REVISION.MINORREVISION[-POSTFIX][-BUILD]".
      */
-    public static final String     VERSTR        =
-        VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : "") + ((BUILD.length() != 0 ? "-"+BUILD : ""));
+    public static final String     VERSTR        = VERSION + "." +
+                                                   REVISION + "." +
+                                                   MINORREVISION +
+                                                   ( POSTFIX.length() != 0 ? "-" + POSTFIX : "" ) +
+                                                   ( BUILD.length() != 0 ? "-" + BUILD : "" );
 
-    /**
-     *  Private constructor prevents instantiation.
-     */
+    /** Private constructor prevents instantiation. */
     private Release() {
     }
 
     /**
-     *  This method is useful for templates, because hopefully it will
-     *  not be inlined, and thus any change to version number does not
+     *  This method is useful for templates, because hopefully it will not be inlined, and thus any change to version number does not
      *  need recompiling the pages.
      *
      *  @since 2.1.26.
@@ -101,32 +98,30 @@ public final class Release {
 
     /**
      *  Returns true, if this version of JSPWiki is newer or equal than what is requested.
+     *
      *  @param version A version parameter string (a.b.c-something). B and C are optional.
      *  @return A boolean value describing whether the given version is newer than the current JSPWiki.
      *  @since 2.4.57
      *  @throws IllegalArgumentException If the version string could not be parsed.
      */
-    public static boolean isNewerOrEqual( String version ) throws IllegalArgumentException {
+    public static boolean isNewerOrEqual( final String version ) throws IllegalArgumentException {
         if( version == null ) {
         	return true;
         }
-        String[] versionComponents = StringUtils.split( version, VERSION_SEPARATORS );
-        int reqVersion       = versionComponents.length > 0 ? Integer.parseInt( versionComponents[0] ) : Release.VERSION;
-        int reqRevision      = versionComponents.length > 1 ? Integer.parseInt( versionComponents[1] ) : Release.REVISION;
-        int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt( versionComponents[2] ) : Release.MINORREVISION;
+        final String[] versionComponents = StringUtils.split( version, VERSION_SEPARATORS );
+        final int reqVersion       = versionComponents.length > 0 ? Integer.parseInt( versionComponents[0] ) : Release.VERSION;
+        final int reqRevision      = versionComponents.length > 1 ? Integer.parseInt( versionComponents[1] ) : Release.REVISION;
+        final int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt( versionComponents[2] ) : Release.MINORREVISION;
 
         if( VERSION == reqVersion ) {
             if( REVISION == reqRevision ) {
                 if( MINORREVISION == reqMinorRevision ) {
                     return true;
                 }
-
                 return MINORREVISION > reqMinorRevision;
             }
-
             return REVISION > reqRevision;
         }
-
         return VERSION > reqVersion;
     }
 
@@ -138,28 +133,25 @@ public final class Release {
      *  @since 2.4.57
      *  @throws IllegalArgumentException If the version string could not be parsed.
      */
-    public static boolean isOlderOrEqual( String version ) throws IllegalArgumentException {
+    public static boolean isOlderOrEqual( final String version ) throws IllegalArgumentException {
         if( version == null ) {
         	return true;
         }
 
-        String[] versionComponents = StringUtils.split( version, VERSION_SEPARATORS );
-        int reqVersion       = versionComponents.length > 0 ? Integer.parseInt( versionComponents[0] ) : Release.VERSION;
-        int reqRevision      = versionComponents.length > 1 ? Integer.parseInt( versionComponents[1] ) : Release.REVISION;
-        int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt( versionComponents[2] ) : Release.MINORREVISION;
+        final String[] versionComponents = StringUtils.split( version, VERSION_SEPARATORS );
+        final int reqVersion       = versionComponents.length > 0 ? Integer.parseInt( versionComponents[0] ) : Release.VERSION;
+        final int reqRevision      = versionComponents.length > 1 ? Integer.parseInt( versionComponents[1] ) : Release.REVISION;
+        final int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt( versionComponents[2] ) : Release.MINORREVISION;
 
         if( VERSION == reqVersion ) {
             if( REVISION == reqRevision ) {
                 if( MINORREVISION == reqMinorRevision ) {
                     return true;
                 }
-
                 return MINORREVISION < reqMinorRevision;
             }
-
             return REVISION < reqRevision;
         }
-
         return VERSION < reqVersion;
     }
 
@@ -174,8 +166,8 @@ public final class Release {
      *
      *  @param argv The argument string.  This class takes in no arguments.
      */
-    public static void main( String[] argv ) {
-        System.out.println(VERSTR);
+    public static void main( final String[] argv ) {
+        System.out.println( VERSTR );
     }
 
 }


[jspwiki] 02/26: apply suggested fixes + formatting by intellij

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 06ee24657e279e9261475cc21255e8eaa3156c9d
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Jan 11 01:31:07 2020 +0100

    apply suggested fixes + formatting by intellij
---
 .../wiki/render/CustomXMLOutputProcessor.java      |   5 +-
 .../java/org/apache/wiki/render/XHTMLRenderer.java |   5 +-
 .../wiki/render/WysiwygEditingRendererTest.java    |  43 +++----
 .../InterWikiLinkAttributeProviderState.java       |   2 +-
 .../WysiwygEditingAttributeProviderState.java      |  14 +--
 .../AccessRuleLinkNodePostProcessorState.java      |   2 +-
 .../InterWikiLinkNodePostProcessorState.java       |   2 +-
 .../JSPWikiLinkNodePostProcessor.java              |   8 +-
 .../MetadataLinkNodePostProcessorState.java        |   4 +-
 .../NodePostProcessorStateCommonOperations.java    |   2 +-
 .../PluginLinkNodePostProcessorState.java          |   2 +-
 .../VariableLinkNodePostProcessorState.java        |   2 +-
 .../markdown/renderer/JSPWikiLinkRenderer.java     |  15 ++-
 .../wiki/parser/markdown/MarkdownDocument.java     |   2 +-
 .../wiki/parser/markdown/MarkdownParser.java       |  13 +--
 .../apache/wiki/render/MarkdownRendererTest.java   | 126 ++++++++++-----------
 16 files changed, 115 insertions(+), 132 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/CustomXMLOutputProcessor.java b/jspwiki-main/src/main/java/org/apache/wiki/render/CustomXMLOutputProcessor.java
index da68a9d..de5cb56 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/CustomXMLOutputProcessor.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/CustomXMLOutputProcessor.java
@@ -33,11 +33,8 @@ import java.io.Writer;
  */
 public class CustomXMLOutputProcessor extends AbstractXMLOutputProcessor {
 
-    protected void attributeEscapedEntitiesFilter( final Writer out,
-                                                   final FormatStack fstack, final String value ) throws IOException {
-
+    protected void attributeEscapedEntitiesFilter( final Writer out, final FormatStack fstack, final String value ) throws IOException {
         write( out, Format.escapeAttribute( fstack.getEscapeStrategy(), value ) );
-
     }
 
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/XHTMLRenderer.java b/jspwiki-main/src/main/java/org/apache/wiki/render/XHTMLRenderer.java
index 49e6a4d..5ffe2f9 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/XHTMLRenderer.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/XHTMLRenderer.java
@@ -27,9 +27,8 @@ import java.io.IOException;
 import java.io.StringWriter;
 
 /**
- *  Implements a WikiRendered that outputs XHTML.  Because the internal DOM
- *  representation is in XHTML already, this just basically dumps out everything
- *  out in a non-prettyprinted format.
+ *  Implements a WikiRendered that outputs XHTML.  Because the internal DOM  representation is in XHTML already, this just basically
+ *  dumps out everything out in a non-prettyprinted format.
  *
  *  @since  2.4
  */
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/render/WysiwygEditingRendererTest.java b/jspwiki-main/src/test/java/org/apache/wiki/render/WysiwygEditingRendererTest.java
index fc55cb7..5dd12c5 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/render/WysiwygEditingRendererTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/render/WysiwygEditingRendererTest.java
@@ -18,10 +18,6 @@
  */
 package org.apache.wiki.render;
 
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Properties;
-
 import org.apache.wiki.TestEngine;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.WikiPage;
@@ -32,45 +28,41 @@ import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-public class WysiwygEditingRendererTest
-{
-    protected TestEngine testEngine;
+import java.io.IOException;
+import java.io.StringReader;
+
+public class WysiwygEditingRendererTest {
 
-    @BeforeEach
-    public void setUp() throws Exception
-    {
-        Properties props = TestEngine.getTestProperties();
-        testEngine = new TestEngine(props);
+    TestEngine testEngine = TestEngine.build();
 
+    @BeforeEach
+    public void setUp() throws Exception {
         testEngine.saveText( "WysiwygEditingRendererTest", "test page" );
         testEngine.saveText( "This Pagename Has Spaces", "This Pagename Has Spaces" );
     }
 
     @AfterEach
-    public void tearDown()
-    {
+    public void tearDown() {
         testEngine.deleteTestPage( "WysiwygEditingRendererTest" );
         testEngine.deleteTestPage( "This Pagename Has Spaces" );
     }
 
-    private String render(String s) throws IOException
-    {
-        WikiPage dummyPage = new WikiPage(testEngine,"TestPage");
-        WikiContext ctx = new WikiContext(testEngine,dummyPage);
+    private String render( final String s ) throws IOException {
+        final WikiPage dummyPage = new WikiPage(testEngine,"TestPage");
+        final WikiContext ctx = new WikiContext(testEngine,dummyPage);
 
-        StringReader in = new StringReader(s);
+        final StringReader in = new StringReader(s);
 
-        JSPWikiMarkupParser p = new JSPWikiMarkupParser( ctx, in );
-        WikiDocument d = p.parse();
+        final JSPWikiMarkupParser p = new JSPWikiMarkupParser( ctx, in );
+        final WikiDocument d = p.parse();
 
-        WysiwygEditingRenderer wer = new WysiwygEditingRenderer( ctx, d );
+        final WysiwygEditingRenderer wer = new WysiwygEditingRenderer( ctx, d );
 
         return wer.getString();
     }
 
     @Test
-    public void testDefinedPageLink() throws Exception
-    {
+    public void testDefinedPageLink() throws Exception {
         String src = "[WysiwygEditingRendererTest]";
         Assertions.assertEquals( "<a class=\"wikipage\" href=\"WysiwygEditingRendererTest\">WysiwygEditingRendererTest</a>", render(src) );
 
@@ -85,8 +77,7 @@ public class WysiwygEditingRendererTest
     }
 
     @Test
-    public void testUndefinedPageLink() throws Exception
-    {
+    public void testUndefinedPageLink() throws Exception {
         String src = "[UndefinedPageLinkHere]";
         Assertions.assertEquals( "<a class=\"createpage\" href=\"UndefinedPageLinkHere\">UndefinedPageLinkHere</a>", render(src) );
 
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
index 1a82aee..3c7daf4 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/InterWikiLinkAttributeProviderState.java
@@ -45,7 +45,7 @@ public class InterWikiLinkAttributeProviderState implements NodeAttributeProvide
         this.wikiContext = wikiContext;
         this.linkOperations = new LinkParsingOperations( wikiContext );
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
index 704cd70..48c5406 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/attributeprovider/WysiwygEditingAttributeProviderState.java
@@ -40,7 +40,7 @@ public class WysiwygEditingAttributeProviderState implements NodeAttributeProvid
     public WysiwygEditingAttributeProviderState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
@@ -52,17 +52,15 @@ public class WysiwygEditingAttributeProviderState implements NodeAttributeProvid
     public void setAttributes( final Attributes attributes, final JSPWikiLink link ) {
         if( m_wysiwygEditorMode ) {
             if( attributes.getValue( "class" ) != null ) {
-                String href = attributes.getValue( "href" );
-                XHtmlToWikiConfig wikiConfig = new XHtmlToWikiConfig( wikiContext );
+                final String href = attributes.getValue( "href" );
+                final XHtmlToWikiConfig wikiConfig = new XHtmlToWikiConfig( wikiContext );
                 // Get the url for wiki page link - it's typically "Wiki.jsp?page=MyPage"
                 // or when using the ShortURLConstructor option, it's "wiki/MyPage" .
-                String wikiPageLinkUrl = wikiConfig.getWikiJspPage();
-                String editPageLinkUrl = wikiConfig.getEditJspPage();
+                final String wikiPageLinkUrl = wikiConfig.getWikiJspPage();
+                final String editPageLinkUrl = wikiConfig.getEditJspPage();
                 if( href != null && href.startsWith( wikiPageLinkUrl ) ) {
-                    // Remove the leading url string so that users will only see the
-                    // wikipage's name when editing an existing wiki link.
+                    // Remove the leading url string so that users will only see the wikipage's name when editing an existing wiki link.
                     // For example, change "Wiki.jsp?page=MyPage" to just "MyPage".
-
                     String newHref = href.substring( wikiPageLinkUrl.length() );
 
                     // Convert "This%20Pagename%20Has%20Spaces" to "This Pagename Has Spaces"
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
index cbbf04a..c7e46d4 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/AccessRuleLinkNodePostProcessorState.java
@@ -41,7 +41,7 @@ public class AccessRuleLinkNodePostProcessorState implements NodePostProcessorSt
     public AccessRuleLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
index 128b6dd..66b9cd7 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/InterWikiLinkNodePostProcessorState.java
@@ -54,7 +54,7 @@ public class InterWikiLinkNodePostProcessorState implements NodePostProcessorSta
         this.document = document;
         this.m_useOutlinkImage = wikiContext.getBooleanWikiProperty( MarkupParser.PROP_USEOUTLINKIMAGE, m_useOutlinkImage );
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/JSPWikiLinkNodePostProcessor.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/JSPWikiLinkNodePostProcessor.java
index f9e7d76..2aba7de 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/JSPWikiLinkNodePostProcessor.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/JSPWikiLinkNodePostProcessor.java
@@ -59,7 +59,7 @@ public class JSPWikiLinkNodePostProcessor extends NodePostProcessor {
     @Override
     public void process( final NodeTracker state, final Node node ) {
         if( node instanceof Link ) {
-            JSPWikiLink link = replaceLinkWithJSPWikiLink( state, node );
+            final JSPWikiLink link = replaceLinkWithJSPWikiLink( state, node );
 
             final NodePostProcessorState< JSPWikiLink > linkPostProcessor;
             if( linkOperations.isAccessRule( link.getUrl().toString() ) ) {
@@ -86,9 +86,9 @@ public class JSPWikiLinkNodePostProcessor extends NodePostProcessor {
     }
 
     JSPWikiLink replaceLinkWithJSPWikiLink( final NodeTracker state, final Node node ) {
-        JSPWikiLink link = new JSPWikiLink( ( Link )node );
-        Node previous = node.getPrevious();
-        Node parent = node.getParent();
+        final JSPWikiLink link = new JSPWikiLink( ( Link )node );
+        final Node previous = node.getPrevious();
+        final Node parent = node.getParent();
 
         link.takeChildren( node );
         node.unlink();
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
index bc5526b..99a9ed5 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/MetadataLinkNodePostProcessorState.java
@@ -43,7 +43,7 @@ public class MetadataLinkNodePostProcessorState implements NodePostProcessorStat
     public MetadataLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
@@ -57,7 +57,7 @@ public class MetadataLinkNodePostProcessorState implements NodePostProcessorStat
         try {
             final String args = metadataLine.substring( metadataLine.indexOf(' '), metadataLine.length() - 1 );
             String name = args.substring( 0, args.indexOf( '=' ) );
-            String val = args.substring( args.indexOf( '=' ) + 1, args.length() );
+            String val = args.substring( args.indexOf( '=' ) + 1 );
 
             name = name.trim();
             val = val.trim();
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
index 635d3e7..87d5b3c 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/NodePostProcessorStateCommonOperations.java
@@ -48,7 +48,7 @@ class NodePostProcessorStateCommonOperations {
 
     static void addOutlinkImage( final NodeTracker state, final Node node, final WikiContext wikiContext, final boolean useOutlinkImage ) {
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        final boolean wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable.booleanValue();
+        final boolean wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable;
 
         if( useOutlinkImage && !wysiwygEditorMode ) {
             final String m_outlinkImageURL = wikiContext.getURL( WikiContext.NONE, MarkupParser.OUTLINK_IMAGE );
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
index e40d75a..4e13e3d 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/PluginLinkNodePostProcessorState.java
@@ -48,7 +48,7 @@ public class PluginLinkNodePostProcessorState implements NodePostProcessorState<
     public PluginLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable.booleanValue() : false;
+        m_wysiwygEditorMode = wysiwygVariable != null ? wysiwygVariable : false;
     }
 
     /**
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
index bea0820..8855af5 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/extensions/jspwikilinks/postprocessor/VariableLinkNodePostProcessorState.java
@@ -40,7 +40,7 @@ public class VariableLinkNodePostProcessorState implements NodePostProcessorStat
     public VariableLinkNodePostProcessorState( final WikiContext wikiContext ) {
         this.wikiContext = wikiContext;
         final Boolean wysiwygVariable = ( Boolean )wikiContext.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE );
-        m_wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable.booleanValue();
+        m_wysiwygEditorMode = wysiwygVariable != null && wysiwygVariable;
     }
 
     /**
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/renderer/JSPWikiLinkRenderer.java b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/renderer/JSPWikiLinkRenderer.java
index befdc7d..70895c7 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/renderer/JSPWikiLinkRenderer.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/markdown/renderer/JSPWikiLinkRenderer.java
@@ -18,11 +18,6 @@
 */
 package org.apache.wiki.markdown.renderer;
 
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.wiki.markdown.nodes.JSPWikiLink;
-
 import com.vladsch.flexmark.html.CustomNodeRenderer;
 import com.vladsch.flexmark.html.HtmlWriter;
 import com.vladsch.flexmark.html.renderer.LinkType;
@@ -30,6 +25,10 @@ import com.vladsch.flexmark.html.renderer.NodeRenderer;
 import com.vladsch.flexmark.html.renderer.NodeRendererContext;
 import com.vladsch.flexmark.html.renderer.NodeRenderingHandler;
 import com.vladsch.flexmark.html.renderer.ResolvedLink;
+import org.apache.wiki.markdown.nodes.JSPWikiLink;
+
+import java.util.HashSet;
+import java.util.Set;
 
 
 /**
@@ -44,8 +43,8 @@ public class JSPWikiLinkRenderer implements NodeRenderer {
      */
     @Override
     public Set< NodeRenderingHandler< ? > > getNodeRenderingHandlers() {
-        HashSet< NodeRenderingHandler< ? > > set = new HashSet< NodeRenderingHandler< ? > >();
-        set.add( new NodeRenderingHandler< JSPWikiLink >( JSPWikiLink.class, new CustomNodeRenderer< JSPWikiLink >() {
+        final HashSet< NodeRenderingHandler< ? > > set = new HashSet<>();
+        set.add( new NodeRenderingHandler<>( JSPWikiLink.class, new CustomNodeRenderer< JSPWikiLink >() {
 
             /**
              * {@inheritDoc}
@@ -56,7 +55,7 @@ public class JSPWikiLinkRenderer implements NodeRenderer {
                     context.renderChildren( node );
                 } else {
                     // standard Link Rendering
-                    ResolvedLink resolvedLink = context.resolveLink( LinkType.LINK, node.getUrl().unescape(), null );
+                    final ResolvedLink resolvedLink = context.resolveLink( LinkType.LINK, node.getUrl().unescape(), null );
 
                     html.attr( "href", resolvedLink.getUrl() );
                     if( node.getTitle().isNotNull() ) {
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownDocument.java b/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownDocument.java
index 64a2e20..b8b0e28 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownDocument.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownDocument.java
@@ -59,7 +59,7 @@ public class MarkdownDocument extends WikiDocument {
 	 * @return configuration options for MarkdownRenderers.
 	 */
 	public static MutableDataSet options( final WikiContext context ) {
-		MutableDataSet options = new MutableDataSet();
+		final MutableDataSet options = new MutableDataSet();
 		options.setFrom( ParserEmulationProfile.COMMONMARK );
 		// align style of Markdown's footnotes extension with jspwiki footnotes refs
 		options.set( FootnoteExtension.FOOTNOTE_LINK_REF_CLASS, JSPWikiMarkupParser.CLASS_FOOTNOTE_REF );
diff --git a/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownParser.java b/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownParser.java
index 4d39810..c98f4ef 100755
--- a/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownParser.java
+++ b/jspwiki-markdown/src/main/java/org/apache/wiki/parser/markdown/MarkdownParser.java
@@ -18,15 +18,14 @@
  */
 package org.apache.wiki.parser.markdown;
 
-import java.io.IOException;
-import java.io.Reader;
-
+import com.vladsch.flexmark.parser.Parser;
+import com.vladsch.flexmark.util.ast.Node;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.parser.MarkupParser;
 import org.apache.wiki.parser.WikiDocument;
 
-import com.vladsch.flexmark.parser.Parser;
-import com.vladsch.flexmark.util.ast.Node;
+import java.io.IOException;
+import java.io.Reader;
 
 
 /**
@@ -49,8 +48,8 @@ public class MarkdownParser extends MarkupParser {
 	 */
 	@Override
 	public WikiDocument parse() throws IOException {
-		Node document = parser.parseReader( m_in );
-		MarkdownDocument md = new MarkdownDocument( m_context.getPage(), document );
+		final Node document = parser.parseReader( m_in );
+		final MarkdownDocument md = new MarkdownDocument( m_context.getPage(), document );
         md.setContext( m_context );
 
 		return md;
diff --git a/jspwiki-markdown/src/test/java/org/apache/wiki/render/MarkdownRendererTest.java b/jspwiki-markdown/src/test/java/org/apache/wiki/render/MarkdownRendererTest.java
index 4ae2dde..19bbb2d 100755
--- a/jspwiki-markdown/src/test/java/org/apache/wiki/render/MarkdownRendererTest.java
+++ b/jspwiki-markdown/src/test/java/org/apache/wiki/render/MarkdownRendererTest.java
@@ -50,7 +50,7 @@ public class MarkdownRendererTest {
 
     @Test
     public void testMarkupSimpleMarkdown() throws Exception {
-        String src = "This should be a **bold**";
+        final String src = "This should be a **bold**";
 
         Assertions.assertEquals( "<p>This should be a <strong>bold</strong></p>\n", translate( src ) );
     }
@@ -58,123 +58,123 @@ public class MarkdownRendererTest {
     @Test
     public void testMarkupExtensionSelfViewLink() throws Exception {
     	newPage( "MarkupExtensionSelfViewLink" );
-        String src = "This should be a [MarkupExtensionSelfViewLink]()";
+        final String src = "This should be a [MarkupExtensionSelfViewLink]()";
 
         Assertions.assertEquals( "<p>This should be a <a href=\"/test/Wiki.jsp?page=MarkupExtensionSelfViewLink\" class=\"wikipage\">MarkupExtensionSelfViewLink</a></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionSelfEditLink() throws Exception {
-        String src = "This should be a [self<->link]()";
+        final String src = "This should be a [self<->link]()";
 
         Assertions.assertEquals( "<p>This should be a <a href=\"/test/Edit.jsp?page=self%3C-%3Elink\" title=\"Create &quot;self&lt;-&gt;link&quot;\" class=\"createpage\">self&lt;-&gt;link</a></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionExternalLink() throws Exception {
         testEngine.getWikiProperties().setProperty( "jspwiki.translatorReader.useOutlinkImage", "true" );
-        String src = "This should be an [external link](https://jspwiki.apache.org)";
+        final String src = "This should be an [external link](https://jspwiki.apache.org)";
 
         Assertions.assertEquals( "<p>This should be an <a href=\"https://jspwiki.apache.org\" class=\"external\">external link</a><img class=\"outlink\" alt=\"\" src=\"/test/images/out.png\" /></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
         testEngine.getWikiProperties().remove( "jspwiki.translatorReader.useOutlinkImage" );
     }
 
     @Test
     public void testMarkupExtensionInterWikiLink() throws Exception {
-        String src = "This should be an [interwiki link](JSPWiki:About)";
+        final String src = "This should be an [interwiki link](JSPWiki:About)";
 
         Assertions.assertEquals( "<p>This should be an <a href=\"http://jspwiki-wiki.apache.org/Wiki.jsp?page=About\" class=\"interwiki\">interwiki link</a></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionWrongInterWikiLink() throws Exception {
-        String src = "This should be an [interwiki link](JSPWiko:About)";
+        final String src = "This should be an [interwiki link](JSPWiko:About)";
 
         Assertions.assertEquals( "<p>This should be an <span class=\"error\">No InterWiki reference defined in properties for Wiki called \"JSPWiko\"!</span></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionACL() throws Exception {
-        String src = "[{ALLOW view PerryMason}]() This should be visible if the ACL allows you to see it";
+        final String src = "[{ALLOW view PerryMason}]() This should be visible if the ACL allows you to see it";
         // text is seen because although ACL is added to the page, it is not applied while parsing / rendering
         Assertions.assertEquals( "<p> This should be visible if the ACL allows you to see it</p>\n", translate( src ) );
         // in any case, we also check that the created wikipage has the ACL added
         Assertions.assertEquals( "  user = PerryMason: ((\"org.apache.wiki.auth.permissions.PagePermission\",\"JSPWiki:testpage\",\"view\"))\n",
-        		             testEngine.getPageManager().getPage( PAGE_NAME ).getAcl().toString() );
+        		                 testEngine.getPageManager().getPage( PAGE_NAME ).getAcl().toString() );
     }
 
     @Test
     public void testMarkupExtensionMetadata() throws Exception {
-        String src = "[{SET Perry='Mason'}]() Some text after setting metadata";
+        final String src = "[{SET Perry='Mason'}]() Some text after setting metadata";
         Assertions.assertEquals( "<p> Some text after setting metadata</p>\n", translate( src ) );
         Assertions.assertEquals( "Mason", testEngine.getPageManager().getPage( PAGE_NAME ).getAttribute( "Perry" ) );
     }
 
     @Test
     public void testMarkupExtensionPlugin() throws Exception {
-        String src = "[{SamplePlugin text=test}]()";
+        final String src = "[{SamplePlugin text=test}]()";
         Assertions.assertEquals( "<p>test</p>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionTOCPluginGetsSubstitutedWithMDTocExtension() throws Exception {
-        String src = "[{TableOfContents}]()\n" +
-                     "# Header 1\n" +
-                     "## Header 2\n" +
-                     "## Header 2\n";
+        final String src = "[{TableOfContents}]()\n" +
+                           "# Header 1\n" +
+                           "## Header 2\n" +
+                           "## Header 2\n";
         Assertions.assertEquals( "<p><div class=\"toc\">\n" +
-                             "<div class=\"collapsebox\">\n" +
-                             "<h4 id=\"section-TOC\">Table of Contents</h4>\n" +
-                             "<ul>\n" +
-                             "<li><a href=\"#header-1\">Header 1</a>\n" +
-                             "<ul>\n" +
-                             "<li><a href=\"#header-2\">Header 2</a></li>\n" +
-                             "<li><a href=\"#header-2-1\">Header 2</a></li>\n" +
-                             "</ul>\n" +
-                             "</li>\n" +
-                             "</ul>\n" +
-                             "</div>\n" +
-                             "</div>\n" +
-                             "</p>\n" +
-                             "<h1 id=\"header-1\">Header 1</h1>\n" +
-                             "<h2 id=\"header-2\">Header 2</h2>\n" +
-                             "<h2 id=\"header-2-1\">Header 2</h2>\n", translate( src ) );
+                                 "<div class=\"collapsebox\">\n" +
+                                 "<h4 id=\"section-TOC\">Table of Contents</h4>\n" +
+                                 "<ul>\n" +
+                                 "<li><a href=\"#header-1\">Header 1</a>\n" +
+                                 "<ul>\n" +
+                                 "<li><a href=\"#header-2\">Header 2</a></li>\n" +
+                                 "<li><a href=\"#header-2-1\">Header 2</a></li>\n" +
+                                 "</ul>\n" +
+                                 "</li>\n" +
+                                 "</ul>\n" +
+                                 "</div>\n" +
+                                 "</div>\n" +
+                                 "</p>\n" +
+                                 "<h1 id=\"header-1\">Header 1</h1>\n" +
+                                 "<h2 id=\"header-2\">Header 2</h2>\n" +
+                                "<h2 id=\"header-2-1\">Header 2</h2>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionNonExistentPlugin() throws Exception {
-        String src = "[{PampleSlugin text=test}]()";
+        final String src = "[{PampleSlugin text=test}]()";
         Assertions.assertEquals( "<p><span class=\"error\">JSPWiki : testpage - Plugin insertion failed: Could not find plugin PampleSlugin</span></p>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionVariable0() throws Exception {
-        String src = "Some text with some pre-set variable: [{$applicationname}]()";
+        final String src = "Some text with some pre-set variable: [{$applicationname}]()";
         Assertions.assertEquals( "<p>Some text with some pre-set variable: JSPWiki</p>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionVariable1() throws Exception {
-        String src = "[{SET Perry='Mason'}]() Some text after setting some metadata: [{$Perry}]()";
+        final String src = "[{SET Perry='Mason'}]() Some text after setting some metadata: [{$Perry}]()";
         Assertions.assertEquals( "<p> Some text after setting some metadata: Mason</p>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionFootnote0() throws Exception {
-        String src = "Footnote[1]()";
+        final String src = "Footnote[1]()";
         Assertions.assertEquals( "<p>Footnote<a href=\"#ref-testpage-1\" class=\"footnoteref\">[1]</a></p>\n", translate( src ) );
     }
 
     @Test
     public void testMarkupExtensionFootnoteMD() throws Exception {
-        String src = "text [^footnote] embedded.\n\n" +
-        		     "[^footnote]: footnote text\n" +
-        		     "with continuation";
+        final String src = "text [^footnote] embedded.\n\n" +
+        	               "[^footnote]: footnote text\n" +
+                           "with continuation";
         Assertions.assertEquals( "<p>text <sup id=\"fnref-1\"><a class=\"footnoteref\" href=\"#fn-1\">1</a></sup> embedded.</p>\n" +
         		             "<div class=\"footnotes\">\n" +
         		             "<hr />\n" +
@@ -190,44 +190,44 @@ public class MarkdownRendererTest {
 
     @Test
     public void testAttachmentLink() throws Exception {
-        String src = "This should be an [attachment link](Test/TestAtt.txt)";
+        final String src = "This should be an [attachment link](Test/TestAtt.txt)";
         newPage( "Test" );
 
-        Attachment att = new Attachment( testEngine, "Test", "TestAtt.txt" );
+        final Attachment att = new Attachment( testEngine, "Test", "TestAtt.txt" );
         att.setAuthor( "FirstPost" );
         testEngine.getAttachmentManager().storeAttachment( att, testEngine.makeAttachmentFile() );
 
         Assertions.assertEquals( "<p>This should be an <a href=\"/test/attach/Test/TestAtt.txt\" class=\"attachment\">attachment link</a>" +
-                             "<a href=\"/test/PageInfo.jsp?page=Test/TestAtt.txt\" class=\"infolink\">" +
-                               "<img src=\"/test/images/attachment_small.png\" border=\"0\" alt=\"(info)\" />" +
-                             "</a></p>\n",
-                translate( src ) );
+                                 "<a href=\"/test/PageInfo.jsp?page=Test/TestAtt.txt\" class=\"infolink\">" +
+                                   "<img src=\"/test/images/attachment_small.png\" border=\"0\" alt=\"(info)\" />" +
+                                 "</a></p>\n",
+                                 translate( src ) );
     }
 
     @Test
     public void testInlineImages() throws Exception {
-        String src = "Link [test](http://www.ecyrd.com/test.png)";
+        final String src = "Link [test](http://www.ecyrd.com/test.png)";
 
         Assertions.assertEquals( "<p>Link <img class=\"inline\" src=\"http://www.ecyrd.com/test.png\" alt=\"test\" /></p>\n", translate( src ) );
     }
 
     @Test
     public void testInlineImages2() throws Exception {
-        String src = "Link [test](http://www.ecyrd.com/test.ppm)";
+        final String src = "Link [test](http://www.ecyrd.com/test.ppm)";
 
         Assertions.assertEquals( "<p>Link <a href=\"http://www.ecyrd.com/test.ppm\" class=\"external\">test</a></p>\n", translate( src ) );
     }
 
     @Test
     public void testInlineImages3() throws Exception {
-        String src = "Link [test](http://images.com/testi)";
+        final String src = "Link [test](http://images.com/testi)";
 
         Assertions.assertEquals( "<p>Link <img class=\"inline\" src=\"http://images.com/testi\" alt=\"test\" /></p>\n", translate( src ) );
     }
 
     @Test
     public void testInlineImages4() throws Exception {
-        String src = "Link [test](http://foobar.jpg)";
+        final String src = "Link [test](http://foobar.jpg)";
 
         Assertions.assertEquals( "<p>Link <img class=\"inline\" src=\"http://foobar.jpg\" alt=\"test\" /></p>\n", translate( src ) );
     }
@@ -235,33 +235,33 @@ public class MarkdownRendererTest {
     // No link text should be just embedded link.
     @Test
     public void testInlineImagesLink2() throws Exception {
-        String src = "Link [http://foobar.jpg]()";
+        final String src = "Link [http://foobar.jpg]()";
 
         Assertions.assertEquals( "<p>Link <img class=\"inline\" src=\"http://foobar.jpg\" alt=\"http://foobar.jpg\" /></p>\n", translate( src ) );
     }
 
     @Test
     public void testInlineImagesLink() throws Exception {
-        String src = "Link [http://link.to/](http://foobar.jpg)";
+        final String src = "Link [http://link.to/](http://foobar.jpg)";
 
         Assertions.assertEquals( "<p>Link <a href=\"http://link.to/\" class=\"external\"><img class=\"inline\" src=\"http://foobar.jpg\" alt=\"http://link.to/\" /></a></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testInlineImagesLink3() throws Exception {
-        String src = "Link [SandBox](http://foobar.jpg)";
+        final String src = "Link [SandBox](http://foobar.jpg)";
 
         newPage( "SandBox" );
 
         Assertions.assertEquals( "<p>Link <a href=\"/test/Wiki.jsp?page=SandBox\" class=\"wikipage\"><img class=\"inline\" src=\"http://foobar.jpg\" alt=\"SandBox\" /></a></p>\n",
-                             translate( src ) );
+                                 translate( src ) );
     }
 
     @Test
     public void testHeadersWithSameNameGetIdWithCounter() throws Exception {
-        String src = "### Awesome H3\n" +
-                     "### Awesome H3";
+        final String src = "### Awesome H3\n" +
+                           "### Awesome H3";
 
         Assertions.assertEquals( "<h3 id=\"awesome-h3\">Awesome H3</h3>\n" +
                              "<h3 id=\"awesome-h3-1\">Awesome H3</h3>\n",
@@ -279,7 +279,7 @@ public class MarkdownRendererTest {
 
     @AfterEach
     public void tearDown() {
-        for( String name : created ) {
+        for( final String name : created ) {
             testEngine.deleteTestPage(name);
             TestEngine.deleteAttachments(name);
         }
@@ -301,9 +301,9 @@ public class MarkdownRendererTest {
     }
 
     String translate( final WikiEngine e, final WikiPage p, final String src ) throws Exception {
-        WikiContext context = new WikiContext( e, testEngine.newHttpRequest(), p );
-        MarkdownParser tr = new MarkdownParser( context, new BufferedReader( new StringReader( src ) ) );
-        MarkdownRenderer conv = new MarkdownRenderer( context, tr.parse() );
+        final WikiContext context = new WikiContext( e, testEngine.newHttpRequest(), p );
+        final MarkdownParser tr = new MarkdownParser( context, new BufferedReader( new StringReader( src ) ) );
+        final MarkdownRenderer conv = new MarkdownRenderer( context, tr.parse() );
         newPage( p.getName(), src );
 
         return conv.getString();


[jspwiki] 07/26: extract text nodes extraction routine from Dom to XmlUtils

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 5851edd12f623e4db3fd28941afbd29f5ef41197
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Jan 13 00:16:46 2020 +0100

    extract text nodes extraction routine from Dom to XmlUtils
---
 .../apache/wiki/parser/JSPWikiMarkupParser.java    | 53 ++++++----------------
 .../org/apache/wiki/render/CleanTextRenderer.java  | 30 ++----------
 .../main/java/org/apache/wiki/util/XmlUtil.java    | 35 +++++++++++---
 .../java/org/apache/wiki/util/XmlUtilTest.java     | 17 +++++++
 4 files changed, 65 insertions(+), 70 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
index 7dad359..567e65c 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/JSPWikiMarkupParser.java
@@ -38,8 +38,8 @@ import org.apache.wiki.auth.WikiSecurityException;
 import org.apache.wiki.auth.acl.Acl;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.preferences.Preferences;
-import org.apache.wiki.render.CleanTextRenderer;
 import org.apache.wiki.util.TextUtil;
+import org.apache.wiki.util.XmlUtil;
 import org.jdom2.Attribute;
 import org.jdom2.Content;
 import org.jdom2.Element;
@@ -85,7 +85,7 @@ public class JSPWikiMarkupParser extends MarkupParser {
     protected static final int              IMAGEWIKILINK = 9;
     protected static final int              ATTACHMENT    = 10;
 
-    private static Logger log = Logger.getLogger( JSPWikiMarkupParser.class );
+    private static final Logger log = Logger.getLogger( JSPWikiMarkupParser.class );
 
     private boolean        m_isbold       = false;
     private boolean        m_isitalic     = false;
@@ -221,17 +221,12 @@ public class JSPWikiMarkupParser extends MarkupParser {
      *  @param text Text that should be passed to the mutate() method of each of the mutators in the chain.
      *  @return The result of the mutation.
      */
-    protected String callMutatorChain( Collection< StringTransmutator > list, String text )
-    {
-        if( list == null || list.size() == 0 )
-        {
+    protected String callMutatorChain( final Collection< StringTransmutator > list, String text ) {
+        if( list == null || list.size() == 0 ) {
             return text;
         }
 
-        for( Iterator< StringTransmutator > i = list.iterator(); i.hasNext(); )
-        {
-            StringTransmutator m = i.next();
-
+        for( final StringTransmutator m : list ) {
             text = m.mutate( m_context, text );
         }
 
@@ -808,19 +803,13 @@ public class JSPWikiMarkupParser extends MarkupParser {
     private JSPWikiMarkupParser m_cleanTranslator;
 
     /**
-     *  Does a lazy init.  Otherwise, we would get into a situation
-     *  where HTMLRenderer would try and boot a TranslatorReader before
+     *  Does a lazy init.  Otherwise, we would get into a situation where HTMLRenderer would try and boot a TranslatorReader before
      *  the TranslatorReader it is contained by is up.
      */
-    private JSPWikiMarkupParser getCleanTranslator()
-    {
-        if( m_cleanTranslator == null )
-        {
-            WikiContext dummyContext = new WikiContext( m_engine,
-                                                        m_context.getHttpRequest(),
-                                                        m_context.getPage() );
+    private JSPWikiMarkupParser getCleanTranslator() {
+        if( m_cleanTranslator == null ) {
+            final WikiContext dummyContext = new WikiContext( m_engine, m_context.getHttpRequest(), m_context.getPage() );
             m_cleanTranslator = new JSPWikiMarkupParser( dummyContext, null );
-
             m_cleanTranslator.m_allowHTML = true;
         }
 
@@ -834,27 +823,20 @@ public class JSPWikiMarkupParser extends MarkupParser {
      *  Counts also duplicate headings (= headings with similar name), and
      *  attaches a counter.
      */
-    private String makeHeadingAnchor( String baseName, String title, Heading hd )
-    {
+    private String makeHeadingAnchor( final String baseName, String title, final Heading hd ) {
         hd.m_titleText = title;
         title = MarkupParser.wikifyLink( title );
-
         hd.m_titleSection = m_engine.encodeName(title);
 
-        if( m_titleSectionCounter.containsKey( hd.m_titleSection ) )
-        {
-            Integer count = m_titleSectionCounter.get( hd.m_titleSection );
-            count = count + 1;
+        if( m_titleSectionCounter.containsKey( hd.m_titleSection ) ) {
+            final Integer count = m_titleSectionCounter.get( hd.m_titleSection ) + 1;
             m_titleSectionCounter.put( hd.m_titleSection, count );
             hd.m_titleSection += "-" + count;
-        }
-        else
-        {
+        } else {
             m_titleSectionCounter.put( hd.m_titleSection, 1 );
         }
 
-        hd.m_titleAnchor = "section-"+m_engine.encodeName(baseName)+
-                           "-"+hd.m_titleSection;
+        hd.m_titleAnchor = "section-" + m_engine.encodeName( baseName ) + "-" + hd.m_titleSection;
         hd.m_titleAnchor = hd.m_titleAnchor.replace( '%', '_' );
         hd.m_titleAnchor = hd.m_titleAnchor.replace( '/', '_' );
 
@@ -863,20 +845,15 @@ public class JSPWikiMarkupParser extends MarkupParser {
 
     private String makeSectionTitle( String title ) {
         title = title.trim();
-        final String outTitle;
-
         try {
             final JSPWikiMarkupParser dtr = getCleanTranslator();
             dtr.setInputReader( new StringReader( title ) );
 
-            final CleanTextRenderer ctt = new CleanTextRenderer( m_context, dtr.parse() );
-            outTitle = ctt.getString();
+            return XmlUtil.extractTextFromDocument( dtr.parse() );
         } catch( final IOException e ) {
             log.fatal("CleanTranslator not working", e );
             throw new InternalWikiException( "CleanTranslator not working as expected, when cleaning title"+ e.getMessage() , e );
         }
-
-        return outTitle;
     }
 
     /**
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/render/CleanTextRenderer.java b/jspwiki-main/src/main/java/org/apache/wiki/render/CleanTextRenderer.java
index 602f6ba..dec05ec 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/render/CleanTextRenderer.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/render/CleanTextRenderer.java
@@ -18,27 +18,18 @@
  */
 package org.apache.wiki.render;
 
-import org.apache.log4j.Logger;
 import org.apache.wiki.WikiContext;
 import org.apache.wiki.parser.WikiDocument;
-import org.jdom2.Text;
-import org.jdom2.xpath.XPathFactory;
-
-import java.io.IOException;
-import java.util.List;
+import org.apache.wiki.util.XmlUtil;
 
 
 /**
- *  A simple renderer that just renders all the text() nodes from the DOM tree.
- *  This is very useful for cleaning away all of the XHTML.
+ *  A simple renderer that just renders all the text() nodes from the DOM tree. This is very useful for cleaning away all of the XHTML.
  *
  *  @since  2.4
  */
 public class CleanTextRenderer extends WikiRenderer {
 
-    private static final String ALL_TEXT_NODES = "//text()";
-    private static final Logger log = Logger.getLogger( CleanTextRenderer.class );
-
     /**
      *  Create a renderer.
      *
@@ -52,21 +43,8 @@ public class CleanTextRenderer extends WikiRenderer {
     /**
      *  {@inheritDoc}
      */
-    public String getString() throws IOException {
-    	final StringBuilder sb = new StringBuilder();
-        try {
-            final List< ? > nodes = XPathFactory.instance().compile( ALL_TEXT_NODES ).evaluate( m_document.getDocument() );
-            for( final Object el : nodes ) {
-                if( el instanceof Text ) {
-                    sb.append( ( ( Text )el ).getValue() );
-                }
-            }
-        } catch( final IllegalStateException e ) {
-            log.error("Could not parse XPATH expression");
-            throw new IOException( e.getMessage(), e );
-        }
-
-        return sb.toString();
+    public String getString() {
+    	return m_document != null ? XmlUtil.extractTextFromDocument( m_document.getDocument() ) : "";
     }
 
 }
diff --git a/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java b/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
index 2412b2c..1d0ef08 100644
--- a/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
+++ b/jspwiki-util/src/main/java/org/apache/wiki/util/XmlUtil.java
@@ -24,6 +24,7 @@ import org.apache.log4j.Logger;
 import org.jdom2.Document;
 import org.jdom2.Element;
 import org.jdom2.JDOMException;
+import org.jdom2.Text;
 import org.jdom2.filter.Filters;
 import org.jdom2.input.SAXBuilder;
 import org.jdom2.xpath.XPathExpression;
@@ -49,7 +50,8 @@ import java.util.Set;
  */
 public final class XmlUtil  {
 
-	private static final Logger log = Logger.getLogger( XmlUtil.class );
+	private static final String ALL_TEXT_NODES = "//text()";
+	private static final Logger LOG = Logger.getLogger( XmlUtil.class );
 	private XmlUtil() {}
 	
 	/**
@@ -69,7 +71,7 @@ public final class XmlUtil  {
 				final Enumeration< URL > resources = XmlUtil.class.getClassLoader().getResources( xml );
 				while( resources.hasMoreElements() ) {
 					final URL resource = resources.nextElement();
-	                log.debug( "reading " + resource.toString() );
+					LOG.debug( "reading " + resource.toString() );
 					final Document doc = builder.build( resource );
 					final XPathFactory xpfac = XPathFactory.instance();
 					final XPathExpression<Element> xp = xpfac.compile( requestedNodes, Filters.element() );
@@ -77,9 +79,9 @@ public final class XmlUtil  {
 	            }
 				return new ArrayList<>( readed );
 			} catch( final IOException ioe ) {
-				log.error( "Couldn't load all " + xml + " resources", ioe );
+				LOG.error( "Couldn't load all " + xml + " resources", ioe );
 			} catch( final JDOMException jdome ) {
-				log.error( "error parsing " + xml + " resources", jdome );
+				LOG.error( "error parsing " + xml + " resources", jdome );
 			}
 		}
 		return Collections.emptyList();
@@ -102,12 +104,33 @@ public final class XmlUtil  {
 				final XPathExpression< Element > xp = xpfac.compile( requestedNodes,Filters.element() );
 				return xp.evaluate( doc );
 			} catch( final IOException ioe ) {
-				log.error( "Couldn't load all " + xmlStream + " resources", ioe );
+				LOG.error( "Couldn't load all " + xmlStream + " resources", ioe );
 			} catch( final JDOMException jdome ) {
-				log.error( "error parsing " + xmlStream + " resources", jdome );
+				LOG.error( "error parsing " + xmlStream + " resources", jdome );
 			}
 		}		
 		return Collections.emptyList();
 	}
 
+	/**
+	 * Renders all the text() nodes from the DOM tree. This is very useful for cleaning away all of the XHTML.
+	 *
+	 * @param doc Dom tree
+	 * @return String containing only the text from the provided Dom tree.
+	 */
+	public static String extractTextFromDocument( final Document doc ) {
+		if( doc == null ) {
+			return "";
+		}
+		final StringBuilder sb = new StringBuilder();
+		final List< ? > nodes = XPathFactory.instance().compile( ALL_TEXT_NODES ).evaluate( doc );
+		for( final Object el : nodes ) {
+			if( el instanceof Text ) {
+				sb.append( ( ( Text )el ).getValue() );
+			}
+		}
+
+		return sb.toString();
+	}
+
 }
\ No newline at end of file
diff --git a/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java b/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
index cefc0e9..68aa485 100644
--- a/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
+++ b/jspwiki-util/src/test/java/org/apache/wiki/util/XmlUtilTest.java
@@ -18,7 +18,9 @@
  */
 package org.apache.wiki.util;
 
+import org.jdom2.Document;
 import org.jdom2.Element;
+import org.jdom2.input.SAXBuilder;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
@@ -80,4 +82,19 @@ public class XmlUtilTest {
         }
     }
 
+    @Test
+    public void testExtractTestFrom() throws Exception {
+        Assertions.assertEquals( "", XmlUtil.extractTextFromDocument( null ) );
+        final SAXBuilder builder = new SAXBuilder();
+        try( final InputStream is = new FileInputStream( new File ("./src/test/resources/ini/classmappings.xml" ) ) ) {
+            final Document doc = builder.build( is );
+            final String text = XmlUtil.extractTextFromDocument( doc );
+            Assertions.assertEquals( "\n" +
+                                     "  \n" +
+                                     "    java.util.List\n" +
+                                     "    java.util.ArrayList\n" +
+                                     "  \n", text );
+        }
+    }
+
 }


[jspwiki] 17/26: code cleanup

Posted by ju...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

juanpablo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 0f6c61ac03913c588d7659bf016f967372e3fbb0
Author: juanpablo <ju...@apache.org>
AuthorDate: Wed Jan 15 00:11:08 2020 +0100

    code cleanup
---
 .../main/java/org/apache/wiki/parser/MarkupParser.java    | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
index 96a0b56..f2c6dab 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/parser/MarkupParser.java
@@ -35,7 +35,6 @@ import java.io.Reader;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Iterator;
 import java.util.List;
 
 /**
@@ -67,7 +66,7 @@ public abstract class MarkupParser
     protected List< Pattern > m_inlineImagePatterns = null;
     protected LinkParsingOperations m_linkParsingOperations;
 
-    private static Logger log = Logger.getLogger( MarkupParser.class );
+    private static final Logger log = Logger.getLogger( MarkupParser.class );
 
     /** If set to "true", allows using raw HTML within Wiki text.  Be warned,
         this is a VERY dangerous option to set - never turn this on in a publicly
@@ -290,12 +289,10 @@ public abstract class MarkupParser
             //
             //  Make them into Regexp Patterns.  Unknown patterns are ignored.
             //
-            for( Iterator< String > i = ptrns.iterator(); i.hasNext(); ) {
-            	String pattern = i.next();
+            for( final String pattern : ptrns ) {
                 try {
-                    compiledpatterns.add( compiler.compile( pattern,
-                                                            GlobCompiler.DEFAULT_MASK | GlobCompiler.READ_ONLY_MASK ) );
-                } catch( MalformedPatternException e ) {
+                    compiledpatterns.add( compiler.compile( pattern, GlobCompiler.DEFAULT_MASK | GlobCompiler.READ_ONLY_MASK ) );
+                } catch( final MalformedPatternException e ) {
                     log.error( "Malformed pattern [" + pattern + "] in properties: ", e );
                 }
             }
@@ -474,9 +471,9 @@ public abstract class MarkupParser
      *  @return A cleaned link.
      *  @since 2.6
      */
-    public static String wikifyLink(String link)
+    public static String wikifyLink( final String link )
     {
-        return MarkupParser.cleanLink(link, MarkupParser.LEGACY_CHARS_ALLOWED);
+        return MarkupParser.cleanLink(link, LEGACY_CHARS_ALLOWED);
     }
 
 }