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 2018/11/05 21:35:36 UTC

[jspwiki] branch master updated (dfb8b45 -> 0abc7d0)

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 dfb8b45  2.11.0-M1-git-07
     new f01e854  more use of generics
     new 2b4d583  more use of generics
     new 789cef2  log exception
     new efd6512  no need of catching UnsupportedEncodingException
     new 7e7b0c0  simplify WikiContexthasAdminPermissions()
     new da34fc4  avoid UnsupportedEncodingException and small refactor to be able to use try-with-resources
     new db3f7f1  avoid concurrency issue by building a new Set, remove close it's called implicitly
     new 728fba0  avoid catching UnsupportedEncodingException
     new c22f374  avoid catching UnsupportedEncodingException
     new 045ee2a  breaking change: both urlDecode methods don't throw UnsupportedOperationException anymore
     new 92e6e5e  remove compilation warnings
     new 187d379  breaking: verifySaltedPassword doesn't throw UnsupportedEncodingException anymore
     new f7a5971  remove some warnings
     new d75b50b  * (breaking) ClassUtil#getMappedObject methods now throw ReflectiveOperationException, IllegalArgumentException instead of WikiException * getMappedClass method now throws ClassNotFoundException instead of WikiException
     new 5e8f280  further refactors on ClassUtil
     new 69c64db  use java 8 class instead of commons-codec one
     new bf9e8b7  add @Overrides
     new ebbbeca  fix typo and use constants instead of Strings
     new 9dfbe70  try to load as many externals third-party jars as possible instead of trying all-or-nothing approach of loading them
     new 83b9c10  remove last warning from util package
     new 0abc7d0  2.11.0-M1-git-08

The 21 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                                          |  25 ++-
 .../java/org/apache/wiki/ReferenceManager.java     | 212 +++++++++------------
 .../src/main/java/org/apache/wiki/Release.java     |   2 +-
 .../src/main/java/org/apache/wiki/WikiContext.java |  39 ++--
 .../src/main/java/org/apache/wiki/WikiEngine.java  |  96 ++++------
 .../java/org/apache/wiki/auth/UserManager.java     |   7 +-
 .../wiki/auth/user/AbstractUserDatabase.java       |  17 +-
 .../apache/wiki/plugin/DefaultPluginManager.java   |  17 +-
 .../wiki/providers/AbstractFileProvider.java       |  27 +--
 .../wiki/providers/CachingAttachmentProvider.java  |  51 +++--
 .../org/apache/wiki/render/RenderingManager.java   |   6 +-
 .../org/apache/wiki/tags/IfNoSearchResultsTag.java |  16 +-
 .../java/org/apache/wiki/tags/IteratorTag.java     |  16 +-
 .../apache/wiki/tags/SearchResultIteratorTag.java  |   8 +-
 .../org/apache/wiki/tags/SearchResultsSizeTag.java |  10 +-
 .../org/apache/wiki/tags/SearchResultsTag.java     |  22 +--
 .../java/org/apache/wiki/ui/TemplateManager.java   |  17 +-
 .../main/java/org/apache/wiki/util/ClassUtil.java  | 197 +++++++------------
 .../org/apache/wiki/util/CommentedProperties.java  |   9 +-
 .../main/java/org/apache/wiki/util/CryptoUtil.java |  32 +---
 .../main/java/org/apache/wiki/util/FormUtil.java   |  19 +-
 .../main/java/org/apache/wiki/util/TextUtil.java   |  62 ++----
 .../java/org/apache/wiki/xmlrpc/RPCHandler.java    |  16 +-
 .../java/org/apache/wiki/util/CryptoUtilTest.java  |   8 +-
 24 files changed, 378 insertions(+), 553 deletions(-)


[jspwiki] 14/21: * (breaking) ClassUtil#getMappedObject methods now throw ReflectiveOperationException, IllegalArgumentException instead of WikiException * getMappedClass method now throws ClassNotFoundException instead of WikiException

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 d75b50b4246fbff0b31301d0230835883964b4a0
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 21:51:08 2018 +0100

    * (breaking) ClassUtil#getMappedObject methods now throw ReflectiveOperationException, IllegalArgumentException instead of WikiException
    * getMappedClass method now throws ClassNotFoundException instead of WikiException
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  |  20 ++--
 .../org/apache/wiki/render/RenderingManager.java   |   4 +-
 .../main/java/org/apache/wiki/util/ClassUtil.java  | 126 ++++++++-------------
 3 files changed, 60 insertions(+), 90 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 3ac5559..d0aa34d 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -727,6 +727,10 @@ public class WikiEngine
         {
             log.fatal("PageProvider is unable to list pages: ", e);
         }
+        catch( ReflectiveOperationException | IllegalArgumentException e ) 
+        {
+            throw new WikiException( "Could not instantiate ReferenceManager: " + e.getMessage(), e );
+        }
     }
 
     /**
@@ -837,6 +841,7 @@ public class WikiEngine
      *
      *  @since 2.0.3
      */
