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 2297125aa8a2d6cdbfaf1f9c5be89591ca0dcd8b Author: juanpablo <[email protected]> AuthorDate: Thu Jan 9 21:38:29 2020 +0100 apply format and fixes suggested by IntelliJ --- .../main/java/org/apache/wiki/WikiProvider.java | 3 +- .../src/main/java/org/apache/wiki/WikiServlet.java | 24 +- .../src/main/java/org/apache/wiki/WikiSession.java | 603 ++++++++------------- .../main/java/org/apache/wiki/plugin/Counter.java | 66 +-- 4 files changed, 256 insertions(+), 440 deletions(-) diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiProvider.java index d9e6f45..8e13402 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/WikiProvider.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiProvider.java @@ -30,8 +30,7 @@ import java.util.Properties; * * @since 2.0 */ -public interface WikiProvider -{ +public interface WikiProvider { /** * Passing this to any method should get the latest version */ diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiServlet.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiServlet.java index b8a405b..45c5f2f 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/WikiServlet.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiServlet.java @@ -18,7 +18,9 @@ */ package org.apache.wiki; -import java.io.IOException; +import net.sf.ehcache.CacheManager; +import org.apache.log4j.Logger; +import org.apache.wiki.url.DefaultURLConstructor; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; @@ -26,11 +28,7 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; -import org.apache.wiki.url.DefaultURLConstructor; - -import net.sf.ehcache.CacheManager; +import java.io.IOException; /** @@ -44,13 +42,13 @@ public class WikiServlet extends HttpServlet { private static final long serialVersionUID = 3258410651167633973L; private WikiEngine m_engine; - static final Logger log = Logger.getLogger( WikiServlet.class.getName() ); + private static final Logger log = Logger.getLogger( WikiServlet.class.getName() ); /** * {@inheritDoc} */ @Override - public void init( ServletConfig config ) throws ServletException { + public void init( final ServletConfig config ) throws ServletException { super.init( config ); m_engine = WikiEngine.getInstance( config ); log.info( "WikiServlet initialized." ); @@ -77,7 +75,7 @@ public class WikiServlet extends HttpServlet { * {@inheritDoc} */ @Override - public void doPost( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { + public void doPost( final HttpServletRequest req, final HttpServletResponse res ) throws IOException, ServletException { doGet( req, res ); } @@ -85,7 +83,7 @@ public class WikiServlet extends HttpServlet { * {@inheritDoc} */ @Override - public void doGet( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { + public void doGet( final HttpServletRequest req, final HttpServletResponse res ) throws IOException, ServletException { String pageName = DefaultURLConstructor.parsePageFromURL( req, m_engine.getContentEncoding() ); log.info( "Request for page: " + pageName ); @@ -93,9 +91,9 @@ public class WikiServlet extends HttpServlet { pageName = m_engine.getFrontPage(); // FIXME: Add special pages as well } - String jspPage = m_engine.getURLConstructor().getForwardPage( req ); - RequestDispatcher dispatcher = req.getRequestDispatcher( "/" + jspPage + "?page=" + - m_engine.encodeName( pageName ) + "&" + req.getQueryString() ); + final String jspPage = m_engine.getURLConstructor().getForwardPage( req ); + final RequestDispatcher dispatcher = req.getRequestDispatcher( "/" + jspPage + "?page=" + + m_engine.encodeName( pageName ) + "&" + req.getQueryString() ); dispatcher.forward( req, res ); } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiSession.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiSession.java index eb58b90..756260f 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/WikiSession.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiSession.java @@ -51,10 +51,9 @@ import java.util.Map; import java.util.Set; /** - * <p>Represents a long-running wiki session, with an associated user Principal, - * user Subject, and authentication status. This class is initialized with - * minimal, default-deny values: authentication is set to <code>false</code>, - * and the user principal is set to <code>null</code>.</p> + * <p>Represents a long-running wiki session, with an associated user Principal, user Subject, and authentication status. This class + * is initialized with minimal, default-deny values: authentication is set to <code>false</code>, and the user principal is set to + * <code>null</code>.</p> * <p>The WikiSession class allows callers to:</p> * <ul> * <li>Obtain the authentication status of the user via @@ -66,34 +65,23 @@ import java.util.Set; * {@link #addMessage(String)}, {@link #getMessages(String)} * and {@link #clearMessages(String)}</li> * </ul> - * <p>To keep track of the Principals each user posseses, each WikiSession - * stores a JAAS Subject. Various login processes add or remove Principals - * when users authenticate or log out.</p> - * <p>WikiSession implements the {@link org.apache.wiki.event.WikiEventListener} - * interface and listens for group add/change/delete events fired by - * event sources the WikiSession is registered with. Normally, - * {@link org.apache.wiki.auth.AuthenticationManager} registers each WikiSession - * with the {@link org.apache.wiki.auth.authorize.GroupManager} - * so it can catch group events. Thus, when a user is added to a - * {@link org.apache.wiki.auth.authorize.Group}, a corresponding - * {@link org.apache.wiki.auth.GroupPrincipal} is injected into - * the Subject's Principal set. Likewise, when the user is removed from - * the Group or the Group is deleted, the GroupPrincipal is removed - * from the Subject. The effect that this strategy produces is extremely - * beneficial: when someone adds a user to a wiki group, that user - * <em>immediately</em> gains the privileges associated with that - * group; he or she does not need to re-authenticate. + * <p>To keep track of the Principals each user posseses, each WikiSession stores a JAAS Subject. Various login processes add or + * remove Principals when users authenticate or log out.</p> + * <p>WikiSession implements the {@link org.apache.wiki.event.WikiEventListener} interface and listens for group add/change/delete + * events fired by event sources the WikiSession is registered with. Normally, {@link org.apache.wiki.auth.AuthenticationManager} + * registers each WikiSession with the {@link org.apache.wiki.auth.authorize.GroupManager} so it can catch group events. Thus, when + * a user is added to a {@link org.apache.wiki.auth.authorize.Group}, a corresponding {@link org.apache.wiki.auth.GroupPrincipal} is + * injected into the Subject's Principal set. Likewise, when the user is removed from the Group or the Group is deleted, the + * GroupPrincipal is removed from the Subject. The effect that this strategy produces is extremely beneficial: when someone adds a user + * to a wiki group, that user <em>immediately</em> gains the privileges associated with that group; he or she does not need to + * re-authenticate. * </p> - * <p>In addition to methods for examining individual <code>WikiSession</code> - * objects, this class also contains a number of static methods for - * managing WikiSessions for an entire wiki. These methods allow callers - * to find, query and remove WikiSession objects, and + * <p>In addition to methods for examining individual <code>WikiSession</code> objects, this class also contains a number of static + * methods for managing WikiSessions for an entire wiki. These methods allow callers to find, query and remove WikiSession objects, and * to obtain a list of the current wiki session users.</p> - * <p>WikiSession encloses a protected static class, {@link SessionMonitor}, - * to keep track of WikiSessions registered with each wiki.</p> + * <p>WikiSession encloses a protected static class, {@link SessionMonitor}, to keep track of WikiSessions registered with each wiki.</p> */ -public final class WikiSession implements WikiEventListener -{ +public final class WikiSession implements WikiEventListener { /** An anonymous user's session status. */ public static final String ANONYMOUS = "anonymous"; @@ -132,36 +120,31 @@ public final class WikiSession implements WikiEventListener private Locale m_cachedLocale = Locale.getDefault(); /** - * Returns <code>true</code> if one of this WikiSession's user Principals - * can be shown to belong to a particular wiki group. If the user is - * not authenticated, this method will always return <code>false</code>. + * Returns <code>true</code> if one of this WikiSession's user Principals can be shown to belong to a particular wiki group. If + * the user is not authenticated, this method will always return <code>false</code>. + * * @param group the group to test * @return the result */ - protected boolean isInGroup( Group group ) - { - for ( Principal principal : getPrincipals() ) - { - if ( isAuthenticated() && group.isMember( principal ) ) - { - return true; - } + protected boolean isInGroup( final Group group ) { + for( final Principal principal : getPrincipals() ) { + if( isAuthenticated() && group.isMember( principal ) ) { + return true; + } } return false; } /** - * Private constructor to prevent WikiSession from being instantiated - * directly. + * Private constructor to prevent WikiSession from being instantiated directly. */ - private WikiSession() - { + private WikiSession() { } /** - * Returns <code>true</code> if the user is considered asserted via - * a session cookie; that is, the Subject contains the Principal + * Returns <code>true</code> if the user is considered asserted via a session cookie; that is, the Subject contains the Principal * Role.ASSERTED. + * * @return Returns <code>true</code> if the user is asserted */ public boolean isAsserted() @@ -170,26 +153,20 @@ public final class WikiSession implements WikiEventListener } /** - * Returns the authentication status of the user's session. The user is - * considered authenticated if the Subject contains the Principal - * Role.AUTHENTICATED. If this method determines that an earlier - * LoginModule did not inject Role.AUTHENTICATED, it will inject one - * if the user is not anonymous <em>and</em> not asserted. + * Returns the authentication status of the user's session. The user is considered authenticated if the Subject contains the + * Principal Role.AUTHENTICATED. If this method determines that an earlier LoginModule did not inject Role.AUTHENTICATED, it + * will inject one if the user is not anonymous <em>and</em> not asserted. + * * @return Returns <code>true</code> if the user is authenticated */ - public boolean isAuthenticated() - { + public boolean isAuthenticated() { // If Role.AUTHENTICATED is in principals set, always return true. - if ( m_subject.getPrincipals().contains( Role.AUTHENTICATED ) ) - { + if ( m_subject.getPrincipals().contains( Role.AUTHENTICATED ) ) { return true; } - // With non-JSPWiki LoginModules, the role may not be there, so - // we need to add it if the user really is authenticated. - if ( !isAnonymous() && !isAsserted() ) - { - // Inject AUTHENTICATED role + // With non-JSPWiki LoginModules, the role may not be there, so we need to add it if the user really is authenticated. + if ( !isAnonymous() && !isAsserted() ) { m_subject.getPrincipals().add( Role.AUTHENTICATED ); return true; } @@ -198,8 +175,7 @@ public final class WikiSession implements WikiEventListener } /** - * <p>Determines whether the current session is anonymous. This will be - * true if any of these conditions are true:</p> + * <p>Determines whether the current session is anonymous. This will be true if any of these conditions are true:</p> * <ul> * <li>The session's Principal set contains * {@link org.apache.wiki.auth.authorize.Role#ANONYMOUS}</li> @@ -208,30 +184,24 @@ public final class WikiSession implements WikiEventListener * <li>The Principal returned by {@link #getUserPrincipal()} evaluates * to an IP address.</li> * </ul> - * <p>The criteria above are listed in the order in which they are - * evaluated.</p> - * @return whether the current user's identity is equivalent to an IP - * address + * <p>The criteria above are listed in the order in which they are evaluated.</p> + * @return whether the current user's identity is equivalent to an IP address */ - public boolean isAnonymous() - { - Set<Principal> principals = m_subject.getPrincipals(); + public boolean isAnonymous() { + final Set< Principal > principals = m_subject.getPrincipals(); return principals.contains( Role.ANONYMOUS ) || - principals.contains( WikiPrincipal.GUEST ) || - isIPV4Address( getUserPrincipal().getName() ); + principals.contains( WikiPrincipal.GUEST ) || + isIPV4Address( getUserPrincipal().getName() ); } /** - * <p> Returns the Principal used to log in to an authenticated session. The - * login principal is determined by examining the Subject's Principal set - * for PrincipalWrappers or WikiPrincipals with type designator - * <code>LOGIN_NAME</code>; the first one found is the login principal. - * If one is not found, this method returns the first principal that isn't - * of type Role or GroupPrincipal. If neither of these conditions hold, this method returns - * {@link org.apache.wiki.auth.WikiPrincipal#GUEST}. - * @return the login Principal. If it is a PrincipalWrapper containing an - * externally-provided Principal, the object returned is the Principal, not - * the wrapper around it. + * <p> Returns the Principal used to log in to an authenticated session. The login principal is determined by examining the + * Subject's Principal set for PrincipalWrappers or WikiPrincipals with type designator <code>LOGIN_NAME</code>; the first one + * found is the login principal. If one is not found, this method returns the first principal that isn't of type Role or + * GroupPrincipal. If neither of these conditions hold, this method returns {@link org.apache.wiki.auth.WikiPrincipal#GUEST}. + * + * @return the login Principal. If it is a PrincipalWrapper containing an externally-provided Principal, the object returned is the + * Principal, not the wrapper around it. */ public Principal getLoginPrincipal() { @@ -239,16 +209,15 @@ public final class WikiSession implements WikiEventListener } /** - * <p>Returns the primary user Principal associated with this session. The - * primary user principal is determined as follows:</p> <ol> <li>If the - * Subject's Principal set contains WikiPrincipals, the first WikiPrincipal - * with type designator <code>WIKI_NAME</code> or (alternatively) - * <code>FULL_NAME</code> is the primary Principal.</li> - * <li>For all other cases, the first Principal in the Subject's principal - * collection that that isn't of type Role or GroupPrincipal is the primary.</li> + * <p>Returns the primary user Principal associated with this session. The primary user principal is determined as follows:</p> + * <ol> + * <li>If the Subject's Principal set contains WikiPrincipals, the first WikiPrincipal with type designator + * <code>WIKI_NAME</code> or (alternatively) <code>FULL_NAME</code> is the primary Principal.</li> + * <li>For all other cases, the first Principal in the Subject's principal collection that that isn't of type Role or + * GroupPrincipal is the primary.</li> * </ol> - * If no primary user Principal is found, this method returns - * {@link org.apache.wiki.auth.WikiPrincipal#GUEST}. + * If no primary user Principal is found, this method returns {@link org.apache.wiki.auth.WikiPrincipal#GUEST}. + * * @return the primary user Principal */ public Principal getUserPrincipal() @@ -257,12 +226,10 @@ public final class WikiSession implements WikiEventListener } /** - * Returns a cached Locale object for this user. It's better to use - * WikiContext's corresponding getBundle() method, since that will actually - * react if the user changes the locale in the middle, but if that's not - * available (or, for some reason, you need the speed), this method can - * also be used. The Locale expires when the WikiSession expires, and - * currently there is no way to reset the Locale. + * Returns a cached Locale object for this user. It's better to use WikiContext's corresponding getBundle() method, since that + * will actually react if the user changes the locale in the middle, but if that's not available (or, for some reason, you need + * the speed), this method can also be used. The Locale expires when the WikiSession expires, and currently there is no way to + * reset the Locale. * * @return A cached Locale object * @since 2.5.96 @@ -273,36 +240,28 @@ public final class WikiSession implements WikiEventListener } /** - * Adds a message to the generic list of messages associated with the - * session. These messages retain their order of insertion and remain until - * the {@link #clearMessages()} method is called. + * Adds a message to the generic list of messages associated with the session. These messages retain their order of insertion and + * remain until the {@link #clearMessages()} method is called. + * * @param message the message to add; if <code>null</code> it is ignored. */ - public void addMessage(String message) + public void addMessage( final String message ) { addMessage( ALL, message ); } - /** - * Adds a message to the specific set of messages associated with the - * session. These messages retain their order of insertion and remain until - * the {@link #clearMessages()} method is called. + * Adds a message to the specific set of messages associated with the session. These messages retain their order of insertion and + * remain until the {@link #clearMessages()} method is called. + * * @param topic the topic to associate the message to; * @param message the message to add */ - public void addMessage(String topic, String message) - { - if ( topic == null ) - { + public void addMessage( final String topic, final String message ) { + if ( topic == null ) { throw new IllegalArgumentException( "addMessage: topic cannot be null." ); } - Set<String> messages = m_messages.get( topic ); - if (messages == null ) - { - messages = new LinkedHashSet<>(); - m_messages.put( topic, messages ); - } + final Set< String > messages = m_messages.computeIfAbsent( topic, k -> new LinkedHashSet<>() ); messages.add( StringUtils.defaultString( message ) ); } @@ -316,13 +275,12 @@ public final class WikiSession implements WikiEventListener /** * Clears all messages associated with a session topic. + * * @param topic the topic whose messages should be cleared. */ - public void clearMessages( String topic ) - { - Set<String> messages = m_messages.get( topic ); - if ( messages != null ) - { + public void clearMessages( final String topic ) { + final Set< String > messages = m_messages.get( topic ); + if ( messages != null ) { m_messages.clear(); } } @@ -345,32 +303,27 @@ public final class WikiSession implements WikiEventListener * @return the current messages. * @param topic The topic */ - public String[] getMessages( String topic ) - { - Set<String> messages = m_messages.get( topic ); - if ( messages == null || messages.size() == 0 ) - { + public String[] getMessages( final String topic ) { + final Set< String > messages = m_messages.get( topic ); + if( messages == null || messages.size() == 0 ) { return new String[0]; } return messages.toArray( new String[messages.size()] ); } /** - * Returns all user Principals associated with this session. User principals - * are those in the Subject's principal collection that aren't of type Role or - * of type GroupPrincipal. This is a defensive copy. + * Returns all user Principals associated with this session. User principals are those in the Subject's principal collection that + * aren't of type Role or of type GroupPrincipal. This is a defensive copy. + * * @return Returns the user principal * @see org.apache.wiki.auth.AuthenticationManager#isUserPrincipal(Principal) */ - public Principal[] getPrincipals() - { - ArrayList<Principal> principals = new ArrayList<>(); + public Principal[] getPrincipals() { + final ArrayList< Principal > principals = new ArrayList<>(); // Take the first non Role as the main Principal - for( Principal principal : m_subject.getPrincipals() ) - { - if ( AuthenticationManager.isUserPrincipal( principal ) ) - { + for( final Principal principal : m_subject.getPrincipals() ) { + if ( AuthenticationManager.isUserPrincipal( principal ) ) { principals.add( principal ); } } @@ -379,21 +332,16 @@ public final class WikiSession implements WikiEventListener } /** - * Returns an array of Principal objects that represents the groups and - * roles that the user associated with a WikiSession possesses. The array is - * built by iterating through the Subject's Principal set and extracting all - * Role and GroupPrincipal objects into a list. The list is returned as an - * array sorted in the natural order implied by each Principal's - * <code>getName</code> method. Note that this method does <em>not</em> - * consult the external Authorizer or GroupManager; it relies on the - * Principals that have been injected into the user's Subject at login time, - * or after group creation/modification/deletion. - * @return an array of Principal objects corresponding to the roles the - * Subject possesses + * Returns an array of Principal objects that represents the groups and roles that the user associated with a WikiSession possesses. + * The array is built by iterating through the Subject's Principal set and extracting all Role and GroupPrincipal objects into a + * list. The list is returned as an array sorted in the natural order implied by each Principal's <code>getName</code> method. Note + * that this method does <em>not</em> consult the external Authorizer or GroupManager; it relies on the Principals that have been + * injected into the user's Subject at login time, or after group creation/modification/deletion. + * + * @return an array of Principal objects corresponding to the roles the Subject possesses */ - public Principal[] getRoles() - { - Set<Principal> roles = new HashSet<>(); + public Principal[] getRoles() { + final Set< Principal > roles = new HashSet<>(); // Add all of the Roles possessed by the Subject directly roles.addAll( m_subject.getPrincipals( Role.class ) ); @@ -402,104 +350,79 @@ public final class WikiSession implements WikiEventListener roles.addAll( m_subject.getPrincipals( GroupPrincipal.class ) ); // Return a defensive copy - Principal[] roleArray = roles.toArray( new Principal[roles.size()] ); + final Principal[] roleArray = roles.toArray( new Principal[roles.size()] ); Arrays.sort( roleArray, WikiPrincipal.COMPARATOR ); return roleArray; } /** - * Removes the wiki session associated with the user's HTTP request - * from the cache of wiki sessions, typically as part of a logout - * process. + * Removes the wiki session associated with the user's HTTP request from the cache of wiki sessions, typically as part of a + * logout process. + * * @param engine the wiki engine * @param request the users's HTTP request */ - public static void removeWikiSession( WikiEngine engine, HttpServletRequest request ) - { - if ( engine == null || request == null ) - { + public static void removeWikiSession( final WikiEngine engine, final HttpServletRequest request ) { + if ( engine == null || request == null ) { throw new IllegalArgumentException( "Request or engine cannot be null." ); } - SessionMonitor monitor = SessionMonitor.getInstance( engine ); + final SessionMonitor monitor = SessionMonitor.getInstance( engine ); monitor.remove( request.getSession() ); } /** - * Returns <code>true</code> if the WikiSession's Subject - * possess a supplied Principal. This method eliminates the need - * to externally request and inspect the JAAS subject. + * Returns <code>true</code> if the WikiSession's Subject possess a supplied Principal. This method eliminates the need to externally + * request and inspect the JAAS subject. + * * @param principal the Principal to test * @return the result */ - public boolean hasPrincipal( Principal principal ) - { + public boolean hasPrincipal( final Principal principal ) { return m_subject.getPrincipals().contains( principal ); - } /** - * Listens for WikiEvents generated by source objects such as the - * GroupManager. This method adds Principals to the private Subject managed - * by the WikiSession. + * Listens for WikiEvents generated by source objects such as the GroupManager. This method adds Principals to the private Subject + * managed by the WikiSession. + * * @see org.apache.wiki.event.WikiEventListener#actionPerformed(org.apache.wiki.event.WikiEvent) */ @Override - public void actionPerformed( WikiEvent event ) - { - if ( event instanceof WikiSecurityEvent ) - { - WikiSecurityEvent e = (WikiSecurityEvent)event; - if ( e.getTarget() != null ) - { - switch (e.getType() ) - { + public void actionPerformed( final WikiEvent event ) { + if ( event instanceof WikiSecurityEvent ) { + final WikiSecurityEvent e = (WikiSecurityEvent)event; + if ( e.getTarget() != null ) { + switch (e.getType() ) { case WikiSecurityEvent.GROUP_ADD: - { - Group group = (Group)e.getTarget(); - if ( isInGroup( group ) ) - { - m_subject.getPrincipals().add( group.getPrincipal() ); + final Group groupAdd = (Group)e.getTarget(); + if ( isInGroup( groupAdd ) ) { + m_subject.getPrincipals().add( groupAdd.getPrincipal() ); } break; - } case WikiSecurityEvent.GROUP_REMOVE: - { - Group group = (Group)e.getTarget(); - if ( m_subject.getPrincipals().contains( group.getPrincipal() ) ) - { - m_subject.getPrincipals().remove( group.getPrincipal() ); - } + final Group group = (Group)e.getTarget(); + m_subject.getPrincipals().remove( group.getPrincipal() ); break; - } case WikiSecurityEvent.GROUP_CLEAR_GROUPS: - { m_subject.getPrincipals().removeAll( m_subject.getPrincipals( GroupPrincipal.class ) ); break; - } case WikiSecurityEvent.LOGIN_INITIATED: - { // Do nothing break; - } case WikiSecurityEvent.PRINCIPAL_ADD: - { - WikiSession target = (WikiSession)e.getTarget(); - if ( this.equals( target ) && m_status.equals(AUTHENTICATED) ) - { - Set<Principal> principals = m_subject.getPrincipals(); - principals.add( (Principal)e.getPrincipal()); + final WikiSession targetPA = (WikiSession)e.getTarget(); + if ( this.equals( targetPA ) && m_status.equals(AUTHENTICATED) ) { + final Set<Principal> principals = m_subject.getPrincipals(); + principals.add( ( Principal )e.getPrincipal() ); } break; - } case WikiSecurityEvent.LOGIN_ANONYMOUS: - { - WikiSession target = (WikiSession)e.getTarget(); - if ( this.equals( target ) ) - { + final WikiSession targetLAN = (WikiSession)e.getTarget(); + if( this.equals( targetLAN ) ) { m_status = ANONYMOUS; // Set the login/user principals and login status - Set<Principal> principals = m_subject.getPrincipals(); + final Set<Principal> principals = m_subject.getPrincipals(); m_loginPrincipal = (Principal)e.getPrincipal(); m_userPrincipal = m_loginPrincipal; @@ -510,16 +433,13 @@ public final class WikiSession implements WikiEventListener principals.add( Role.ANONYMOUS ); } break; - } case WikiSecurityEvent.LOGIN_ASSERTED: - { - WikiSession target = (WikiSession)e.getTarget(); - if ( this.equals( target ) ) - { + final WikiSession targetLAS = (WikiSession)e.getTarget(); + if ( this.equals( targetLAS ) ) { m_status = ASSERTED; // Set the login/user principals and login status - Set<Principal> principals = m_subject.getPrincipals(); + final Set<Principal> principals = m_subject.getPrincipals(); m_loginPrincipal = (Principal)e.getPrincipal(); m_userPrincipal = m_loginPrincipal; @@ -530,16 +450,13 @@ public final class WikiSession implements WikiEventListener principals.add( Role.ASSERTED ); } break; - } case WikiSecurityEvent.LOGIN_AUTHENTICATED: - { - WikiSession target = (WikiSession)e.getTarget(); - if ( this.equals( target ) ) - { + final WikiSession targetLAU = (WikiSession)e.getTarget(); + if ( this.equals( targetLAU ) ) { m_status = AUTHENTICATED; // Set the login/user principals and login status - Set<Principal> principals = m_subject.getPrincipals(); + final Set<Principal> principals = m_subject.getPrincipals(); m_loginPrincipal = (Principal)e.getPrincipal(); m_userPrincipal = m_loginPrincipal; @@ -554,32 +471,25 @@ public final class WikiSession implements WikiEventListener injectGroupPrincipals(); // Inject group principals } break; - } case WikiSecurityEvent.PROFILE_SAVE: - { - WikiSession source = e.getSrc(); - if ( this.equals( source ) ) - { + final WikiSession sourcePS = e.getSrc(); + if ( this.equals( sourcePS ) ) { injectUserProfilePrincipals(); // Add principals for the user profile injectGroupPrincipals(); // Inject group principals } break; - } case WikiSecurityEvent.PROFILE_NAME_CHANGED: - { // Refresh user principals based on new user profile - WikiSession source = e.getSrc(); - if ( this.equals( source ) && m_status.equals(AUTHENTICATED) ) - { + final WikiSession sourcePNC = e.getSrc(); + if ( this.equals( sourcePNC ) && m_status.equals(AUTHENTICATED) ) { // To prepare for refresh, set the new full name as the primary principal - UserProfile[] profiles = (UserProfile[])e.getTarget(); - UserProfile newProfile = profiles[1]; - if ( newProfile.getFullname() == null ) - { + final UserProfile[] profiles = (UserProfile[])e.getTarget(); + final UserProfile newProfile = profiles[1]; + if ( newProfile.getFullname() == null ) { throw new IllegalStateException( "User profile FullName cannot be null." ); } - Set<Principal> principals = m_subject.getPrincipals(); + final Set<Principal> principals = m_subject.getPrincipals(); m_loginPrincipal = new WikiPrincipal( newProfile.getLoginName() ); // Add the login principal to the Subject, and set the built-in roles @@ -593,24 +503,18 @@ public final class WikiSession implements WikiEventListener injectGroupPrincipals(); // Inject group principals } break; - } - // // No action, if the event is not recognized. - // - default: - break; + default: break; } } } } /** - * Invalidates the WikiSession and resets its Subject's - * Principals to the equivalent of a "guest session". + * Invalidates the WikiSession and resets its Subject's Principals to the equivalent of a "guest session". */ - public void invalidate() - { + public void invalidate() { m_subject.getPrincipals().clear(); m_subject.getPrincipals().add( WikiPrincipal.GUEST ); m_subject.getPrincipals().add( Role.ANONYMOUS ); @@ -620,81 +524,62 @@ public final class WikiSession implements WikiEventListener } /** - * Injects GroupPrincipal objects into the user's Principal set based on the - * groups the user belongs to. For Groups, the algorithm first calls the - * {@link GroupManager#getRoles()} to obtain the array of GroupPrincipals - * the authorizer knows about. Then, the method - * {@link GroupManager#isUserInRole(WikiSession, Principal)} is called for - * each Principal. If the user is a member of the group, an equivalent - * GroupPrincipal is injected into the user's principal set. Existing - * GroupPrincipals are flushed and replaced. This method should generally be - * called after a user's {@link org.apache.wiki.auth.user.UserProfile} is - * saved. If the wiki session is null, or there is no matching user profile, - * the method returns silently. + * Injects GroupPrincipal objects into the user's Principal set based on the groups the user belongs to. For Groups, the algorithm + * first calls the {@link GroupManager#getRoles()} to obtain the array of GroupPrincipals the authorizer knows about. Then, the + * method {@link GroupManager#isUserInRole(WikiSession, Principal)} is called for each Principal. If the user is a member of the + * group, an equivalent GroupPrincipal is injected into the user's principal set. Existing GroupPrincipals are flushed and replaced. + * This method should generally be called after a user's {@link org.apache.wiki.auth.user.UserProfile} is saved. If the wiki session + * is null, or there is no matching user profile, the method returns silently. */ - protected void injectGroupPrincipals() - { + protected void injectGroupPrincipals() { // Flush the existing GroupPrincipals m_subject.getPrincipals().removeAll( m_subject.getPrincipals(GroupPrincipal.class) ); // Get the GroupManager and test for each Group - GroupManager manager = m_engine.getGroupManager(); - for ( Principal group : manager.getRoles() ) - { - if ( manager.isUserInRole( this, group ) ) - { + final GroupManager manager = m_engine.getGroupManager(); + for( final Principal group : manager.getRoles() ) { + if ( manager.isUserInRole( this, group ) ) { m_subject.getPrincipals().add( group ); } } } /** - * Adds Principal objects to the Subject that correspond to the - * logged-in user's profile attributes for the wiki name, full name - * and login name. These Principals will be WikiPrincipals, and they - * will replace all other WikiPrincipals in the Subject. <em>Note: + * Adds Principal objects to the Subject that correspond to the logged-in user's profile attributes for the wiki name, full name + * and login name. These Principals will be WikiPrincipals, and they will replace all other WikiPrincipals in the Subject. <em>Note: * this method is never called during anonymous or asserted sessions.</em> */ - protected void injectUserProfilePrincipals() - { + protected void injectUserProfilePrincipals() { // Search for the user profile - String searchId = m_loginPrincipal.getName(); - if ( searchId == null ) - { + final String searchId = m_loginPrincipal.getName(); + if ( searchId == null ) { // Oh dear, this wasn't an authenticated user after all log.info("Refresh principals failed because WikiSession had no user Principal; maybe not logged in?"); return; } // Look up the user and go get the new Principals - UserDatabase database = m_engine.getUserManager().getUserDatabase(); - if ( database == null ) - { + final UserDatabase database = m_engine.getUserManager().getUserDatabase(); + if( database == null ) { throw new IllegalStateException( "User database cannot be null." ); } - try - { - UserProfile profile = database.find( searchId ); - Principal[] principals = database.getPrincipals( profile.getLoginName() ); - for ( Principal principal : principals ) - { + try { + final UserProfile profile = database.find( searchId ); + final Principal[] principals = database.getPrincipals( profile.getLoginName() ); + for( final Principal principal : principals ) { // Add the Principal to the Subject m_subject.getPrincipals().add( principal ); // Set the user principal if needed; we prefer FullName, but the WikiName will also work - boolean isFullNamePrincipal = ( principal instanceof WikiPrincipal && ((WikiPrincipal)principal).getType() == WikiPrincipal.FULL_NAME ); - if ( isFullNamePrincipal ) - { + final boolean isFullNamePrincipal = ( principal instanceof WikiPrincipal && + ( ( WikiPrincipal )principal ).getType().equals( WikiPrincipal.FULL_NAME ) ); + if ( isFullNamePrincipal ) { m_userPrincipal = principal; - } - else if ( !( m_userPrincipal instanceof WikiPrincipal ) ) - { + } else if ( !( m_userPrincipal instanceof WikiPrincipal ) ) { m_userPrincipal = principal; } } - } - catch ( NoSuchPrincipalException e ) - { + } catch ( final NoSuchPrincipalException e ) { // We will get here if the user has a principal but not a profile // For example, it's a container-managed user who hasn't set up a profile yet log.warn("User profile '" + searchId + "' not found. This is normal for container-auth users who haven't set up a profile yet."); @@ -710,70 +595,59 @@ public final class WikiSession implements WikiEventListener * </ul> * @return the user's session status */ - public String getStatus() - { + public String getStatus() { return m_status; } /** - * <p>Static factory method that returns the WikiSession object associated with - * the current HTTP request. This method looks up the associated HttpSession - * in an internal WeakHashMap and attempts to retrieve the WikiSession. If - * not found, one is created. This method is guaranteed to always return a - * WikiSession, although the authentication status is unpredictable until - * the user attempts to log in. If the servlet request parameter is - * <code>null</code>, a synthetic {@link #guestSession(WikiEngine)}is returned.</p> - * <p>When a session is created, this method attaches a WikiEventListener - * to the GroupManager so that changes to groups are detected automatically.</p> + * <p>Static factory method that returns the WikiSession object associated with the current HTTP request. This method looks up + * the associated HttpSession in an internal WeakHashMap and attempts to retrieve the WikiSession. If not found, one is created. + * This method is guaranteed to always return a WikiSession, although the authentication status is unpredictable until the user + * attempts to log in. If the servlet request parameter is <code>null</code>, a synthetic {@link #guestSession(WikiEngine)} is + * returned.</p> + * <p>When a session is created, this method attaches a WikiEventListener to the GroupManager so that changes to groups are detected + * automatically.</p> + * * @param engine the wiki engine * @param request the servlet request object * @return the existing (or newly created) wiki session */ - public static WikiSession getWikiSession( WikiEngine engine, HttpServletRequest request ) - { - // If request is null, return guest session - if ( request == null ) - { - if ( log.isDebugEnabled() ) - { + public static WikiSession getWikiSession( final WikiEngine engine, final HttpServletRequest request ) { + if ( request == null ) { + if ( log.isDebugEnabled() ) { log.debug( "Looking up WikiSession for NULL HttpRequest: returning guestSession()" ); } return staticGuestSession( engine ); } - // Look for a WikiSession associated with the user's Http Session - // and create one if it isn't there yet. - HttpSession session = request.getSession(); - SessionMonitor monitor = SessionMonitor.getInstance( engine ); - WikiSession wikiSession = monitor.find( session ); + // Look for a WikiSession associated with the user's Http Session and create one if it isn't there yet. + final HttpSession session = request.getSession(); + final SessionMonitor monitor = SessionMonitor.getInstance( engine ); + final WikiSession wikiSession = monitor.find( session ); // Attach reference to wiki engine wikiSession.m_engine = engine; - wikiSession.m_cachedLocale = request.getLocale(); - return wikiSession; } /** - * Static factory method that creates a new "guest" session containing a single - * user Principal {@link org.apache.wiki.auth.WikiPrincipal#GUEST}, - * plus the role principals {@link Role#ALL} and - * {@link Role#ANONYMOUS}. This method also adds the session as a listener - * for GroupManager, AuthenticationManager and UserManager events. + * Static factory method that creates a new "guest" session containing a single user Principal + * {@link org.apache.wiki.auth.WikiPrincipal#GUEST}, plus the role principals {@link Role#ALL} and {@link Role#ANONYMOUS}. This + * method also adds the session as a listener for GroupManager, AuthenticationManager and UserManager events. + * * @param engine the wiki engine * @return the guest wiki session */ - public static WikiSession guestSession( WikiEngine engine ) - { - WikiSession session = new WikiSession(); + public static WikiSession guestSession( final WikiEngine engine ) { + final WikiSession session = new WikiSession(); session.m_engine = engine; session.invalidate(); // Add the session as listener for GroupManager, AuthManager, UserManager events - GroupManager groupMgr = engine.getGroupManager(); - AuthenticationManager authMgr = engine.getAuthenticationManager(); - UserManager userMgr = engine.getUserManager(); + final GroupManager groupMgr = engine.getGroupManager(); + final AuthenticationManager authMgr = engine.getAuthenticationManager(); + final UserManager userMgr = engine.getUserManager(); groupMgr.addWikiEventListener( session ); authMgr.addWikiEventListener( session ); userMgr.addWikiEventListener( session ); @@ -782,25 +656,17 @@ public final class WikiSession implements WikiEventListener } /** - * Returns a static guest session, which is available for this - * thread only. This guest session is used internally whenever - * there is no HttpServletRequest involved, but the request is - * done e.g. when embedding JSPWiki code. + * Returns a static guest session, which is available for this thread only. This guest session is used internally whenever + * there is no HttpServletRequest involved, but the request is done e.g. when embedding JSPWiki code. * * @param engine WikiEngine for this session - * @return A static WikiSession which is shared by all in this - * same Thread. + * @return A static WikiSession which is shared by all in this same Thread. */ // FIXME: Should really use WeakReferences to clean away unused sessions. - - private static WikiSession staticGuestSession( WikiEngine engine ) - { + private static WikiSession staticGuestSession( final WikiEngine engine ) { WikiSession session = c_guestSession.get(); - - if( session == null ) - { + if( session == null ) { session = guestSession( engine ); - c_guestSession.set( session ); } @@ -808,47 +674,42 @@ public final class WikiSession implements WikiEventListener } /** - * Returns the total number of active wiki sessions for a - * particular wiki. This method delegates to the wiki's + * Returns the total number of active wiki sessions for a particular wiki. This method delegates to the wiki's * {@link SessionMonitor#sessions()} method. + * * @param engine the wiki session * @return the number of sessions */ - public static int sessions( WikiEngine engine ) - { - SessionMonitor monitor = SessionMonitor.getInstance( engine ); + public static int sessions( final WikiEngine engine ) { + final SessionMonitor monitor = SessionMonitor.getInstance( engine ); return monitor.sessions(); } /** - * Returns Principals representing the current users known - * to a particular wiki. Each Principal will correspond to the - * value returned by each WikiSession's {@link #getUserPrincipal()} - * method. This method delegates to {@link SessionMonitor#userPrincipals()}. + * Returns Principals representing the current users known to a particular wiki. Each Principal will correspond to the + * value returned by each WikiSession's {@link #getUserPrincipal()} method. This method delegates to + * {@link SessionMonitor#userPrincipals()}. + * * @param engine the wiki engine * @return an array of Principal objects, sorted by name */ - public static Principal[] userPrincipals( WikiEngine engine ) - { - SessionMonitor monitor = SessionMonitor.getInstance( engine ); + public static Principal[] userPrincipals( final WikiEngine engine ) { + final SessionMonitor monitor = SessionMonitor.getInstance( engine ); return monitor.userPrincipals(); } /** * Wrapper for * {@link javax.security.auth.Subject#doAsPrivileged(Subject, java.security.PrivilegedExceptionAction, java.security.AccessControlContext)} - * that executes an action with the privileges posssessed by a - * WikiSession's Subject. The action executes with a <code>null</code> - * AccessControlContext, which has the effect of running it "cleanly" - * without the AccessControlContexts of the caller. + * that executes an action with the privileges posssessed by a WikiSession's Subject. The action executes with a <code>null</code> + * AccessControlContext, which has the effect of running it "cleanly" without the AccessControlContexts of the caller. + * * @param session the wiki session * @param action the privileged action * @return the result of the privileged action; may be <code>null</code> - * @throws java.security.AccessControlException if the action is not permitted - * by the security policy + * @throws java.security.AccessControlException if the action is not permitted by the security policy */ - public static Object doPrivileged( WikiSession session, PrivilegedAction<?> action ) throws AccessControlException - { + public static Object doPrivileged( final WikiSession session, final PrivilegedAction<?> action ) throws AccessControlException { return Subject.doAsPrivileged( session.m_subject, action, null ); } @@ -858,39 +719,29 @@ public final class WikiSession implements WikiEventListener * @param name the address to test * @return the result */ - protected static boolean isIPV4Address( String name ) - { - if ( name.charAt( 0 ) == DOT || name.charAt( name.length() - 1 ) == DOT ) - { + protected static boolean isIPV4Address( final String name ) { + if ( name.charAt( 0 ) == DOT || name.charAt( name.length() - 1 ) == DOT ) { return false; } - int[] addr = new int[] + final int[] addr = new int[] { 0, 0, 0, 0 }; int currentOctet = 0; - for( int i = 0; i < name.length(); i++ ) - { - int ch = name.charAt( i ); - boolean isDigit = ch >= ONE && ch <= NINE; - boolean isDot = ch == DOT; - if ( !isDigit && !isDot ) - { + for( int i = 0; i < name.length(); i++ ) { + final int ch = name.charAt( i ); + final boolean isDigit = ch >= ONE && ch <= NINE; + final boolean isDot = ch == DOT; + if ( !isDigit && !isDot ) { return false; } - if ( isDigit ) - { + if( isDigit ) { addr[currentOctet] = 10 * addr[currentOctet] + ( ch - ONE ); - if ( addr[currentOctet] > 255 ) - { + if ( addr[currentOctet] > 255 ) { return false; } - } - else if ( name.charAt( i - 1 ) == DOT ) - { + } else if( name.charAt( i - 1 ) == DOT ) { return false; - } - else - { + } else { currentOctet++; } } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/plugin/Counter.java b/jspwiki-main/src/main/java/org/apache/wiki/plugin/Counter.java index 8258560..44a8ad7 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/plugin/Counter.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/plugin/Counter.java @@ -18,13 +18,13 @@ */ package org.apache.wiki.plugin; -import java.util.Map; - import org.apache.wiki.WikiContext; import org.apache.wiki.api.exceptions.PluginException; import org.apache.wiki.api.plugin.WikiPlugin; import org.apache.wiki.util.TextUtil; +import java.util.Map; + /** * Provides a page-specific counter, it is reset every time a page is rendered, so it is not usable as a hitcounter. * <br>Stores a variable in the WikiContext called "counter", with the name of the optionally specified variable "name". @@ -39,9 +39,7 @@ import org.apache.wiki.util.TextUtil; * * @since 1.9.30 */ -public class Counter - implements WikiPlugin -{ +public class Counter implements WikiPlugin { // private static Logger log = Logger.getLogger( Counter.class ); /** Parameter name for setting the name. Value is <tt>{@value}</tt>. */ @@ -59,56 +57,32 @@ public class Counter /** * {@inheritDoc} */ - public String execute( WikiContext context, Map<String, String> params ) - throws PluginException - { - // - // First, determine which kind of name we use to store in - // the WikiContext. - // + public String execute( final WikiContext context, final Map< String, String > params ) throws PluginException { + // First, determine which kind of name we use to store in the WikiContext. String countername = params.get( PARAM_NAME); - if( countername == null ) - { + if( countername == null ) { countername = DEFAULT_NAME; - } - else - { + } else { countername = DEFAULT_NAME+"-"+countername; } - // // Fetch the old value - // Integer val = (Integer)context.getVariable( countername ); - - if( val == null ) - { + if( val == null ) { val = 0; } - // // Check if we need to reset this - // - - String start = params.get( PARAM_START ); - - if( start != null ) - { + final String start = params.get( PARAM_START ); + if( start != null ) { val = Integer.parseInt( start ); - } - else - { - // + } else { // Determine how much to increment - // - String incrementObj = params.get( PARAM_INCREMENT ); - + final String incrementObj = params.get( PARAM_INCREMENT ); int increment = DEFAULT_INCREMENT; - - if (incrementObj != null) - { - increment = ( Integer.valueOf( incrementObj ) ).intValue(); + if( incrementObj != null ) { + increment = Integer.parseInt( incrementObj ); } val = val + increment; @@ -116,20 +90,14 @@ public class Counter context.setVariable( countername, val ); - // // check if we want to hide the result (just count, don't show result on the page - // - String showObj = params.get(PARAM_SHOW_RESULT); - + final String showObj = params.get(PARAM_SHOW_RESULT); boolean show = DEFAULT_SHOW_RESULT; - - if( showObj != null ) - { + if( showObj != null ) { show = TextUtil.isPositive( showObj ); } - if( show ) - { + if( show ) { return val.toString(); }