+    @Deprecated
     public String getEditURL( String pageName )
     {
         return m_urlConstructor.makeURL( WikiContext.EDIT, pageName, false, null );
@@ -853,6 +858,7 @@ public class WikiEngine
      *  @deprecated
      *  @return An URI.
      */
+    @Deprecated
     public String getAttachmentURL( String attName )
     {
         return m_urlConstructor.makeURL( WikiContext.ATTACH, attName, false, null );
@@ -920,6 +926,7 @@ public class WikiEngine
      *              the near future.
      */
 
+    @Deprecated
     public String safeGetParameter( ServletRequest request, String name )
     {
         try
@@ -1010,7 +1017,7 @@ public class WikiEngine
      */
     public Collection< String > getAllInterWikiLinks()
     {
-    	ArrayList< String > list = new ArrayList< String >();
+        ArrayList< String > list = new ArrayList< >();
 
         for( Enumeration< ? > i = m_properties.propertyNames(); i.hasMoreElements(); )
         {
@@ -1033,7 +1040,7 @@ public class WikiEngine
     public Collection< String > getAllInlinedImagePatterns()
     {
         Properties props    = getWikiProperties();
-        ArrayList<String>  ptrnlist = new ArrayList<String>();
+        ArrayList<String>  ptrnlist = new ArrayList<>();
 
         for( Enumeration< ? > e = props.propertyNames(); e.hasMoreElements(); )
         {
@@ -2320,15 +2327,14 @@ public class WikiEngine
         {
             try
             {
-                String s = m_properties.getProperty( PROP_ACL_MANAGER_IMPL,
-                                                     DefaultAclManager.class.getName() );
+                String s = m_properties.getProperty( PROP_ACL_MANAGER_IMPL, DefaultAclManager.class.getName() );
                 m_aclManager = (AclManager)ClassUtil.getMappedObject(s); // TODO: I am not sure whether this is the right call
                 m_aclManager.initialize( this, m_properties );
             }
-            catch ( WikiException we )
+            catch ( ReflectiveOperationException | IllegalArgumentException e )
             {
-                log.fatal( "unable to instantiate class for AclManager: " + we.getMessage() );
-                throw new InternalWikiException("Cannot instantiate AclManager, please check logs.", we);
+                log.fatal( "unable to instantiate class for AclManager: " + e.getMessage() );
+                throw new InternalWikiException( "Cannot instantiate AclManager, please check logs.", e );
             }
         }
         return m_aclManager;
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 6af59f1..ef55fa3 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
@@ -180,8 +180,8 @@ public class RenderingManager implements WikiEventListener, InternalModule
     public MarkupParser getParser( WikiContext context, String pagedata ) {
     	try {
 			return ( MarkupParser )ClassUtil.getMappedObject( m_markupParserClass, context, new StringReader( pagedata ) );
-		} catch( WikiException e ) {
-			log.error( "unable to get an instance of " + m_markupParserClass + " (" + e.getMessage() + "), returning default markup parser." );
+		} catch( 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 ) );
 		}
     }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
index c957766..58a628a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
@@ -21,7 +21,6 @@ package org.apache.wiki.util;
 import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
 import java.net.JarURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
@@ -57,7 +56,7 @@ public final class ClassUtil {
      */
     public  static final String MAPPINGS = "ini/classmappings.xml";
     
-    private static Map<String, String> c_classMappings = new Hashtable<String, String>();
+    private static Map<String, String> c_classMappings = new Hashtable<>();
 
     private static boolean classLoaderSetup = false;
     private static ClassLoader loader = null;
@@ -67,7 +66,7 @@ public final class ClassUtil {
      *  Initialize the class mappings document.
      */
     static {
-    	List< Element > nodes = XmlUtil.parse( MAPPINGS, "/classmappings/mapping" );
+        List< Element > nodes = XmlUtil.parse( MAPPINGS, "/classmappings/mapping" );
 
         if( nodes.size() > 0 ) {
             for( Iterator< Element > i = nodes.iterator(); i.hasNext(); ) {
@@ -183,7 +182,7 @@ public final class ClassUtil {
      */
     public static List< String > classpathEntriesUnder( final String rootPackage ) 
     {
-        List< String > results = new ArrayList< String >();
+        List< String > results = new ArrayList< >();
         Enumeration< URL > en = null;
         if( StringUtils.isNotEmpty( rootPackage ) ) {
             try
@@ -301,11 +300,12 @@ public final class ClassUtil {
      *  
      *  @param requestedClass The name of the class you wish to instantiate.
      *  @return An instantiated Object.
-     *  @throws WikiException If the class cannot be found or instantiated.
+     *  @throws IllegalArgumentException If the class cannot be found or instantiated. 
+     *  @throws ReflectiveOperationException If the class cannot be found or instantiated.
      *  @since 2.5.40
      */
     public static Object getMappedObject( String requestedClass )
-        throws WikiException
+        throws ReflectiveOperationException, IllegalArgumentException
     {
         Object[] initargs = {};
         return getMappedObject(requestedClass, initargs );
@@ -327,73 +327,46 @@ public final class ClassUtil {
      *  @param requestedClass The name of the class you wish to instantiate.
      *  @param initargs The parameters to be passed to the constructor. May be <code>null</code>.
      *  @return An instantiated Object.
-     *  @throws WikiException If the class cannot be found or instantiated.  The error is logged.
+     *  @throws IllegalArgumentException If the class cannot be found or instantiated. 
+     *  @throws ReflectiveOperationException If the class cannot be found or instantiated.
      *  @since 2.5.40
      */
     public static Object getMappedObject( String requestedClass, Object... initargs )
-        throws WikiException
+        throws ReflectiveOperationException, IllegalArgumentException
     {
-        try
+        Class<?> cl = getMappedClass( requestedClass );
+        Constructor<?>[] ctors = cl.getConstructors();
+        
+        //
+        //  Try to find the proper constructor by comparing the
+        //  initargs array classes and the constructor types.
+        //
+        for( int c = 0; c < ctors.length; c++ )
         {
-            Class<?> cl = getMappedClass( requestedClass );
-         
-            Constructor<?>[] ctors = cl.getConstructors();
+            Class<?>[] params = ctors[c].getParameterTypes();
             
-            //
-            //  Try to find the proper constructor by comparing the
-            //  initargs array classes and the constructor types.
-            //
-            for( int c = 0; c < ctors.length; c++ )
+            if( params.length == initargs.length )
             {
-                Class<?>[] params = ctors[c].getParameterTypes();
-                
-                if( params.length == initargs.length )
+                for( int arg = 0; arg < initargs.length; arg++ )
                 {
-                    for( int arg = 0; arg < initargs.length; arg++ )
+                    if( params[arg].isAssignableFrom(initargs[arg].getClass()))
                     {
-                        if( params[arg].isAssignableFrom(initargs[arg].getClass()))
-                        {
-                            //
-                            //  Ha, found it!  Instantiating and returning...
-                            //
-                            return ctors[c].newInstance(initargs);
-                        }
+                        //
+                        //  Ha, found it!  Instantiating and returning...
+                        //
+                        return ctors[c].newInstance(initargs);
                     }
                 }
             }
-            
-            //
-            //  No arguments, so we can just call a default constructor and
-            //  ignore the arguments.
-            //
-            Object o = cl.newInstance();
-            
-            return o;
-        }
-        catch( InstantiationException e )
-        {
-            log.info( "Cannot instantiate requested class "+requestedClass, e );
-            
-            throw new WikiException("Failed to instantiate class "+requestedClass, e );
-        }
-        catch (IllegalAccessException e)
-        {
-            log.info( "Cannot access requested class "+requestedClass, e );
-            
-            throw new WikiException("Failed to instantiate class "+requestedClass, e );
-        }
-        catch (IllegalArgumentException e)
-        {
-            log.info( "Illegal arguments when constructing new object", e );
-            
-            throw new WikiException("Failed to instantiate class "+requestedClass, e );
-        }
-        catch (InvocationTargetException e)
-        {
-            log.info( "You tried to instantiate an abstract class "+requestedClass, e );
-            
-            throw new WikiException("Failed to instantiate class "+requestedClass, e );
         }
+        
+        //
+        //  No arguments, so we can just call a default constructor and
+        //  ignore the arguments.
+        //
+        Object o = cl.newInstance();
+        
+        return o;
     }
 
     /**
@@ -405,7 +378,7 @@ public final class ClassUtil {
      *  @throws WikiException
      */
     private static Class< ? > getMappedClass( String requestedClass )
-        throws WikiException
+        throws ClassNotFoundException
     {
         String mappedClass = c_classMappings.get( requestedClass );
         
@@ -414,18 +387,9 @@ public final class ClassUtil {
             mappedClass = requestedClass;
         }
         
-        try
-        {
-            Class< ? > cl = Class.forName(mappedClass);
-            
-            return cl;
-        }
-        catch (ClassNotFoundException e)
-        {
-            log.info( "Cannot find requested class", e );
-            
-            throw new WikiException("Failed to instantiate class "+requestedClass, e );
-        }
+        Class< ? > cl = Class.forName(mappedClass);
+        
+        return cl;
     }
     
     /**
@@ -436,14 +400,14 @@ public final class ClassUtil {
      * @return {@code true} if {@code srcClassName} is a subclass of {@code parentClassname}, {@code false} otherwise.
      */
     public static boolean assignable( String srcClassName, String parentClassName ) {
-    	try {
-			Class< ? > src = Class.forName( srcClassName );
-			Class< ? > parent = Class.forName( parentClassName );
-			return parent.isAssignableFrom( src );
-		} catch( Exception e ) {
-			log.error( e.getMessage(), e );
-		}
-    	return false;
+        try {
+            Class< ? > src = Class.forName( srcClassName );
+            Class< ? > parent = Class.forName( parentClassName );
+            return parent.isAssignableFrom( src );
+        } catch( Exception e ) {
+            log.error( e.getMessage(), e );
+        }
+        return false;
     }
     
 }


[jspwiki] 07/21: avoid concurrency issue by building a new Set, remove close it's called implicitly

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 db3f7f158d47aace27eae819a027a705c483988f
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:30:04 2018 +0100

    avoid concurrency issue by building a new Set, remove close it's called implicitly
---
 .../java/org/apache/wiki/ReferenceManager.java     | 24 ++++++----------------
 1 file changed, 6 insertions(+), 18 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java b/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
index eebfa08..097335b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
@@ -482,10 +482,8 @@ public class ReferenceManager
             //
             f = new File( f, hashName );
             
-            try( ObjectOutputStream out =  new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(f)) ) )
-            {
-                // FIXME: There is a concurrency issue here...
-                Set< Map.Entry < String, Object > > entries = p.getAttributes().entrySet();
+            try( ObjectOutputStream out =  new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream( f ) ) ) ) {
+                Set< Map.Entry < String, Object > > entries = new HashSet<>( p.getAttributes().entrySet() ); // new Set to avoid concurrency issue
 
                 if( entries.size() == 0 ) 
                 {
@@ -502,29 +500,19 @@ public class ReferenceManager
                 out.writeUTF( p.getName() );
                 out.writeLong( entries.size() );
 
-                for( Iterator< Map.Entry < String, Object > > i = entries.iterator(); i.hasNext(); )
-                {
+                for( Iterator< Map.Entry < String, Object > > i = entries.iterator(); i.hasNext(); ) {
                     Map.Entry< String, Object > e = i.next();
 
-                    if( e.getValue() instanceof Serializable )
-                    {
+                    if( e.getValue() instanceof Serializable ) {
                         out.writeUTF( e.getKey() );
                         out.writeObject( e.getValue() );
                     }
                 }
 
-                out.close();
-
-            }
-            catch( IOException e )
-            {
+            } catch( IOException e ) {
                 log.error( "Unable to serialize!", e );
-
-            }
-            finally
-            {
+            } finally {
                 sw.stop();
-
                 log.debug("serialization for "+p.getName()+" done - took "+sw);
             }
         }


[jspwiki] 04/21: no need of catching UnsupportedEncodingException

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 efd65125b91d19004baba78079ee81eb0f1405e5
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Nov 3 17:05:53 2018 +0100

    no need of catching UnsupportedEncodingException
---
 .../org/apache/wiki/auth/user/AbstractUserDatabase.java | 17 ++---------------
 1 file changed, 2 insertions(+), 15 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/user/AbstractUserDatabase.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/user/AbstractUserDatabase.java
index fbdf620..596eac5 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/auth/user/AbstractUserDatabase.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/user/AbstractUserDatabase.java
@@ -18,7 +18,6 @@
  */
 package org.apache.wiki.auth.user;
 
-import java.io.UnsupportedEncodingException;
 import java.nio.charset.StandardCharsets;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
@@ -260,10 +259,6 @@ public abstract class AbstractUserDatabase implements UserDatabase
         {
             log.error( "Unsupported algorithm: " + e.getMessage() );
         }
-        catch( UnsupportedEncodingException e )
-        {
-            log.fatal( "You do not have UTF-8!?!" );
-        }
         catch( WikiSecurityException e )
         {
             log.error( "Could not upgrade SHA password to SSHA because profile could not be saved. Reason: " + e.getMessage(), e );
@@ -312,17 +307,13 @@ public abstract class AbstractUserDatabase implements UserDatabase
         String hash = null;
         try
         {
-            hash = CryptoUtil.getSaltedPassword( text.getBytes("UTF-8") );
+            hash = CryptoUtil.getSaltedPassword( text.getBytes(StandardCharsets.UTF_8) );
         }
         catch( NoSuchAlgorithmException e )
         {
             log.error( "Error creating salted SHA password hash:" + e.getMessage() );
             hash = text;
         }
-        catch( UnsupportedEncodingException e )
-        {
-            log.fatal("You do not have UTF-8!?!");
-        }
         return hash;
     }
 
@@ -339,7 +330,7 @@ public abstract class AbstractUserDatabase implements UserDatabase
         try
         {
             MessageDigest md = MessageDigest.getInstance( "SHA" );
-            md.update( text.getBytes("UTF-8") );
+            md.update( text.getBytes(StandardCharsets.UTF_8) );
             byte[] digestedBytes = md.digest();
             hash = ByteUtils.bytes2hex( digestedBytes );
         }
@@ -348,10 +339,6 @@ public abstract class AbstractUserDatabase implements UserDatabase
             log.error( "Error creating SHA password hash:" + e.getMessage() );
             hash = text;
         }
-        catch (UnsupportedEncodingException e)
-        {
-            log.fatal("UTF-8 not supported!?!");
-        }
         return hash;
     }
 


[jspwiki] 03/21: log exception

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 789cef21571256af96cdcb9889e6b8006d08e93e
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Nov 3 17:04:58 2018 +0100

    log exception
---
 jspwiki-main/src/main/java/org/apache/wiki/auth/UserManager.java | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/UserManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/UserManager.java
index 6f503d5..6ea4de3 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/auth/UserManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/UserManager.java
@@ -155,8 +155,7 @@ public class UserManager {
 
         try
         {
-            dbClassName = TextUtil.getRequiredProperty( m_engine.getWikiProperties(),
-                                                          PROP_DATABASE );
+            dbClassName = TextUtil.getRequiredProperty( m_engine.getWikiProperties(), PROP_DATABASE );
 
             log.info("Attempting to load user database class "+dbClassName);
             final Class<?> dbClass = ClassUtil.findClass( USERDATABASE_PACKAGE, dbClassName );
@@ -166,7 +165,7 @@ public class UserManager {
         }
         catch( final NoRequiredPropertyException e )
         {
-            log.error( "You have not set the '"+PROP_DATABASE+"'. You need to do this if you want to enable user management by JSPWiki." );
+            log.error( "You have not set the '"+PROP_DATABASE+"'. You need to do this if you want to enable user management by JSPWiki.", e );
         }
         catch( final ClassNotFoundException e )
         {
@@ -182,7 +181,7 @@ public class UserManager {
         }
         catch( final WikiSecurityException e )
         {
-            log.error( "Exception initializing user database: " + e.getMessage() );
+            log.error( "Exception initializing user database: " + e.getMessage(), e );
         }
         finally
         {


[jspwiki] 12/21: breaking: verifySaltedPassword doesn't throw UnsupportedEncodingException anymore

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 187d3797aaaf2f928f28ecef518f8e6748e13a0b
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:41:55 2018 +0100

    breaking: verifySaltedPassword doesn't throw UnsupportedEncodingException anymore
---
 .../main/java/org/apache/wiki/util/CryptoUtil.java | 26 +++++-----------------
 1 file changed, 6 insertions(+), 20 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
index bc66c75..e386099 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
@@ -18,15 +18,14 @@
  */
 package org.apache.wiki.util;
 
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
 import java.util.Arrays;
+import java.util.Base64;
 import java.util.Random;
 
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
 
 /**
  * Hashes and verifies salted SHA-1 passwords, which are compliant with RFC
@@ -34,8 +33,6 @@ import org.apache.log4j.Logger;
  */
 public final class CryptoUtil
 {
-    private static final Logger log = Logger.getLogger( CryptoUtil.class );
-
     private static final String SSHA = "{SSHA}";
 
     private static final Random RANDOM = new SecureRandom();
@@ -183,18 +180,9 @@ public final class CryptoUtil
         {
             all[hash.length + i] = salt[i];
         }
-        byte[] base64 = Base64.encodeBase64( all );
+        byte[] base64 = Base64.getEncoder().encode( all );
         
-        String saltedString = null;
-        try
-        {
-            saltedString = SSHA + new String( base64, "UTF8" );
-        }
-        catch( UnsupportedEncodingException e )
-        {
-            log.fatal( "You do not have UTF-8!?!" );
-        }
-        return saltedString;
+        return SSHA + new String( base64, StandardCharsets.UTF_8 );
     }
 
     /**
@@ -204,17 +192,15 @@ public final class CryptoUtil
      *  @param entry The password entry, typically starting with {SSHA}.
      *  @return True, if the password matches.
      *  @throws NoSuchAlgorithmException If there is no SHA available.
-     *  @throws UnsupportedEncodingException If no UTF-8 encoding is available 
      */
-    public static boolean verifySaltedPassword( byte[] password, String entry ) 
-        throws NoSuchAlgorithmException, UnsupportedEncodingException
+    public static boolean verifySaltedPassword( byte[] password, String entry ) throws NoSuchAlgorithmException
     {
         // First, extract everything after {SSHA} and decode from Base64
         if( !entry.startsWith( SSHA ) )
         {
             throw new IllegalArgumentException( "Hash not prefixed by {SSHA}; is it really a salted hash?" );
         }
-        byte[] challenge = Base64.decodeBase64( entry.substring( 6 ).getBytes("UTF-8") );
+        byte[] challenge = Base64.getDecoder().decode( entry.substring( 6 ).getBytes( StandardCharsets.UTF_8 ) );
 
         // Extract the password hash and salt
         byte[] passwordHash = extractPasswordHash( challenge );


[jspwiki] 09/21: avoid catching UnsupportedEncodingException

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 c22f374e0233a858f6315109bf48bb3d0a439af1
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:32:39 2018 +0100

    avoid catching UnsupportedEncodingException
---
 .../src/main/java/org/apache/wiki/xmlrpc/RPCHandler.java | 16 ++--------------
 1 file changed, 2 insertions(+), 14 deletions(-)

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 82fc4d3..215f2a3 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
@@ -19,6 +19,7 @@
 package org.apache.wiki.xmlrpc;
 
 import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
 import java.util.Calendar;
 import java.util.Collection;
 import java.util.Date;
@@ -78,20 +79,7 @@ public class RPCHandler
      */
     private byte[] toRPCBase64( String src )
     {
-        try
-        {
-            return src.getBytes("UTF-8");
-        }
-        catch( UnsupportedEncodingException e )
-        {
-            //
-            //  You shouldn't be running JSPWiki on a platform that does not
-            //  use UTF-8.  We revert to platform default, so that the other
-            //  end might have a chance of getting something.
-            //
-            log.fatal("Platform does not support UTF-8, reverting to platform default");
-            return src.getBytes();
-        }
+        return src.getBytes( StandardCharsets.UTF_8 );
     }
 
     public String getApplicationName()


[jspwiki] 11/21: remove compilation warnings

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 92e6e5e02f2bf7cfbaf7785af4428714ab7c1c5e
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:40:36 2018 +0100

    remove compilation warnings
---
 .../src/main/java/org/apache/wiki/util/FormUtil.java  | 19 +++++++++----------
 1 file changed, 9 insertions(+), 10 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/FormUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/FormUtil.java
index 72f6d1a..2fb23b3 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/FormUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/FormUtil.java
@@ -53,15 +53,15 @@ public final class FormUtil
      * @param key the key to look up
      * @return the List of keys
      */
-    public static List getValues( Map params, String key )
+    public static List< ? > getValues( Map< ? , ? > params, String key )
     {
         if( params == null || key == null )
-            return new ArrayList(0);
+            return new ArrayList<>(0);
 
         Object entry = params.get( key );
         if( entry != null )
         {
-            ArrayList<Object> rval = new ArrayList<Object>(1);
+            ArrayList<Object> rval = new ArrayList<>(1);
             rval.add( entry );
             return rval;
         }
@@ -88,9 +88,9 @@ public final class FormUtil
      * @return ArrayList, containing the values corresponding to the
      *          keyPrefix, in order.
      */
-    public static List getNumberedValues( Map params, String keyPrefix )
+    public static List< ? > getNumberedValues( Map< ?, ? > params, String keyPrefix )
     {
-        ArrayList<Object> rval = new ArrayList<Object>();
+        ArrayList<Object> rval = new ArrayList<>();
         if( params == null || 
             params.size() == 0 || 
             keyPrefix == null || 
@@ -137,17 +137,16 @@ public final class FormUtil
      * @param filterPrefix the prefix
      * @return the Map containing parsed key/value pairs
      */
-    public static Map< String, String > requestToMap( HttpServletRequest req, 
-                                                      String filterPrefix )
+    public static Map< String, String > requestToMap( HttpServletRequest req, String filterPrefix )
     {
-        HashMap<String,String> params = new HashMap<String,String>();
+        HashMap<String,String> params = new HashMap<>();
         
         if( filterPrefix == null ) filterPrefix = "";
         
-        Enumeration en = req.getParameterNames();
+        Enumeration< String > en = req.getParameterNames();
         while( en.hasMoreElements() )
         {
-            String param = (String)en.nextElement();
+            String param = en.nextElement();
             
             if( param.startsWith( filterPrefix ) )
             {


[jspwiki] 05/21: simplify WikiContexthasAdminPermissions()

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 7e7b0c0f75af938f5879b3b0d6c3c7d7c119127a
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:24:55 2018 +0100

    simplify WikiContexthasAdminPermissions()
---
 .../src/main/java/org/apache/wiki/WikiContext.java | 39 ++++++++++++----------
 1 file changed, 21 insertions(+), 18 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 455f70e..621f8cd 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
@@ -74,7 +74,7 @@ public class WikiContext
     private    WikiEngine m_engine;
     private    String     m_template = "default";
 
-    private    HashMap<String,Object> m_variableMap = new HashMap<String,Object>();
+    private    HashMap<String,Object> m_variableMap = new HashMap<>();
 
     /**
      *  Stores the HttpServletRequest.  May be null, if the request did not
@@ -274,7 +274,8 @@ public class WikiContext
      * {@inheritDoc}
      * @see org.apache.wiki.ui.Command#getContentTemplate()
      */
-    public String getContentTemplate()
+    @Override
+	public String getContentTemplate()
     {
         return m_command.getContentTemplate();
     }
@@ -283,7 +284,8 @@ public class WikiContext
      * {@inheritDoc}
      * @see org.apache.wiki.ui.Command#getJSP()
      */
-    public String getJSP()
+    @Override
+	public String getJSP()
     {
         return m_command.getContentTemplate();
     }
@@ -404,7 +406,8 @@ public class WikiContext
      *  Returns the request context.
      *  @return The name of the request context (e.g. VIEW).
      */
-    public String getRequestContext()
+    @Override
+	public String getRequestContext()
     {
         return m_command.getRequestContext();
     }
@@ -424,7 +427,8 @@ public class WikiContext
      * {@inheritDoc}
      * @see org.apache.wiki.ui.Command#getTarget()
      */
-    public Object getTarget()
+    @Override
+	public Object getTarget()
     {
         return m_command.getTarget();
     }
@@ -433,7 +437,8 @@ public class WikiContext
      * {@inheritDoc}
      * @see org.apache.wiki.ui.Command#getURLPattern()
      */
-    public String getURLPattern()
+    @Override
+	public String getURLPattern()
     {
         return m_command.getURLPattern();
     }
@@ -542,7 +547,8 @@ public class WikiContext
      * @see org.apache.wiki.ui.PageCommand#getName()
      * @see org.apache.wiki.ui.GroupCommand#getName()
      */
-    public String getName()
+    @Override
+	public String getName()
     {
         if ( m_command instanceof PageCommand )
         {
@@ -644,7 +650,8 @@ public class WikiContext
      *  @since 2.1.37.
      *  @return A shallow clone of the WikiContext
      */
-    public Object clone()
+    @Override
+	public Object clone()
     {
         try
         {
@@ -742,7 +749,8 @@ public class WikiContext
      * @return the permission
      * @since 2.4
      */
-    public Permission requiredPermission()
+    @Override
+	public Permission requiredPermission()
     {
         // This is a filthy rotten hack -- absolutely putrid
         if ( WikiCommand.INSTALL.equals( m_command ) )
@@ -779,7 +787,8 @@ public class WikiContext
      *
      * {@inheritDoc}
      */
-    public Command targetedCommand( Object target )
+    @Override
+	public Command targetedCommand( Object target )
     {
         if ( m_command.getTarget() == null )
         {
@@ -795,14 +804,8 @@ public class WikiContext
      *  @since 2.4.46
      *  @return true, if the user has all permissions.
      */
-    public boolean hasAdminPermissions()
-    {
-        boolean admin = false;
-
-        admin = m_engine.getAuthorizationManager().checkPermission( getWikiSession(),
-                                                                    new AllPermission(m_engine.getApplicationName()) );
-
-        return admin;
+    public boolean hasAdminPermissions() {
+        return m_engine.getAuthorizationManager().checkPermission( getWikiSession(), new AllPermission(m_engine.getApplicationName()) );
     }
 
     /**


[jspwiki] 13/21: remove some warnings

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 f7a5971bb25aef5af0b1aa1003c1fa60d1e357e7
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:48:58 2018 +0100

    remove some warnings
---
 .../wiki/providers/CachingAttachmentProvider.java  | 51 +++++++++++++++-------
 1 file changed, 35 insertions(+), 16 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/providers/CachingAttachmentProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/providers/CachingAttachmentProvider.java
index 12e0ac7..a50a498 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/providers/CachingAttachmentProvider.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/providers/CachingAttachmentProvider.java
@@ -20,14 +20,17 @@ package org.apache.wiki.providers;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.util.*;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
 
 import org.apache.log4j.Logger;
-import org.apache.wiki.*;
+import org.apache.wiki.WikiEngine;
+import org.apache.wiki.WikiPage;
+import org.apache.wiki.WikiProvider;
 import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
 import org.apache.wiki.api.exceptions.ProviderException;
 import org.apache.wiki.attachment.Attachment;
@@ -36,6 +39,10 @@ import org.apache.wiki.search.QueryItem;
 import org.apache.wiki.util.ClassUtil;
 import org.apache.wiki.util.TextUtil;
 
+import net.sf.ehcache.Cache;
+import net.sf.ehcache.CacheManager;
+import net.sf.ehcache.Element;
+
 /**
  *  Provides a caching attachment provider.  This class rests on top of a
  *  real provider class and provides a cache to speed things up.  Only the
@@ -88,6 +95,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public void initialize( WikiEngine engine, Properties properties )
         throws NoRequiredPropertyException,
                IOException
@@ -147,6 +155,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public void putAttachmentData( Attachment att, InputStream data )
         throws ProviderException, IOException {
         m_provider.putAttachmentData( att, data );
@@ -159,6 +168,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public InputStream getAttachmentData( Attachment att )
         throws ProviderException, IOException {
         return m_provider.getAttachmentData( att );
@@ -167,13 +177,14 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public List< Attachment > listAttachments(WikiPage page) throws ProviderException {
         log.debug("Listing attachments for " + page);
-        List<Attachment> c = null;
         Element element = m_cache.get(page.getName());
 
         if (element != null) {
-            c = (List<Attachment>) element.getObjectValue();
+            @SuppressWarnings("unchecked") 
+            List< Attachment > c = ( List< Attachment > )element.getObjectValue();
             log.debug("LIST from cache, " + page.getName() + ", size=" + c.size());
             return cloneCollection(c);
         }
@@ -195,6 +206,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public Collection findAttachments( QueryItem[] query )
     {
         return m_provider.findAttachments( query );
@@ -203,8 +215,9 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public List listAllChanged(Date timestamp) throws ProviderException {
-        List all = null;
+        List< Attachment > all = null;
         //
         // we do a one-time build up of the cache, after this the cache is updated for every attachment add/delete
         if (m_gotall == false) {
@@ -213,20 +226,20 @@ public class CachingAttachmentProvider
             // Put all pages in the cache :
 
             synchronized (this) {
-                for (Iterator i = all.iterator(); i.hasNext(); ) {
-                    Attachment att = (Attachment) i.next();
+                for (Iterator< Attachment > i = all.iterator(); i.hasNext(); ) {
+                    Attachment att = i.next();
                     m_attCache.put(new Element(att.getName(), att));
                 }
                 m_gotall = true;
             }
         } else {
             List<String> keys = m_attCache.getKeysWithExpiryCheck();
-            all = new ArrayList();
+            all = new ArrayList<>();
             for (String key : keys) {
                 Element element = m_attCache.get(key);
-                Object cachedAttachment = element.getObjectValue();
+                Attachment cachedAttachment = ( Attachment )element.getObjectValue();
                 if (cachedAttachment != null) {
-                    all.add((Attachment) cachedAttachment);
+                    all.add(cachedAttachment);
                 }
             }
         }
@@ -241,7 +254,7 @@ public class CachingAttachmentProvider
      *  @return null, if no such attachment was in this collection.
      */
     private Attachment findAttachmentFromCollection( Collection< Attachment > c, String name ) {
-        for( Attachment att : new ArrayList< Attachment >( c ) ) {
+        for( Attachment att : new ArrayList< >( c ) ) {
             if( name.equals( att.getFileName() ) ) {
                 return att;
             }
@@ -266,6 +279,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public Attachment getAttachmentInfo(WikiPage page, String name, int version) throws ProviderException {
         if (log.isDebugEnabled()) {
             log.debug("Getting attachments for " + page + ", name=" + name + ", version=" + version);
@@ -298,6 +312,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public List getVersionHistory( Attachment att )
     {
         return m_provider.getVersionHistory( att );
@@ -306,6 +321,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public void deleteVersion( Attachment att ) throws ProviderException
     {
         // This isn't strictly speaking correct, but it does not really matter
@@ -316,6 +332,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public void deleteAttachment( Attachment att ) throws ProviderException
     {
         m_cache.remove(att.getParentName());
@@ -329,6 +346,7 @@ public class CachingAttachmentProvider
      *
      * @return A plain string with all the above mentioned values.
      */
+    @Override
     public synchronized String getProviderInfo()
     {
         return "Real provider: "+m_provider.getClass().getName()+
@@ -349,6 +367,7 @@ public class CachingAttachmentProvider
     /**
      * {@inheritDoc}
      */
+    @Override
     public void moveAttachmentsForPage( String oldParent, String newParent ) throws ProviderException
     {
         m_provider.moveAttachmentsForPage(oldParent, newParent);
@@ -362,7 +381,7 @@ public class CachingAttachmentProvider
         String checkName = oldParent + "/";
 
         @SuppressWarnings("unchecked")
-		List< String > names = m_cache.getKeysWithExpiryCheck();
+        List< String > names = m_cache.getKeysWithExpiryCheck();
         for( String name : names )
         {
             if( name.startsWith( checkName ) )


[jspwiki] 21/21: 2.11.0-M1-git-08

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 0abc7d0a3196706df03aeac0348b0d1c7ca220f8
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 22:35:00 2018 +0100

    2.11.0-M1-git-08
---
 ChangeLog                                          | 25 ++++++++++++++++++----
 .../src/main/java/org/apache/wiki/Release.java     |  2 +-
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 64a6663..1aac5be 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,10 +1,27 @@
+2018-11-05  Juan Pablo Santos (juanpablo AT apache DOT org)
+
+       * 2.11.0-M1-git-08: try to load as many external third-party plugin jars as possible, instead  
+	     of all-or-nothing
+
+	   * small backwards-incompatible changes: 
+	     - CryptoUtil#verifySaltedPassword doesn't throw UnsupportedEncodingException anymore
+	     - TextUtil#urlDecode methods don't throw UnsupportedOperationException anymore
+         - ClassUtil#getMappedObject methods now throw ReflectiveOperationException, IllegalArgumentException 
+		   instead of WikiException
+         - ClassUtil#getMappedClass method now throws ClassNotFoundException instead of WikiException
+
+	   * fix possible concurrency issue at ReferenceManager#serializeAttrsToDisk
+
+	   * remove commons-codec usage from source (it's carried onto the war as a transitive 
+	     dependency though), plus several other small refactors
+
 2018-11-02  Juan Pablo Santos (juanpablo AT apache DOT org)
 
        * 2.11.0-M1-git-07: removed a bunch of warnings throughout the code
-	   
-	   * added a Jenkinsfile
-	   
-	   * small backwards-incompatible change: WikiEngine#getRecentChanges() now returns a Set instead of a Collection
+
+       * added a Jenkinsfile
+
+       * small backwards-incompatible change: WikiEngine#getRecentChanges() now returns a Set instead of a Collection
 
 2018-10-30  Juan Pablo Santos (juanpablo AT apache DOT org)
 
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 c2bf99e..996bc46 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/Release.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/Release.java
@@ -72,7 +72,7 @@ public final class Release {
      *  <p>
      *  If the build identifier is empty, it is not added.
      */
-    public static final String     BUILD         = "7";
+    public static final String     BUILD         = "8";
 
     /**
      *  This is the generic version string you should use when printing out the version.  It is of


[jspwiki] 10/21: breaking change: both urlDecode methods don't throw UnsupportedOperationException anymore

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 045ee2afacc47dbe2e915867d1e03986c7083f21
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:39:24 2018 +0100

    breaking change: both urlDecode methods don't throw UnsupportedOperationException anymore
---
 .../main/java/org/apache/wiki/util/TextUtil.java   | 62 ++++++----------------
 1 file changed, 15 insertions(+), 47 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/TextUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/TextUtil.java
index 31eda8a..90508c9 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/TextUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/TextUtil.java
@@ -20,7 +20,8 @@ package org.apache.wiki.util;
 
 import java.io.File;
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.security.SecureRandom;
 import java.util.Properties;
 import java.util.Random;
@@ -97,11 +98,9 @@ public final class TextUtil {
      *  @param encoding The encoding in which the string should be interpreted
      *  @return A decoded String
      *
-     *  @throws UnsupportedEncodingException If the encoding is unknown.
      *  @throws IllegalArgumentException If the byte array is not a valid string.
      */
-    protected static String urlDecode( byte[] bytes, String encoding )
-              throws UnsupportedEncodingException, IllegalArgumentException {
+    protected static String urlDecode( byte[] bytes, String encoding ) throws  IllegalArgumentException {
         if( bytes == null ) {
             return null;
         }
@@ -130,15 +129,7 @@ public final class TextUtil {
             throw new IllegalArgumentException( "Malformed UTF-8 string?" );
         }
 
-        String processedPageName = null ;
-
-        try {
-            processedPageName = new String(decodeBytes, 0, decodedByteCount, encoding) ;
-        } catch( UnsupportedEncodingException e ) {
-            throw new UnsupportedEncodingException( "UTF-8 encoding not supported on this platform" );
-        }
-
-        return processedPageName;
+        return new String(decodeBytes, 0, decodedByteCount, Charset.forName( encoding ) );
     }
 
     /**
@@ -153,14 +144,8 @@ public final class TextUtil {
             return "";
         }
 
-        byte[] rs;
-
-        try {
-            rs = text.getBytes( "UTF-8" );
-            return urlEncode( rs );
-        } catch( UnsupportedEncodingException uee ) {
-            throw new UnsupportedOperationException( "UTF-8 not supported!?!", uee );
-        }
+        byte[] rs = text.getBytes( StandardCharsets.UTF_8 );
+        return urlEncode( rs );
     }
 
     /**
@@ -170,17 +155,11 @@ public final class TextUtil {
      *  @return A plain, normal string.
      */
     public static String urlDecodeUTF8( String utf8 ) {
-        String rs = null;
-
-        if( utf8 == null ) return null;
-
-        try {
-            rs = urlDecode( utf8.getBytes( "ISO-8859-1" ), "UTF-8" );
-        } catch( UnsupportedEncodingException uee ) {
-            throw new UnsupportedOperationException( "UTF-8 or ISO-8859-1 not supported!?!", uee );
+        if( utf8 == null ) {
+            return null;
         }
 
-        return rs;
+        return urlDecode( utf8.getBytes( StandardCharsets.ISO_8859_1 ), StandardCharsets.UTF_8.toString() );
     }
 
     /**
@@ -195,15 +174,11 @@ public final class TextUtil {
     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.
-        if( "UTF-8".equals( encoding ) ) {
-            return TextUtil.urlEncodeUTF8( data );
+        if( StandardCharsets.UTF_8.toString().equals( encoding ) ) {
+            return urlEncodeUTF8( data );
         }
 
-        try {
-            return TextUtil.urlEncode( data.getBytes( encoding ) );
-        } catch( UnsupportedEncodingException uee ) {
-            throw new UnsupportedOperationException( "Could not encode String into" + encoding, uee );
-        }
+        return urlEncode( data.getBytes( Charset.forName( encoding ) ) );
     }
 
     /**
@@ -214,23 +189,16 @@ public final class TextUtil {
      * @param data The URL-encoded string to decode
      * @param encoding The encoding to use
      * @return A decoded string.
-     * @throws UnsupportedEncodingException If the encoding is unknown
      * @throws IllegalArgumentException If the data cannot be decoded.
      */
-    public static String urlDecode( String data, String encoding )
-        throws UnsupportedEncodingException, IllegalArgumentException {
+    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.
         if( "UTF-8".equals( encoding ) ) {
-            return TextUtil.urlDecodeUTF8( data );
-        }
-
-        try {
-            return TextUtil.urlDecode( data.getBytes(encoding), encoding );
-        } catch( UnsupportedEncodingException uee ) {
-            throw new UnsupportedOperationException("Could not decode String into" + encoding, uee );
+            return urlDecodeUTF8( data );
         }
 
+        return urlDecode( data.getBytes( Charset.forName( encoding ) ), encoding );
     }
 
     /**


[jspwiki] 08/21: avoid catching UnsupportedEncodingException

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 728fba0d0a2f96744e495621c86d470f5ab141e6
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:31:49 2018 +0100

    avoid catching UnsupportedEncodingException
---
 .../wiki/providers/AbstractFileProvider.java       | 27 ++++++++--------------
 1 file changed, 9 insertions(+), 18 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/providers/AbstractFileProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/providers/AbstractFileProvider.java
index f7eec73..002c59a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/providers/AbstractFileProvider.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/providers/AbstractFileProvider.java
@@ -27,7 +27,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Date;
@@ -102,7 +102,7 @@ public abstract class AbstractFileProvider
     /**
      *  Name of the property that defines where page directories are.
      */
-    public static final String      PROP_PAGEDIR = "jspwiki.fileSystemProvider.pageDir";
+    public static final String PROP_PAGEDIR = "jspwiki.fileSystemProvider.pageDir";
 
     /**
      *  All files should have this extension to be recognized as JSPWiki files.
@@ -112,7 +112,7 @@ public abstract class AbstractFileProvider
     public static final String FILE_EXT = ".txt";
 
     /** The default encoding. */
-    public static final String DEFAULT_ENCODING = "ISO-8859-1";
+    public static final String DEFAULT_ENCODING = StandardCharsets.ISO_8859_1.toString();
 
     private boolean m_windowsHackNeeded = false;
 
@@ -121,9 +121,7 @@ public abstract class AbstractFileProvider
      *  @throws FileNotFoundException If the specified page directory does not exist.
      *  @throws IOException In case the specified page directory is a file, not a directory.
      */
-    public void initialize( WikiEngine engine, Properties properties )
-        throws NoRequiredPropertyException,
-               IOException, FileNotFoundException
+    public void initialize( WikiEngine engine, Properties properties ) throws NoRequiredPropertyException, IOException, FileNotFoundException
     {
         log.debug("Initing FileSystemProvider");
         m_pageDirectory = TextUtil.getCanonicalFilePathProperty(properties, PROP_PAGEDIR,
@@ -230,19 +228,12 @@ public abstract class AbstractFileProvider
     protected String unmangleName( String filename )
     {
         // The exception should never happen.
-        try
+        if( m_windowsHackNeeded && filename.startsWith( "$$$") && filename.length() > 3 )
         {
-            if( m_windowsHackNeeded && filename.startsWith( "$$$") && filename.length() > 3 )
-            {
-                filename = filename.substring(3);
-            }
-
-            return TextUtil.urlDecode( filename, m_encoding );
-        }
-        catch( UnsupportedEncodingException e )
-        {
-            throw new InternalWikiException("Faulty encoding; should never happen", e);
+            filename = filename.substring(3);
         }
+
+        return TextUtil.urlDecode( filename, m_encoding );
     }
 
     /**
@@ -364,7 +355,7 @@ public abstract class AbstractFileProvider
     {
         log.debug("Getting all pages...");
 
-        ArrayList<WikiPage> set = new ArrayList<WikiPage>();
+        ArrayList<WikiPage> set = new ArrayList<>();
 
         File wikipagedir = new File( m_pageDirectory );
 


[jspwiki] 17/21: add @Overrides

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 bf9e8b7b27c8e44103bef910acb058cf266a73e6
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 21:14:35 2018 +0100

    add @Overrides
---
 .../org/apache/wiki/plugin/DefaultPluginManager.java    | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
index 831324f..cd7e8d1 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/DefaultPluginManager.java
@@ -167,9 +167,9 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
 
     private static final String DEFAULT_FORMS_PACKAGE = "org.apache.wiki.forms";
 
-    private ArrayList<String> m_searchPath = new ArrayList<String>();
+    private ArrayList<String> m_searchPath = new ArrayList<>();
 
-    private ArrayList<String> m_externalJars = new ArrayList<String>();
+    private ArrayList<String> m_externalJars = new ArrayList<>();
 
     private Pattern m_pluginPattern;
 
@@ -178,7 +178,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
     /**
      *  Keeps a list of all known plugin classes.
      */
-    private Map<String, WikiPluginInfo> m_pluginClassMap = new HashMap<String, WikiPluginInfo>();
+    private Map<String, WikiPluginInfo> m_pluginClassMap = new HashMap<>();
 
     /**
      *  Create a new PluginManager.
@@ -230,6 +230,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
     /**
      * {@inheritDoc}
      */
+    @Override
     public void enablePlugins( boolean enabled ) {
         m_pluginsEnabled = enabled;
     }
@@ -237,6 +238,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
     /**
      * {@inheritDoc}
      */
+    @Override
     public boolean pluginsEnabled() {
         return m_pluginsEnabled;
     }
@@ -244,6 +246,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
     /**
      * {@inheritDoc}
      */
+    @Override
     public Pattern getPluginPattern() {
 		return m_pluginPattern;
 	}
@@ -251,6 +254,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getPluginSearchPath() {
     	return TextUtil.getStringProperty( m_engine.getWikiProperties(), PROP_SEARCHPATH, null );
     }
@@ -314,6 +318,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
      *
      *  @since 2.0
      */
+    @Override
     public String execute( WikiContext context, String classname, Map< String, String > params ) throws PluginException {
         if( !m_pluginsEnabled ) {
             return "";
@@ -377,8 +382,9 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
      *
      * @throws IOException If the parsing fails.
      */
+    @Override
     public Map< String, String > parseArgs( String argstring ) throws IOException {
-        Map< String, String > arglist = new HashMap< String, String >();
+        Map< String, String > arglist = new HashMap< >();
 
         //
         //  Protection against funny users.
@@ -483,6 +489,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
      *
      *  @throws PluginException From the plugin itself, it propagates, waah!
      */
+    @Override
     public String execute( WikiContext context, String commandline ) throws PluginException {
         if( !m_pluginsEnabled ) {
             return "";
@@ -775,6 +782,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
          *
          *  @return Something human-readable
          */
+        @Override
         public String toString() {
             return "Plugin :[name=" + m_name + "][className=" + m_className + "]";
         }
@@ -804,6 +812,7 @@ public class DefaultPluginManager extends ModuleManager implements PluginManager
      * @return a {@link WikiPlugin}.
      * @throws PluginException if there is a problem building the {@link WikiPlugin}.
      */
+    @Override
     public WikiPlugin newWikiPlugin( String pluginName, ResourceBundle rb ) throws PluginException {
         WikiPlugin plugin = null;
         WikiPluginInfo pluginInfo = m_pluginClassMap.get( pluginName );


[jspwiki] 02/21: more use of generics

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 2b4d58346e18d6f1665700577813e9910d448b3d
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Nov 3 17:03:31 2018 +0100

    more use of generics
---
 .../main/java/org/apache/wiki/ui/TemplateManager.java   | 17 +++++------------
 1 file changed, 5 insertions(+), 12 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java
index 96dce0e..64ddc86 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java
@@ -477,7 +477,7 @@ public class TemplateManager extends ModuleManager {
      * @return map of TimeFormats
      * @since 2.7.x
      */
-    public Map listTimeFormats(PageContext pageContext)
+    public Map< String, String > listTimeFormats(PageContext pageContext)
     {
         WikiContext context = WikiContext.findContext( pageContext );
         Properties props = m_engine.getWikiProperties();
@@ -485,7 +485,7 @@ public class TemplateManager extends ModuleManager {
         LinkedHashMap<String,String> resultMap = new LinkedHashMap<>();
 
         /* filter timeformat properties */
-        for (Enumeration e = props.propertyNames(); e.hasMoreElements();)
+        for (Enumeration< ? > e = props.propertyNames(); e.hasMoreElements();)
         {
             String name = (String) e.nextElement();
 
@@ -496,21 +496,14 @@ public class TemplateManager extends ModuleManager {
         }
 
         /* fetch actual formats */
-        if (tfArr.size() == 0) /*
-                                 * no props found - make sure some default
-                                 * formats are avail
-                                 */
-        {
+        if (tfArr.size() == 0)  {/* no props found - make sure some default formats are avail */
             tfArr.add("dd-MMM-yy");
             tfArr.add("d-MMM-yyyy");
             tfArr.add("EEE, dd-MMM-yyyy, zzzz");
-        }
-        else
-        {
+        } else {
             Collections.sort(tfArr);
 
-            for (int i = 0; i < tfArr.size(); i++)
-            {
+            for (int i = 0; i < tfArr.size(); i++) {
                 tfArr.set(i, props.getProperty(tfArr.get(i)));
             }
         }


[jspwiki] 16/21: use java 8 class instead of commons-codec one

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 69c64db72782c1a4258dda979dd53cca21ba0be3
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 21:14:04 2018 +0100

    use java 8 class instead of commons-codec one
---
 .../src/test/java/org/apache/wiki/util/CryptoUtilTest.java        | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/jspwiki-main/src/test/java/org/apache/wiki/util/CryptoUtilTest.java b/jspwiki-main/src/test/java/org/apache/wiki/util/CryptoUtilTest.java
index 20d351e..7bd2a53 100644
--- a/jspwiki-main/src/test/java/org/apache/wiki/util/CryptoUtilTest.java
+++ b/jspwiki-main/src/test/java/org/apache/wiki/util/CryptoUtilTest.java
@@ -21,8 +21,8 @@ package org.apache.wiki.util;
 import java.io.ByteArrayOutputStream;
 import java.io.OutputStream;
 import java.io.PrintStream;
+import java.util.Base64;
 
-import org.apache.commons.codec.binary.Base64;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
@@ -105,13 +105,13 @@ public class CryptoUtilTest
     {
         byte[] digest;
 
-        digest = Base64.decodeBase64( "yfT8SRT/WoOuNuA6KbJeF10OznZmb28=".getBytes() );
+        digest = Base64.getDecoder().decode( "yfT8SRT/WoOuNuA6KbJeF10OznZmb28=".getBytes() );
         Assertions.assertEquals( "foo", new String( CryptoUtil.extractSalt( digest ) ) );
 
-        digest = Base64.decodeBase64( "tAVisOOQGAeVyP8UMFQY9qi83lxsb09e".getBytes() );
+        digest = Base64.getDecoder().decode( "tAVisOOQGAeVyP8UMFQY9qi83lxsb09e".getBytes() );
         Assertions.assertEquals( "loO^", new String( CryptoUtil.extractSalt( digest ) ) );
 
-        digest = Base64.decodeBase64( "BZaDYvB8czmNW3MjR2j7/mklODV0ZXN0eQ==".getBytes() );
+        digest = Base64.getDecoder().decode( "BZaDYvB8czmNW3MjR2j7/mklODV0ZXN0eQ==".getBytes() );
         Assertions.assertEquals( "testy", new String( CryptoUtil.extractSalt( digest ) ) );
     }
 


[jspwiki] 20/21: remove last warning from util package

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 83b9c109b66b5cee1e47c0ab7cc75824b12af5ce
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 21:22:29 2018 +0100

    remove last warning from util package
---
 .../src/main/java/org/apache/wiki/util/CommentedProperties.java  | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/CommentedProperties.java b/jspwiki-main/src/main/java/org/apache/wiki/util/CommentedProperties.java
index d23a7e7..d262142 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/CommentedProperties.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/CommentedProperties.java
@@ -78,6 +78,7 @@ public class CommentedProperties extends Properties
      *  @param in The reader to read properties from
      *  @throws IOException in case something goes wrong.
      */
+    @Override
     public synchronized void load( Reader in ) throws IOException
     {
         m_propertyString = FileUtil.readContents( in );
@@ -122,14 +123,14 @@ public class CommentedProperties extends Properties
     /**
      * {@inheritDoc}
      */
-    @SuppressWarnings("unchecked")
     @Override
-    public synchronized void putAll( Map arg0 )
+    public synchronized void putAll( Map< ? , ? > arg0 )
     {
         // Shove all of the entries into the property string
-        for( Iterator< Entry< ?, ? > > it = arg0.entrySet().iterator(); it.hasNext(); )
+        for( Iterator< ? > it = arg0.entrySet().iterator(); it.hasNext(); )
         {
-            Entry< ?, ? > entry = it.next();
+            @SuppressWarnings("unchecked") 
+            Entry< Object, Object > entry = ( Entry< Object, Object > )it.next();
             writeProperty( entry.getKey(), entry.getValue() );
         }
 


[jspwiki] 15/21: further refactors on ClassUtil

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 5e8f280423dfe97b7e480d1f87018b4336057216
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 00:25:37 2018 +0100

    further refactors on ClassUtil
    
    * use ConcurrentHashMap to store c_classmappings, instead of a Hashtable
    * use try with resources in jarEntriesUnder
    * getMappedObject methods perform the cast to the wanted type allowing to remove the cast everywhere else in the code. Propagate this change.
---
 .../src/main/java/org/apache/wiki/WikiEngine.java  | 76 ++++++++--------------
 .../org/apache/wiki/render/RenderingManager.java   |  2 +-
 .../main/java/org/apache/wiki/util/ClassUtil.java  | 60 +++++------------
 3 files changed, 46 insertions(+), 92 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 d0aa34d..888da22 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java
@@ -23,6 +23,7 @@ import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.security.Principal;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -494,16 +495,14 @@ public class WikiEngine
         //
         //  Create and find the default working directory.
         //
-        m_workDir        = TextUtil.getStringProperty( props, PROP_WORKDIR, null );
+        m_workDir = TextUtil.getStringProperty( props, PROP_WORKDIR, null );
 
-        if( m_workDir == null )
-        {
+        if( m_workDir == null ) {
             m_workDir = System.getProperty("java.io.tmpdir", ".");
             m_workDir += File.separator+Release.APPNAME+"-"+m_appid;
         }
 
-        try
-        {
+        try {
             File f = new File( m_workDir );
             f.mkdirs();
 
@@ -514,25 +513,16 @@ public class WikiEngine
             if( !f.canRead() ) throw new WikiException("No permission to read work directory: "+m_workDir);
             if( !f.canWrite() ) throw new WikiException("No permission to write to work directory: "+m_workDir);
             if( !f.isDirectory() ) throw new WikiException("jspwiki.workDir does not point to a directory: "+m_workDir);
-        }
-        catch( SecurityException e )
-        {
+        } catch( SecurityException e ) {
             log.fatal( "Unable to find or create the working directory: "+m_workDir, e );
             throw new IllegalArgumentException( "Unable to find or create the working dir: " + m_workDir, e );
         }
 
         log.info("JSPWiki working directory is '"+m_workDir+"'");
 
-        m_saveUserInfo   = TextUtil.getBooleanProperty( props,
-                                                        PROP_STOREUSERNAME,
-                                                        m_saveUserInfo );
-
-        m_useUTF8        = "UTF-8".equals( TextUtil.getStringProperty( props, PROP_ENCODING, "ISO-8859-1" ) );
-
-        m_beautifyTitle  = TextUtil.getBooleanProperty( props,
-                                                        PROP_BEAUTIFYTITLE,
-                                                        m_beautifyTitle );
-
+        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" );
         m_frontPage      = TextUtil.getStringProperty( props, PROP_FRONTPAGE,   "Main" );
 
@@ -550,26 +540,22 @@ public class WikiEngine
         try
         {
             Class< ? > urlclass = ClassUtil.findClass( "org.apache.wiki.url",
-                    TextUtil.getStringProperty( props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor" ) );
+                                                       TextUtil.getStringProperty( props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor" ) );
             m_urlConstructor = (URLConstructor) urlclass.newInstance();
             m_urlConstructor.initialize( this, props );
 
-            m_pageManager       = (PageManager)ClassUtil.getMappedObject(PageManager.class.getName(), this, props );
-            m_pluginManager     = (PluginManager)ClassUtil.getMappedObject(PluginManager.class.getName(), this, props );
-            m_differenceManager = (DifferenceManager)ClassUtil.getMappedObject(DifferenceManager.class.getName(), this, props );
-            m_attachmentManager = (AttachmentManager)ClassUtil.getMappedObject(AttachmentManager.class.getName(), this, props );
-            m_variableManager   = (VariableManager)ClassUtil.getMappedObject(VariableManager.class.getName(), props );
-            // m_filterManager     = (FilterManager)ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
-            m_renderingManager  = (RenderingManager) ClassUtil.getMappedObject(RenderingManager.class.getName());
-
-            m_searchManager     = (SearchManager)ClassUtil.getMappedObject(SearchManager.class.getName(), this, props );
-
-            m_authenticationManager = (AuthenticationManager) ClassUtil.getMappedObject(AuthenticationManager.class.getName());
-            m_authorizationManager  = (AuthorizationManager) ClassUtil.getMappedObject( AuthorizationManager.class.getName());
-            m_userManager           = (UserManager) ClassUtil.getMappedObject(UserManager.class.getName());
-            m_groupManager          = (GroupManager) ClassUtil.getMappedObject(GroupManager.class.getName());
-
-            m_editorManager     = (EditorManager)ClassUtil.getMappedObject(EditorManager.class.getName(), this );
+            m_pageManager           = ClassUtil.getMappedObject( PageManager.class.getName(), this, props );
+            m_pluginManager         = ClassUtil.getMappedObject( PluginManager.class.getName(), this, props );
+            m_differenceManager     = ClassUtil.getMappedObject( DifferenceManager.class.getName(), this, props );
+            m_attachmentManager     = ClassUtil.getMappedObject( AttachmentManager.class.getName(), this, props );
+            m_variableManager       = ClassUtil.getMappedObject( VariableManager.class.getName(), props );
+            m_renderingManager      = ClassUtil.getMappedObject( RenderingManager.class.getName() );
+            m_searchManager         = ClassUtil.getMappedObject( SearchManager.class.getName(), this, props );
+            m_authenticationManager = ClassUtil.getMappedObject( AuthenticationManager.class.getName() );
+            m_authorizationManager  = ClassUtil.getMappedObject( AuthorizationManager.class.getName() );
+            m_userManager           = ClassUtil.getMappedObject( UserManager.class.getName() );
+            m_groupManager          = ClassUtil.getMappedObject( GroupManager.class.getName() );
+            m_editorManager         = ClassUtil.getMappedObject( EditorManager.class.getName(), this );
             m_editorManager.initialize( props );
 
             m_progressManager   = new ProgressManager();
@@ -583,27 +569,21 @@ public class WikiEngine
             m_aclManager = getAclManager();
 
             // Start the Workflow manager
-            m_workflowMgr = (WorkflowManager)ClassUtil.getMappedObject(WorkflowManager.class.getName());
+            m_workflowMgr = ClassUtil.getMappedObject(WorkflowManager.class.getName());
             m_workflowMgr.initialize(this, props);
 
-            m_internationalizationManager = (InternationalizationManager)
-                ClassUtil.getMappedObject(InternationalizationManager.class.getName(),this);
-
-            m_templateManager   = (TemplateManager)
-                ClassUtil.getMappedObject(TemplateManager.class.getName(), this, props );
+            m_internationalizationManager = ClassUtil.getMappedObject(InternationalizationManager.class.getName(),this);
+            m_templateManager = ClassUtil.getMappedObject(TemplateManager.class.getName(), this, props );
 
             // Since we want to use a page filters initilize() method
             // as a engine startup listener where we can initialize global event listeners,
             // it must be called lastly, so that all object references in the engine
             // are availabe to the initialize() method
-            m_filterManager     = (FilterManager)
-                ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
+            m_filterManager = ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
 
-            m_adminBeanManager = (AdminBeanManager)
-                ClassUtil.getMappedObject(AdminBeanManager.class.getName(),this);
+            m_adminBeanManager = ClassUtil.getMappedObject(AdminBeanManager.class.getName(),this);
 
             // RenderingManager depends on FilterManager events.
-
             m_renderingManager.initialize( this, props );
 
             //
@@ -718,7 +698,7 @@ public class WikiEngine
             // Build a new manager with default key lists.
             if( m_referenceManager == null )
             {
-                m_referenceManager = (ReferenceManager) ClassUtil.getMappedObject(ReferenceManager.class.getName(), this );
+                m_referenceManager = ClassUtil.getMappedObject(ReferenceManager.class.getName(), this );
                 m_referenceManager.initialize( pages );
             }
 
@@ -2328,7 +2308,7 @@ public class WikiEngine
             try
             {
                 String s = m_properties.getProperty( PROP_ACL_MANAGER_IMPL, DefaultAclManager.class.getName() );
-                m_aclManager = (AclManager)ClassUtil.getMappedObject(s); // TODO: I am not sure whether this is the right call
+                m_aclManager = ClassUtil.getMappedObject(s); // TODO: I am not sure whether this is the right call
                 m_aclManager.initialize( this, m_properties );
             }
             catch ( ReflectiveOperationException | IllegalArgumentException e )
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 ef55fa3..862d629 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
@@ -179,7 +179,7 @@ public class RenderingManager implements WikiEventListener, InternalModule
      */
     public MarkupParser getParser( WikiContext context, String pagedata ) {
     	try {
-			return ( MarkupParser )ClassUtil.getMappedObject( m_markupParserClass, context, new StringReader( pagedata ) );
+			return ClassUtil.getMappedObject( m_markupParserClass, context, new StringReader( pagedata ) );
 		} catch( 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 ) );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
index 58a628a..9931192 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
@@ -27,10 +27,10 @@ import java.net.URL;
 import java.net.URLClassLoader;
 import java.util.ArrayList;
 import java.util.Enumeration;
-import java.util.Hashtable;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 
@@ -38,7 +38,6 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.apache.wiki.api.engine.PluginManager;
-import org.apache.wiki.api.exceptions.WikiException;
 import org.jdom2.Element;
 
 /**
@@ -56,7 +55,7 @@ public final class ClassUtil {
      */
     public  static final String MAPPINGS = "ini/classmappings.xml";
     
-    private static Map<String, String> c_classMappings = new Hashtable<>();
+    private static Map<String, String> c_classMappings = new ConcurrentHashMap<>();
 
     private static boolean classLoaderSetup = false;
     private static ClassLoader loader = null;
@@ -251,41 +250,19 @@ public final class ClassUtil {
      * @param jurlcon given {@link JarURLConnection} to search in.
      * @param rootPackage base package.
      */
-    static void jarEntriesUnder( List< String > results, JarURLConnection jurlcon, String rootPackage )
-    {
-        JarFile jar = null;
-        try
-        {
-            jar = jurlcon.getJarFile();
+    static void jarEntriesUnder( List< String > results, JarURLConnection jurlcon, String rootPackage ) {
+        try( JarFile jar = jurlcon.getJarFile() ) {
             log.debug( "scanning [" + jar.getName() +"]" );
             Enumeration< JarEntry > entries = jar.entries();
-            while( entries.hasMoreElements() )
-            {
+            while( entries.hasMoreElements() ) {
                 JarEntry entry = entries.nextElement();
-                if( entry.getName().startsWith( rootPackage ) && !entry.isDirectory() ) 
-                {
+                if( entry.getName().startsWith( rootPackage ) && !entry.isDirectory() ) {
                     results.add( entry.getName() );
                 }
             }
-        }
-        catch( IOException ioe )
-        {
+        } catch( IOException ioe ) {
             log.error( ioe.getMessage(), ioe );
         }
-        finally 
-        {
-            if (jar != null)
-            {
-                try
-                {
-                    jar.close();
-                }
-                catch( IOException ioe )
-                {
-                    log.error( ioe.getMessage(), ioe );
-                }
-            }
-        }
     }
     
     /**
@@ -304,11 +281,12 @@ public final class ClassUtil {
      *  @throws ReflectiveOperationException If the class cannot be found or instantiated.
      *  @since 2.5.40
      */
-    public static Object getMappedObject( String requestedClass )
+    @SuppressWarnings("unchecked")
+    public static < T > T getMappedObject( String requestedClass )
         throws ReflectiveOperationException, IllegalArgumentException
     {
         Object[] initargs = {};
-        return getMappedObject(requestedClass, initargs );
+        return ( T )getMappedObject(requestedClass, initargs );
     }
 
     /**
@@ -331,7 +309,8 @@ public final class ClassUtil {
      *  @throws ReflectiveOperationException If the class cannot be found or instantiated.
      *  @since 2.5.40
      */
-    public static Object getMappedObject( String requestedClass, Object... initargs )
+    @SuppressWarnings( "unchecked" )
+    public static < T > T getMappedObject( String requestedClass, Object... initargs )
         throws ReflectiveOperationException, IllegalArgumentException
     {
         Class<?> cl = getMappedClass( requestedClass );
@@ -354,19 +333,16 @@ public final class ClassUtil {
                         //
                         //  Ha, found it!  Instantiating and returning...
                         //
-                        return ctors[c].newInstance(initargs);
+                        return ( T )ctors[c].newInstance(initargs);
                     }
                 }
             }
         }
         
         //
-        //  No arguments, so we can just call a default constructor and
-        //  ignore the arguments.
+        //  No arguments, so we can just call a default constructor and ignore the arguments.
         //
-        Object o = cl.newInstance();
-        
-        return o;
+        return ( T )cl.newInstance();
     }
 
     /**
@@ -375,11 +351,9 @@ public final class ClassUtil {
      *  
      *  @param requestedClass
      *  @return A Class object which you can then instantiate.
-     *  @throws WikiException
+     *  @throws ClassNotFoundException
      */
-    private static Class< ? > getMappedClass( String requestedClass )
-        throws ClassNotFoundException
-    {
+    private static Class< ? > getMappedClass( String requestedClass ) throws ClassNotFoundException {
         String mappedClass = c_classMappings.get( requestedClass );
         
         if( mappedClass == null )


[jspwiki] 01/21: more use of generics

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 f01e8542d8f137c671b87d5dc4e148aaff221860
Author: juanpablo <ju...@apache.org>
AuthorDate: Sat Nov 3 14:26:45 2018 +0100

    more use of generics
---
 .../org/apache/wiki/tags/IfNoSearchResultsTag.java | 16 ++++++----------
 .../java/org/apache/wiki/tags/IteratorTag.java     | 16 +++-------------
 .../apache/wiki/tags/SearchResultIteratorTag.java  |  8 +++-----
 .../org/apache/wiki/tags/SearchResultsSizeTag.java | 10 +++-------
 .../org/apache/wiki/tags/SearchResultsTag.java     | 22 ++++++++--------------
 5 files changed, 23 insertions(+), 49 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/IfNoSearchResultsTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/IfNoSearchResultsTag.java
index 37abd4f..19fae52 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/IfNoSearchResultsTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/IfNoSearchResultsTag.java
@@ -22,26 +22,22 @@ import java.io.IOException;
 import java.util.Collection;
 import javax.servlet.jsp.PageContext;
 
+
 /**
  *  If there have been no search results, then outputs the body text.
  *
  *  @since 2.0
  */
-public class IfNoSearchResultsTag
-    extends WikiTagBase
-{
+public class IfNoSearchResultsTag extends WikiTagBase {
     private static final long serialVersionUID = 0L;
     
-    public final int doWikiStartTag()
-        throws IOException
-    {
-        Collection list = (Collection)pageContext.getAttribute( "searchresults",
-                                                                PageContext.REQUEST_SCOPE );
-        if( list == null || list.size() == 0 )
-        {   
+    public final int doWikiStartTag() throws IOException {
+        Collection< ? > list = (Collection< ? >)pageContext.getAttribute( "searchresults", PageContext.REQUEST_SCOPE );
+        if( list == null || list.size() == 0 ) {
             return EVAL_BODY_INCLUDE;
         }
 
         return SKIP_BODY;
     }
+    
 }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/IteratorTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/IteratorTag.java
index 90935e1..49633f4 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/IteratorTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/IteratorTag.java
@@ -46,8 +46,8 @@ import org.apache.wiki.WikiPage;
 public abstract class IteratorTag extends BodyTagSupport implements TryCatchFinally {
 
 	private static final long serialVersionUID = 8945334759300595321L;
-	protected String      m_pageName;
-    protected Iterator    m_iterator;
+	protected String m_pageName;
+    protected Iterator< ? > m_iterator;
     protected WikiContext m_wikiContext;
 
     private static final Logger log = Logger.getLogger( IteratorTag.class );
@@ -57,7 +57,7 @@ public abstract class IteratorTag extends BodyTagSupport implements TryCatchFina
      *  
      *  @param arg A Collection which will be iterated.
      */
-    public void setList( Collection arg )
+    public void setList( Collection< ? > arg )
     {
         if( arg != null )
             m_iterator = arg.iterator();
@@ -74,16 +74,6 @@ public abstract class IteratorTag extends BodyTagSupport implements TryCatchFina
             m_iterator = Arrays.asList(arg).iterator();
         }
     }
-    
-    /**
-     *  Sets the iterator directly that is used to form the iteration.
-     */
-    /*
-    public void setList( Iterator arg )
-    {
-        m_iterator = arg;
-    }
-    */
 
     /**
      *  Clears the iterator away.  After calling this method doStartTag()
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultIteratorTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultIteratorTag.java
index cbb6b5a..0eb68eb 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultIteratorTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultIteratorTag.java
@@ -78,8 +78,7 @@ public class SearchResultIteratorTag
         //
         if( m_iterator == null )
         {
-            Collection searchresults = (Collection) pageContext.getAttribute( "searchresults",
-                                                                              PageContext.REQUEST_SCOPE );
+            Collection< ? > searchresults = (Collection< ? >)pageContext.getAttribute( "searchresults", PageContext.REQUEST_SCOPE );
             setList( searchresults );
             
             int skip = 0;
@@ -89,9 +88,8 @@ public class SearchResultIteratorTag
             while( m_iterator.hasNext() && (skip++ < m_start) ) m_iterator.next();
         }
 
-        m_count       = 0;
-        m_wikiContext = (WikiContext) pageContext.getAttribute( WikiTagBase.ATTR_CONTEXT,
-                                                                PageContext.REQUEST_SCOPE );
+        m_count = 0;
+        m_wikiContext = (WikiContext) pageContext.getAttribute( WikiTagBase.ATTR_CONTEXT, PageContext.REQUEST_SCOPE );
 
         return nextResult();
     }
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsSizeTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsSizeTag.java
index 7bf27fa..cc9741a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsSizeTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsSizeTag.java
@@ -33,13 +33,9 @@ public class SearchResultsSizeTag
 {
     private static final long serialVersionUID = 0L;
     
-    public final int doWikiStartTag()
-        throws IOException
-    {
-        Collection list = (Collection)pageContext.getAttribute( "searchresults",
-                                                                PageContext.REQUEST_SCOPE );
-        if( list != null )
-        {
+    public final int doWikiStartTag() throws IOException {
+        Collection< ? > list = ( Collection< ? > )pageContext.getAttribute( "searchresults", PageContext.REQUEST_SCOPE );
+        if( list != null ) {
             pageContext.getOut().print( list.size() );
         }
 
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsTag.java b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsTag.java
index 0bf0471..a521278 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsTag.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tags/SearchResultsTag.java
@@ -22,32 +22,25 @@ import java.io.IOException;
 import java.util.Collection;
 import javax.servlet.jsp.PageContext;
 
+
 /**
  *  Includes the body content, if there are any search results.
  *
  *  @since 2.0
  */
-public class SearchResultsTag
-    extends WikiTagBase
-{
+public class SearchResultsTag extends WikiTagBase {
     private static final long serialVersionUID = 0L;
     
-    public final int doWikiStartTag()
-        throws IOException
-    {
-        Collection list = (Collection)pageContext.getAttribute( "searchresults",
-                                                                PageContext.REQUEST_SCOPE );
+    public final int doWikiStartTag() throws IOException {
+        Collection< ? > list = ( Collection< ? > )pageContext.getAttribute( "searchresults", PageContext.REQUEST_SCOPE );
         
-        if( list != null )
-        {
+        if( list != null ) {
             return EVAL_BODY_INCLUDE;
         }
 
-        String message = (String)pageContext.getAttribute( "err",
-                                                           PageContext.REQUEST_SCOPE );
+        String message = (String)pageContext.getAttribute( "err", PageContext.REQUEST_SCOPE );
             
-        if( message != null )
-        {
+        if( message != null ) {
             pageContext.getOut().print("<div class='error'>");
             pageContext.getOut().print( message );
             pageContext.getOut().println("</div>");
@@ -55,4 +48,5 @@ public class SearchResultsTag
         
         return SKIP_BODY;
     }
+
 }


[jspwiki] 06/21: avoid UnsupportedEncodingException and small refactor to be able to use try-with-resources

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 da34fc459fe51a755f7c59dbe3873ece682317ef
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Nov 4 01:26:49 2018 +0100

    avoid UnsupportedEncodingException and small refactor to be able to use try-with-resources
---
 .../java/org/apache/wiki/ReferenceManager.java     | 216 +++++++++------------
 1 file changed, 96 insertions(+), 120 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java b/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
index f12b698..eebfa08 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ReferenceManager.java
@@ -27,7 +27,7 @@ import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
@@ -379,22 +379,16 @@ public class ReferenceManager
         }
     }
 
-    private String getHashFileName( String pageName )
-        throws NoSuchAlgorithmException
-    {
-        MessageDigest digest = MessageDigest.getInstance("MD5");
-
-        byte[] dig;
-        try
-        {
-            dig = digest.digest( pageName.getBytes("UTF-8") );
-        }
-        catch (UnsupportedEncodingException e)
-        {
-            throw new InternalWikiException("AAAAGH!  UTF-8 is gone!  My eyes!  It burns...!", e);
-        }
+    private String getHashFileName( String pageName ) {
+		try {
+			MessageDigest digest = MessageDigest.getInstance("MD5");
+			byte[] dig = digest.digest( pageName.getBytes(StandardCharsets.UTF_8) );
 
-        return TextUtil.toHexString(dig)+".cache";
+	        return TextUtil.toHexString(dig)+".cache";
+		} catch( NoSuchAlgorithmException e ) {
+			log.fatal( "What do you mean - no such algorithm?", e );
+			return null;
+		}
     }
 
     /**
@@ -405,74 +399,66 @@ public class ReferenceManager
         throws IOException,
                ClassNotFoundException
     {
-        ObjectInputStream in = null;
         long saved = 0L;
 
-        try
-        {
-            StopWatch sw = new StopWatch();
-            sw.start();
-
-            //
-            //  Find attribute cache, and check if it exists
-            //
-            File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
+        //
+        //  Find attribute cache, and check if it exists
+        //
+        String hashName = getHashFileName( p.getName() );
+        if( hashName != null ) {
+        	File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
 
-            f = new File( f, getHashFileName(p.getName()) );
+            f = new File( f, hashName );
 
             if( !f.exists() )
             {
                 return 0L;
             }
+            try( ObjectInputStream in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(f)) ))
+            {
+                StopWatch sw = new StopWatch();
+                sw.start();
 
-            log.debug("Deserializing attributes for "+p.getName());
-
-            in = new ObjectInputStream( new BufferedInputStream(new FileInputStream(f)) );
+                log.debug("Deserializing attributes for "+p.getName());
 
-            long ver     = in.readLong();
+                long ver = in.readLong();
 
-            if( ver != serialVersionUID )
-            {
-                log.debug("File format has changed; cannot deserialize.");
-                return 0L;
-            }
+                if( ver != serialVersionUID )
+                {
+                    log.debug("File format has changed; cannot deserialize.");
+                    return 0L;
+                }
 
-            saved        = in.readLong();
+                saved        = in.readLong();
 
-            String name  = in.readUTF();
+                String name  = in.readUTF();
 
-            if( !name.equals(p.getName()) )
-            {
-                log.debug("File name does not match ("+name+"), skipping...");
-                return 0L; // Not here
-            }
+                if( !name.equals(p.getName()) )
+                {
+                    log.debug("File name does not match ("+name+"), skipping...");
+                    return 0L; // Not here
+                }
 
-            long entries = in.readLong();
+                long entries = in.readLong();
 
-            for( int i = 0; i < entries; i++ )
-            {
-                String key   = in.readUTF();
-                Object value = in.readObject();
+                for( int i = 0; i < entries; i++ )
+                {
+                    String key   = in.readUTF();
+                    Object value = in.readObject();
 
-                p.setAttribute( key, value );
+                    p.setAttribute( key, value );
 
-                log.debug("   attr: "+key+"="+value);
-            }
+                    log.debug("   attr: "+key+"="+value);
+                }
 
-            in.close();
+                in.close();
 
-            sw.stop();
-            log.debug("Read serialized data for "+name+" successfully in "+sw);
-            p.setHasMetadata();
-        }
-        catch( NoSuchAlgorithmException e )
-        {
-            log.fatal("No MD5!?!");
-        }
-        finally
-        {
-            if( in != null ) in.close();
+                sw.stop();
+                log.debug("Read serialized data for "+name+" successfully in "+sw);
+                p.setHasMetadata();
+            }
         }
+        
 
         return saved;
     }
@@ -482,75 +468,67 @@ public class ReferenceManager
      */
     private synchronized void serializeAttrsToDisk( WikiPage p )
     {
-        ObjectOutputStream out = null;
         StopWatch sw = new StopWatch();
         sw.start();
 
-        try
-        {
-            File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
+        String hashName = getHashFileName( p.getName() );
+        if( hashName != null ) {
+        	File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
 
             if( !f.exists() ) f.mkdirs();
 
             //
             //  Create a digest for the name
             //
-            f = new File( f, getHashFileName(p.getName()) );
-
-            // FIXME: There is a concurrency issue here...
-            Set< Map.Entry < String, Object > > entries = p.getAttributes().entrySet();
-
-            if( entries.size() == 0 ) 
+            f = new File( f, hashName );
+            
+            try( ObjectOutputStream out =  new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(f)) ) )
             {
-                //  Nothing to serialize, therefore we will just simply remove the
-                //  serialization file so that the next time we boot, we don't
-                //  deserialize old data.
-                f.delete();
-                return;
-            }
+                // FIXME: There is a concurrency issue here...
+                Set< Map.Entry < String, Object > > entries = p.getAttributes().entrySet();
 
-            out = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
+                if( entries.size() == 0 ) 
+                {
+                    //  Nothing to serialize, therefore we will just simply remove the
+                    //  serialization file so that the next time we boot, we don't
+                    //  deserialize old data.
+                    f.delete();
+                    return;
+                }
 
-            out.writeLong( serialVersionUID );
-            out.writeLong( System.currentTimeMillis() ); // Timestamp
+                out.writeLong( serialVersionUID );
+                out.writeLong( System.currentTimeMillis() ); // Timestamp
 
-            out.writeUTF( p.getName() );
-            out.writeLong( entries.size() );
+                out.writeUTF( p.getName() );
+                out.writeLong( entries.size() );
 
-            for( Iterator< Map.Entry < String, Object > > i = entries.iterator(); i.hasNext(); )
-            {
-                Map.Entry< String, Object > e = i.next();
-
-                if( e.getValue() instanceof Serializable )
+                for( Iterator< Map.Entry < String, Object > > i = entries.iterator(); i.hasNext(); )
                 {
-                    out.writeUTF( (String)e.getKey() );
-                    out.writeObject( e.getValue() );
-                }
-            }
+                    Map.Entry< String, Object > e = i.next();
 
-            out.close();
+                    if( e.getValue() instanceof Serializable )
+                    {
+                        out.writeUTF( e.getKey() );
+                        out.writeObject( e.getValue() );
+                    }
+                }
 
-        }
-        catch( IOException e )
-        {
-            log.error("Unable to serialize!");
+                out.close();
 
-            try
+            }
+            catch( IOException e )
             {
-                if( out != null ) out.close();
+                log.error( "Unable to serialize!", e );
+
             }
-            catch( IOException ex ) {}
-        }
-        catch( NoSuchAlgorithmException e )
-        {
-            log.fatal("No MD5 algorithm!?!");
-        }
-        finally
-        {
-            sw.stop();
+            finally
+            {
+                sw.stop();
 
-            log.debug("serialization for "+p.getName()+" done - took "+sw);
+                log.debug("serialization for "+p.getName()+" done - took "+sw);
+            }
         }
+        
     }
 
     /**
@@ -559,7 +537,8 @@ public class ReferenceManager
      *  @param context {@inheritDoc}
      *  @param content {@inheritDoc}
      */
-    public void postSave( WikiContext context, String content )
+    @Override
+	public void postSave( WikiContext context, String content )
     {
         WikiPage page = context.getPage();
 
@@ -630,18 +609,14 @@ public class ReferenceManager
         //
         serializeToDisk();
 
-        try
-        {
-            File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
+        String hashName = getHashFileName( pageName );
+        if( hashName != null ) {
+        	File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR );
 
             f = new File( f, getHashFileName(pageName) );
 
             if( f.exists() ) f.delete();
         }
-        catch( NoSuchAlgorithmException e )
-        {
-            log.error("What do you mean - no such algorithm?", e);
-        }
     }
 
     /**
@@ -684,7 +659,7 @@ public class ReferenceManager
         Collection< String > oldRefTo = m_refersTo.get( page );
         m_refersTo.remove( page );
 
-        TreeSet<String> cleanedRefs = new TreeSet<String>();
+        TreeSet<String> cleanedRefs = new TreeSet<>();
         for( Iterator< String > i = references.iterator(); i.hasNext(); )
         {
             String ref = i.next();
@@ -1143,7 +1118,8 @@ public class ReferenceManager
     /**
      *  {@inheritDoc}
      */
-    public void actionPerformed(WikiEvent event)
+    @Override
+	public void actionPerformed(WikiEvent event)
     {
         if( (event instanceof WikiPageEvent) && (event.getType() == WikiPageEvent.PAGE_DELETED) )
         {


[jspwiki] 18/21: fix typo and use constants instead of Strings

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 ebbbecab863cb00b00fe15431ad53d68ff1d51e9
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 21:15:04 2018 +0100

    fix typo and use constants instead of Strings
---
 jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
index e386099..6417a34 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/CryptoUtil.java
@@ -81,7 +81,7 @@ public final class CryptoUtil
         // Print help if the user requested it, or if no arguments
         if( args.length == 0 || (args.length == 1 && HELP.equals( args[0] )) )
         {
-            System.out.println( "Usage: CryptUtil [options] " );
+            System.out.println( "Usage: CryptoUtil [options] " );
             System.out.println( "   --hash   password             create hash for password" );
             System.out.println( "   --verify password digest      verify password for digest" );
             System.exit( 0 );
@@ -95,7 +95,7 @@ public final class CryptoUtil
                 throw new IllegalArgumentException( "Error: --hash requires a 'password' argument." );
             }
             final String password = args[1].trim();
-            System.out.println( CryptoUtil.getSaltedPassword( password.getBytes("UTF-8") ) );
+            System.out.println( CryptoUtil.getSaltedPassword( password.getBytes( StandardCharsets.UTF_8 ) ) );
         }
 
         // User wants to verify an existing password
@@ -107,7 +107,7 @@ public final class CryptoUtil
             }
             final String password = args[1].trim();
             final String digest = args[2].trim();
-            System.out.println( CryptoUtil.verifySaltedPassword( password.getBytes("UTF-8"), digest ) );
+            System.out.println( CryptoUtil.verifySaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), digest ) );
         }
 
         else


[jspwiki] 19/21: try to load as many externals third-party jars as possible instead of trying all-or-nothing approach of loading them

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 9dfbe706c082d16d47f256bddf540d007003dba1
Author: juanpablo <ju...@apache.org>
AuthorDate: Mon Nov 5 21:17:11 2018 +0100

    try to load as many externals third-party jars as possible instead of trying all-or-nothing approach of loading them
---
 .../main/java/org/apache/wiki/util/ClassUtil.java  | 27 ++++++++++++----------
 1 file changed, 15 insertions(+), 12 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
index 9931192..024cad1 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/util/ClassUtil.java
@@ -37,7 +37,6 @@ import java.util.jar.JarFile;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.apache.wiki.api.engine.PluginManager;
 import org.jdom2.Element;
 
 /**
@@ -124,12 +123,10 @@ public final class ClassUtil {
     }
 
     /**
-     * Setup the plugin classloader.
-     * Check if there are external JARS to add via property {@link org.apache.wiki.api.engine.PluginManager#PROP_EXTERNALJARS}
-     *
-     * @return the classloader that can load classes from the configured external jars or
-     *         ,if not specified, the classloader that loaded this class.
-     * @param externaljars
+     * Setup the plugin classloader, checking if there are external JARS to add.
+     * 
+     * @param externaljars external jars to load into the classloader.
+     * @return the classloader that can load classes from the configured external jars or, if not specified, the classloader that loaded this class.
      */
     private static ClassLoader setupClassLoader(List<String> externaljars) {
         classLoaderSetup = true;
@@ -140,17 +137,23 @@ public final class ClassUtil {
         }
         URL[] urls = new URL[externaljars.size()];
         int i = 0;
-        try {
-            for (String externaljar : externaljars) {
-                File jarFile = new File(externaljar);
+        for( String externaljar : externaljars ) {
+            try {
+                File jarFile = new File( externaljar );
                 URL ucl = jarFile.toURI().toURL();
                 urls[i++] = ucl;
                 log.info("added " + ucl + " to list of external jars");
+            } catch (MalformedURLException e) {
+                log.error("exception (" + e.getMessage() +") while setting up classloaders for external jar:" + externaljar + ", continuing without external jars.");
             }
-        } catch (MalformedURLException e) {
-            log.error("exception while setting up classloaders for external jars via property" + PluginManager.PROP_EXTERNALJARS + ", continuing without external jars.");
+        }
+        
+        if( i == 0 ) {
+            log.error( "all external jars threw an exception while setting up classloaders for them, continuing with standard classloading. " + 
+                       "See https://jspwiki-wiki.apache.org/Wiki.jsp?page=InstallingPlugins for help on how to install custom plugins." );
             return ClassUtil.class.getClassLoader();
         }
+        
         return new URLClassLoader(urls, ClassUtil.class.getClassLoader());
     }