You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jspwiki.apache.org by ju...@apache.org on 2020/01/28 20:34:11 UTC
[jspwiki] 10/32: apply formatting fixes suggested by intellij
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 c88e155747fd918ed0427741eedc3a82bf107337
Author: juanpablo <ju...@apache.org>
AuthorDate: Sun Jan 19 22:45:22 2020 +0100
apply formatting fixes suggested by intellij
---
.../src/main/java/org/apache/wiki/WikiContext.java | 6 +-
.../java/org/apache/wiki/ui/AbstractCommand.java | 133 +++---
.../src/main/java/org/apache/wiki/ui/Command.java | 121 ++----
.../java/org/apache/wiki/ui/CommandResolver.java | 403 +++++++----------
.../java/org/apache/wiki/ui/EditorManager.java | 160 +++----
.../org/apache/wiki/ui/GenericHTTPHandler.java | 12 +-
.../main/java/org/apache/wiki/ui/GroupCommand.java | 90 ++--
.../java/org/apache/wiki/ui/InputValidator.java | 135 +++---
.../main/java/org/apache/wiki/ui/Installer.java | 180 +++-----
.../main/java/org/apache/wiki/ui/PageCommand.java | 62 ++-
.../java/org/apache/wiki/ui/RedirectCommand.java | 64 ++-
.../java/org/apache/wiki/ui/TemplateManager.java | 478 ++++++++-------------
.../main/java/org/apache/wiki/ui/WikiCommand.java | 70 ++-
.../java/org/apache/wiki/ui/WikiJSPFilter.java | 233 ++++------
.../org/apache/wiki/ui/WikiRequestWrapper.java | 103 ++---
.../java/org/apache/wiki/ui/WikiServletFilter.java | 8 +-
16 files changed, 862 insertions(+), 1396 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 4b9a1d6..150cb6f 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiContext.java
@@ -531,8 +531,7 @@ public class WikiContext implements Cloneable, Command {
* @param page The page to which to link.
* @return An URL to the page. This honours the current absolute/relative setting.
*/
- public String getViewURL( final String page )
- {
+ public String getViewURL( final String page ) {
return getURL( VIEW, page, null );
}
@@ -569,8 +568,7 @@ public class WikiContext implements Cloneable, Command {
*
* @return the command
*/
- public Command getCommand()
- {
+ public Command getCommand() {
return m_command;
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/AbstractCommand.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/AbstractCommand.java
index 6f233fa..777a5ad 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/AbstractCommand.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/AbstractCommand.java
@@ -22,12 +22,12 @@ import org.apache.wiki.util.TextUtil;
/**
- * Abstract, immutable Command implementation class. All of the fields in this
- * class are <code>final</code>. This class is thread-safe.
+ * Abstract, immutable Command implementation class. All of the fields in this class are <code>final</code>. This class is thread-safe.
+ *
* @since 2.4.22
*/
-public abstract class AbstractCommand implements Command
-{
+public abstract class AbstractCommand implements Command {
+
private static final Command[] ALL_COMMANDS = new Command[] {
PageCommand.ATTACH,
PageCommand.COMMENT,
@@ -59,98 +59,68 @@ public abstract class AbstractCommand implements Command
RedirectCommand.REDIRECT
};
- private static final String HTTPS = "HTTPS://";
-
- private static final String HTTP = "HTTP://";
-
- private final String m_jsp;
-
- private final String m_jspFriendlyName;
-
- private final String m_urlPattern;
-
- private final String m_requestContext;
-
- private final String m_contentTemplate;
+ private static final String HTTPS = "HTTPS://";
+ private static final String HTTP = "HTTP://";
- private final Object m_target;
+ private final String m_jsp;
+ private final String m_jspFriendlyName;
+ private final String m_urlPattern;
+ private final String m_requestContext;
+ private final String m_contentTemplate;
+ private final Object m_target;
/**
- * Constructs a new Command with a specified wiki context, URL pattern,
- * content template and target. The URL pattern is used to derive
- * the JSP; if it is a "local" JSP (that is, it does not contain
- * the <code>http://</code> or <code>https://</code> prefixes),
- * then the JSP will be a cleansed version of the URL pattern;
- * symbols (such as <code>%u</code>) will removed. If it the supplied
- * URL pattern points to a non-local destination, the JSP will be set
- * to the value supplied, unmodified.
+ * Constructs a new Command with a specified wiki context, URL pattern, content template and target. The URL pattern is used to derive
+ * the JSP; if it is a "local" JSP (that is, it does not contain the <code>http://</code> or <code>https://</code> prefixes),
+ * then the JSP will be a cleansed version of the URL pattern; symbols (such as <code>%u</code>) will removed. If it the supplied
+ * URL pattern points to a non-local destination, the JSP will be set to the value supplied, unmodified.
+ *
* @param requestContext the request context
* @param urlPattern the URL pattern
* @param contentTemplate the content template; may be <code>null</code>
- * @param target the target of the command, such as a WikiPage; may be
- * <code>null</code>
- * @throws IllegalArgumentException if the request content or URL pattern is
- * <code>null</code>
+ * @param target the target of the command, such as a WikiPage; may be <code>null</code>
+ * @throws IllegalArgumentException if the request content or URL pattern is <code>null</code>
*/
- protected AbstractCommand( String requestContext, String urlPattern, String contentTemplate, Object target )
- {
- if ( requestContext == null || urlPattern == null )
- {
+ protected AbstractCommand( final String requestContext, final String urlPattern, final String contentTemplate, final Object target ) {
+ if( requestContext == null || urlPattern == null ) {
throw new IllegalArgumentException( "Request context, URL pattern and type must not be null." );
}
m_requestContext = requestContext;
-
- if ( urlPattern.toUpperCase().startsWith( HTTP ) ||
- urlPattern.toUpperCase().endsWith( HTTPS ) )
- {
+ if ( urlPattern.toUpperCase().startsWith( HTTP ) || urlPattern.toUpperCase().endsWith( HTTPS ) ) {
// For an HTTP/HTTPS url, pass it through without modification
m_jsp = urlPattern;
m_jspFriendlyName = "Special Page";
- }
- else
- {
- // For local JSPs, take everything to the left of ?, then
- // delete all variable substitutions
+ } else {
+ // For local JSPs, take everything to the left of ?, then delete all variable substitutions
String jsp = urlPattern;
- int qPosition = urlPattern.indexOf( '?' );
- if ( qPosition != -1 )
- {
+ final int qPosition = urlPattern.indexOf( '?' );
+ if ( qPosition != -1 ) {
jsp = jsp.substring( 0, qPosition );
}
m_jsp = removeSubstitutions(jsp);
// Calculate the "friendly name" for the JSP
- if ( m_jsp.toUpperCase().endsWith( ".JSP" ) )
- {
+ if ( m_jsp.toUpperCase().endsWith( ".JSP" ) ) {
m_jspFriendlyName = TextUtil.beautifyString( m_jsp.substring( 0, m_jsp.length() - 4 ) );
- }
- else
- {
+ } else {
m_jspFriendlyName = m_jsp;
}
}
-
m_urlPattern = urlPattern;
-
m_contentTemplate = contentTemplate;
-
m_target = target;
}
//
- // This is just *so* much faster than doing String.replaceAll(). It would, in fact,
- // be worth to cache this value.
+ // This is just *so* much faster than doing String.replaceAll(). It would, in fact, be worth to cache this value.
//
- private String removeSubstitutions(String jsp)
- {
+ private String removeSubstitutions( final String jsp ) {
//return jsp.replaceAll( "\u0025[a-z|A-Z]", "" );
- StringBuilder newjsp = new StringBuilder( jsp.length() );
- for( int i = 0; i < jsp.length(); i++ )
- {
- char c = jsp.charAt(i);
- if( c == '%' && i < jsp.length()-1 && Character.isLetterOrDigit( jsp.charAt(i+1) ) )
- {
+ final StringBuilder newjsp = new StringBuilder( jsp.length() );
+ for( int i = 0; i < jsp.length(); i++ ) {
+ final char c = jsp.charAt(i);
+ if( c == '%' && i < jsp.length() - 1 && Character.isLetterOrDigit( jsp.charAt( i + 1 ) ) ) {
i++;
continue;
}
@@ -160,33 +130,30 @@ public abstract class AbstractCommand implements Command
}
/**
- * Returns a defensively-created array of all
- * static Commands.
+ * Returns a defensively-created array of all static Commands.
+ *
* @return the array of commands
*/
- public static final Command[] allCommands()
- {
+ public static Command[] allCommands() {
return ALL_COMMANDS.clone();
}
/**
* @see org.apache.wiki.ui.Command#targetedCommand(Object)
*/
- public abstract Command targetedCommand( Object target );
+ public abstract Command targetedCommand( final Object target );
/**
* @see org.apache.wiki.ui.Command#getContentTemplate()
*/
- public final String getContentTemplate()
- {
+ public final String getContentTemplate() {
return m_contentTemplate;
}
/**
* @see org.apache.wiki.ui.Command#getJSP()
*/
- public final String getJSP()
- {
+ public final String getJSP() {
return m_jsp;
}
@@ -198,43 +165,39 @@ public abstract class AbstractCommand implements Command
/**
* @see org.apache.wiki.ui.Command#getRequestContext()
*/
- public final String getRequestContext()
- {
+ public final String getRequestContext() {
return m_requestContext;
}
/**
* @see org.apache.wiki.ui.Command#getTarget()
*/
- public final Object getTarget()
- {
+ public final Object getTarget() {
return m_target;
}
/**
* @see org.apache.wiki.ui.Command#getURLPattern()
*/
- public final String getURLPattern()
- {
+ public final String getURLPattern() {
return m_urlPattern;
}
/**
- * Returns the "friendly name" for this command's JSP, namely
- * a beatified version of the JSP's name without the .jsp suffix.
+ * Returns the "friendly name" for this command's JSP, namely a beatified version of the JSP's name without the .jsp suffix.
+ *
* @return the friendly name
*/
- protected final String getJSPFriendlyName()
- {
+ protected final String getJSPFriendlyName() {
return m_jspFriendlyName;
}
/**
* Returns a String representation of the Command.
+ *
* @see java.lang.Object#toString()
*/
- public final String toString()
- {
+ public final String toString() {
return "Command" +
"[context=" + m_requestContext + "," +
"urlPattern=" + m_urlPattern + "," +
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/Command.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/Command.java
index 032d643..5a40e6a 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/Command.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/Command.java
@@ -21,39 +21,23 @@ package org.apache.wiki.ui;
import java.security.Permission;
/**
- * <p>
- * Represents a logical "unit of work" that includes a request context, JSP,
- * URLPattern, content template and (optionally) a target and required security
- * permission. Examples of Commands include "view a page," "create a group," and
- * "edit user preferences."
- * </p>
- * <p>
- * Commands come in two flavors: "static" and "targeted."
- * </p>
+ * <p>Represents a logical "unit of work" that includes a request context, JSP, URLPattern, content template and (optionally) a target and
+ * required security permission. Examples of Commands include "view a page," "create a group," and "edit user preferences." </p>
+ * <p> Commands come in two flavors: "static" and "targeted." </p>
* <ul>
- * <li><strong>Static commands</strong> are exactly what they sound like:
- * static. They are <code>final</code>, threadsafe, and immutable. They have
- * no intrinsic idea of the context they are acting in. For example, the static
- * command {@link PageCommand#VIEW} embodies the idea of viewing a page —
- * but exactly <em>which</em> page is left undefined. Static commands exist so
- * that they can be freely shared and passed around without incurring the
- * penalties of object creation. Static commands are a lot like naked request
- * contexts ("edit", "view", etc.) except that they include additional,
- * essential properites such as the associated URL pattern and content JSP.</li>
- * <li><strong>Targeted commands</strong> "decorate" static commands by
- * scoping a static Command at a specific target such as a WikiPage or
- * GroupPrincipal. Targeted commands are created by calling an existing
- * Command's {@link #targetedCommand(Object)} and supplying the target object.
- * Implementing classes generally require a specific target type. For example,
- * the {@link PageCommand} class requires that the target object be of type
- * {@link org.apache.wiki.WikiPage}.</li>
+ * <li><strong>Static commands</strong> are exactly what they sound like: static. They are <code>final</code>, threadsafe, and immutable.
+ * They have no intrinsic idea of the context they are acting in. For example, the static command {@link PageCommand#VIEW} embodies the
+ * idea of viewing a page — but exactly <em>which</em> page is left undefined. Static commands exist so that they can be freely
+ * shared and passed around without incurring the penalties of object creation. Static commands are a lot like naked request contexts
+ * ("edit", "view", etc.) except that they include additional, essential properties such as the associated URL pattern and content JSP.</li>
+ * <li><strong>Targeted commands</strong> "decorate" static commands by scoping a static Command at a specific target such as a WikiPage or
+ * GroupPrincipal. Targeted commands are created by calling an existing Command's {@link #targetedCommand(Object)} and supplying the target
+ * object. Implementing classes generally require a specific target type. For example, the {@link PageCommand} class requires that the
+ * target object be of type {@link org.apache.wiki.WikiPage}.</li>
* </ul>
- * <p>
- * Concrete implementations of Command include:
- * </p>
+ * <p> Concrete implementations of Command include: </p>
* <ul>
- * <li><strong>PageCommand</strong>: commands for editing, renaming, and
- * viewing pages</li>
+ * <li><strong>PageCommand</strong>: commands for editing, renaming, and viewing pages</li>
* <li><strong>GroupCommand</strong>: commands for viewing, editing and
* deleting wiki groups</li>
* <li><strong>WikiCommand</strong>: commands for wiki-wide operations such as
@@ -62,30 +46,21 @@ import java.security.Permission;
* special pages</li>
* </ul>
* <p>
- * For a given targeted Command, its {@link #getTarget()} method will return a
- * non-<code>null</code> value. In addition, its
- * {@link #requiredPermission()} method will generally also return a non-<code>null</code>
- * value. It is each implementation's responsibility to construct and store the
- * correct Permission for a given Command and Target. For example, when
- * PageCommand.VIEW is targeted at the WikiPage <code>Main</code>, the
- * Command's associated permission is
- * <code>PagePermission "<em>theWiki</em>:Main", "view".</code>
- * </p>
- * <p>
- * Static Commands, and targeted Commands that do not require specific
- * permissions to execute, return a <code>null</code> result for
- * {@link #requiredPermission()}.
- * </p>
+ * For a given targeted Command, its {@link #getTarget()} method will return a non-<code>null</code> value. In addition, its
+ * {@link #requiredPermission()} method will generally also return a non-<code>null</code> value. It is each implementation's responsibility
+ * to construct and store the correct Permission for a given Command and Target. For example, when PageCommand.VIEW is targeted at the
+ * WikiPage <code>Main</code>, the Command's associated permission is <code>PagePermission "<em>theWiki</em>:Main", "view".</code></p>
+ * <p>Static Commands, and targeted Commands that do not require specific permissions to execute, return a <code>null</code> result for
+ * {@link #requiredPermission()}.</p>
* @since 2.4.22
*/
-public interface Command
-{
+public interface Command {
+
/**
- * Creates and returns a targeted Command by combining a target, such as a
- * WikiPage or GroupPrincipal into the existing Command. Subclasses should
- * check to make sure the supplied <code>target</code> object is of the
- * correct type. This method is guaranteed to return a non-<code>null</code>
- * Command (unless the target is an incorrect type).
+ * Creates and returns a targeted Command by combining a target, such as a WikiPage or GroupPrincipal into the existing Command.
+ * Subclasses should check to make sure the supplied <code>target</code> object is of the correct type. This method is guaranteed
+ * to return a non-<code>null</code> Command (unless the target is an incorrect type).
+ *
* @param target the object to combine, such as a GroupPrincipal or WikiPage
* @return the new, targeted Command
* @throws IllegalArgumentException if the target is not of the correct type
@@ -93,65 +68,59 @@ public interface Command
Command targetedCommand( Object target );
/**
- * Returns the content template associated with a Command, such as
- * <code>PreferencesContent.jsp</code>. For Commands that are not
- * page-related, this method will always return <code>null</code>.
- * <em>Calling methods should always check to see if the result
+ * Returns the content template associated with a Command, such as <code>PreferencesContent.jsp</code>. For Commands that are not
+ * page-related, this method will always return <code>null</code>. <em>Calling methods should always check to see if the result
* of this method is <code>null</code></em>.
+ *
* @return the content template
*/
String getContentTemplate();
/**
- * Returns the JSP associated with the Command. The JSP is
- * a "local" JSP within the JSPWiki webapp; it is not
- * a general HTTP URL. If it exists, the JSP will be expressed
- * relative to the webapp root, without a leading slash.
- * This method is guaranteed to return a non-<code>null</code>
- * result, although in some cases the result may be an empty string.
+ * Returns the JSP associated with the Command. The JSP is a "local" JSP within the JSPWiki webapp; it is not a general HTTP URL.
+ * If it exists, the JSP will be expressed relative to the webapp root, without a leading slash. This method is guaranteed to return
+ * a non-<code>null</code> result, although in some cases the result may be an empty string.
+ *
* @return the JSP or url associated with the wiki command
*/
String getJSP();
/**
* Returns the human-friendly name for this command.
+ *
* @return the name
*/
String getName();
/**
- * Returns the request context associated with this Command. This method is
- * guaranteed to return a non-<code>null</code> String.
+ * Returns the request context associated with this Command. This method is guaranteed to return a non-<code>null</code> String.
* @return the request context
*/
String getRequestContext();
/**
- * Returns the Permission required to successfully execute this Command. If
- * no Permission is requred, this method returns <code>null</code>. For
- * example, the static command {@link PageCommand#VIEW} doesn't require a
- * permission because it isn't referring to a particular WikiPage. However,
- * if this command targets a WikiPage called <code>Main</code>(via
- * {@link PageCommand#targetedCommand(Object)}, the resulting Command
- * would require the permission
+ * Returns the Permission required to successfully execute this Command. If no Permission is requred, this method returns
+ * <code>null</code>. For example, the static command {@link PageCommand#VIEW} doesn't require a permission because it isn't referring
+ * to a particular WikiPage. However, if this command targets a WikiPage called <code>Main</code>(via
+ * {@link PageCommand#targetedCommand(Object)}, the resulting Command would require the permission
* <code>PagePermission "<em>yourWiki</em>:Main", "view"</code>.
+ *
* @return the required permission, or <code>null</code> if not required
*/
Permission requiredPermission();
/**
- * Returns the target associated with a Command, if it was created with one.
- * Commands created with {@link #targetedCommand(Object)} will
- * <em>always</em> return a non-<code>null</code> object. <em>Calling
- * methods should always check to see if the result of this method
+ * Returns the target associated with a Command, if it was created with one. Commands created with {@link #targetedCommand(Object)} will
+ * <em>always</em> return a non-<code>null</code> object. <em>Calling methods should always check to see if the result of this method
* is <code>null</code></em>.
+ *
* @return the wiki page
*/
Object getTarget();
/**
- * Returns the URL pattern associated with this Command. This method is
- * guaranteed to return a non-<code>null</code> String.
+ * Returns the URL pattern associated with this Command. This method is guaranteed to return a non-<code>null</code> String.
+ *
* @return the URL pattern
*/
String getURLPattern();
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/CommandResolver.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/CommandResolver.java
index 5c7af48..64f965e 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/CommandResolver.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/CommandResolver.java
@@ -31,104 +31,82 @@ import org.apache.wiki.util.TextUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
- * <p>Resolves special pages, JSPs and Commands on behalf of a
- * WikiEngine. CommandResolver will automatically resolve page names
- * with singular/plural variants. It can also detect the correct Command
- * based on parameters supplied in an HTTP request, or due to the
+ * <p>Resolves special pages, JSPs and Commands on behalf of a WikiEngine. CommandResolver will automatically resolve page names
+ * with singular/plural variants. It can also detect the correct Command based on parameters supplied in an HTTP request, or due to the
* JSP being accessed.</p>
* <p>
- * <p>CommandResolver's static {@link #findCommand(String)} method is
- * the simplest method; it looks up and returns the Command matching
- * a supplied wiki context. For example, looking up the request context
- * <code>view</code> returns {@link PageCommand#VIEW}. Use this method
- * to obtain static Command instances that aren't targeted at a particular
- * page or group.</p>
- * <p>For more complex lookups in which the caller supplies an HTTP
- * request, {@link #findCommand(HttpServletRequest, String)} will
- * look up and return the correct Command. The String parameter
- * <code>defaultContext</code> supplies the request context to use
- * if it cannot be detected. However, note that the default wiki
- * context may be over-ridden if the request was for a "special page."</p>
- * <p>For example, suppose the WikiEngine's properties specify a
- * special page called <code>UserPrefs</code>
- * that redirects to <code>UserPreferences.jsp</code>. The ordinary
- * lookup method {@linkplain #findCommand(String)} using a supplied
- * context <code>view</code> would return {@link PageCommand#VIEW}. But
- * the {@linkplain #findCommand(HttpServletRequest, String)} method,
- * when passed the same context (<code>view</code>) and an HTTP request
- * containing the page parameter value <code>UserPrefs</code>,
- * will instead return {@link WikiCommand#PREFS}.</p>
+ * <p>CommandResolver's static {@link #findCommand(String)} method is the simplest method; it looks up and returns the Command matching
+ * a supplied wiki context. For example, looking up the request context <code>view</code> returns {@link PageCommand#VIEW}. Use this method
+ * to obtain static Command instances that aren't targeted at a particular page or group.</p>
+ * <p>For more complex lookups in which the caller supplies an HTTP request, {@link #findCommand(HttpServletRequest, String)} will
+ * look up and return the correct Command. The String parameter <code>defaultContext</code> supplies the request context to use
+ * if it cannot be detected. However, note that the default wiki context may be overridden if the request was for a "special page."</p>
+ * <p>For example, suppose the WikiEngine's properties specify a special page called <code>UserPrefs</code> that redirects to
+ * <code>UserPreferences.jsp</code>. The ordinary lookup method {@linkplain #findCommand(String)} using a supplied context <code>view</code>
+ * would return {@link PageCommand#VIEW}. But the {@linkplain #findCommand(HttpServletRequest, String)} method, when passed the same context
+ * (<code>view</code>) and an HTTP request containing the page parameter value <code>UserPrefs</code>, will instead return
+ * {@link WikiCommand#PREFS}.</p>
+ *
* @since 2.4.22
*/
-public final class CommandResolver
-{
+public final class CommandResolver {
/** Prefix in jspwiki.properties signifying special page keys. */
private static final String PROP_SPECIALPAGE = "jspwiki.specialPage.";
/** Private map with request contexts as keys, Commands as values */
- private static final Map<String, Command> CONTEXTS;
+ private static final Map< String, Command > CONTEXTS;
/** Private map with JSPs as keys, Commands as values */
- private static final Map<String, Command> JSPS;
-
- /** Store the JSP-to-Command and context-to-Command mappings */
- static
- {
- CONTEXTS = new HashMap<String, Command>();
- JSPS = new HashMap<String, Command>();
- Command[] commands = AbstractCommand.allCommands();
- for( int i = 0; i < commands.length; i++ )
- {
- JSPS.put( commands[i].getJSP(), commands[i] );
- CONTEXTS.put( commands[i].getRequestContext(), commands[i] );
+ private static final Map< String, Command > JSPS;
+
+ /* Store the JSP-to-Command and context-to-Command mappings */
+ static {
+ CONTEXTS = new HashMap<>();
+ JSPS = new HashMap<>();
+ final Command[] commands = AbstractCommand.allCommands();
+ for( final Command command : commands ) {
+ JSPS.put( command.getJSP(), command );
+ CONTEXTS.put( command.getRequestContext(), command );
}
}
- private final Logger m_log = Logger.getLogger( CommandResolver.class );
+ private static final Logger LOG = Logger.getLogger( CommandResolver.class );
- private final WikiEngine m_engine;
+ private final WikiEngine m_engine;
/** If true, we'll also consider english plurals (+s) a match. */
- private final boolean m_matchEnglishPlurals;
+ private final boolean m_matchEnglishPlurals;
/** Stores special page names as keys, and Commands as values. */
private final Map<String, Command> m_specialPages;
/**
- * Constructs a CommandResolver for a given WikiEngine. This constructor
- * will extract the special page references for this wiki and store them in
- * a cache used for resolution.
+ * Constructs a CommandResolver for a given WikiEngine. This constructor will extract the special page references for this wiki and
+ * store them in a cache used for resolution.
+ *
* @param engine the wiki engine
* @param properties the properties used to initialize the wiki
*/
- public CommandResolver( WikiEngine engine, Properties properties )
- {
+ public CommandResolver( final WikiEngine engine, final Properties properties ) {
m_engine = engine;
- m_specialPages = new HashMap<String, Command>();
-
- // Skim through the properties and look for anything with
- // the "special page" prefix. Create maps that allow us
- // look up the correct Command based on special page name.
- // If a matching command isn't found, create a RedirectCommand.
- for(String key : properties.stringPropertyNames())
- {
- if ( key.startsWith( PROP_SPECIALPAGE ) )
- {
+ m_specialPages = new HashMap<>();
+
+ // Skim through the properties and look for anything with the "special page" prefix. Create maps that allow us look up
+ // the correct Command based on special page name. If a matching command isn't found, create a RedirectCommand.
+ for( final String key : properties.stringPropertyNames() ) {
+ if ( key.startsWith( PROP_SPECIALPAGE ) ) {
String specialPage = key.substring( PROP_SPECIALPAGE.length() );
- String jsp = (String) properties.getProperty(key);
- if ( specialPage != null && jsp != null )
- {
+ String jsp = properties.getProperty( key );
+ if ( jsp != null ) {
specialPage = specialPage.trim();
jsp = jsp.trim();
Command command = JSPS.get( jsp );
- if ( command == null )
- {
- Command redirect = RedirectCommand.REDIRECT;
+ if ( command == null ) {
+ final Command redirect = RedirectCommand.REDIRECT;
command = redirect.targetedCommand( jsp );
}
m_specialPages.put( specialPage, command );
@@ -141,61 +119,42 @@ public final class CommandResolver
}
/**
- * Attempts to locate a wiki command for a supplied request context.
- * The resolution technique is simple: we examine the list of
- * Commands returned by {@link AbstractCommand#allCommands()} and
- * return the one whose <code>requestContext</code> matches the
- * supplied context. If the supplied context does not resolve to a known
- * Command, this method throws an {@link IllegalArgumentException}.
+ * Attempts to locate a wiki command for a supplied request context. The resolution technique is simple: we examine the list of
+ * Commands returned by {@link AbstractCommand#allCommands()} and return the one whose <code>requestContext</code> matches the
+ * supplied context. If the supplied context does not resolve to a known Command, this method throws an {@link IllegalArgumentException}.
+ *
* @param context the request context
* @return the resolved context
*/
- public static Command findCommand( String context )
- {
- Command command = CONTEXTS.get( context );
- if ( command == null )
- {
+ public static Command findCommand( final String context ) {
+ final Command command = CONTEXTS.get( context );
+ if ( command == null ) {
throw new IllegalArgumentException( "Unsupported wiki context: " + context + "." );
}
return command;
}
/**
- * <p>
- * Attempts to locate a Command for a supplied wiki context and HTTP
- * request, incorporating the correct WikiPage into the command if reqiured.
- * This method will first determine what page the user requested by
- * delegating to {@link #extractPageFromParameter(String, HttpServletRequest)}. If
- * this page equates to a special page, we return the Command
- * corresponding to that page. Otherwise, this method simply returns the
- * Command for the supplied request context.
- * </p>
- * <p>
- * The reason this method attempts to resolve against special pages is
- * because some of them resolve to contexts that may be different from the
- * one supplied. For example, a VIEW request context for the special page
- * "UserPreferences" should return a PREFS context instead.
- * </p>
- * <p>
- * When the caller supplies a request context and HTTP request that
- * specifies an actual wiki page (rather than a special page), this method
- * will return a "targeted" Command that includes the resolved WikiPage
- * as the target. (See {@link #resolvePage(HttpServletRequest, String)}
- * for the resolution algorithm). Specifically, the Command will
- * return a non-<code>null</code> value for its {@link AbstractCommand#getTarget()} method.
- * </p>
- * <p><em>Note: if this method determines that the Command is the VIEW PageCommand,
- * then the Command returned will always be targeted to the front page.</em></p>
- * @param request the HTTP request; if <code>null</code>, delegates
- * to {@link #findCommand(String)}
+ * <p>Attempts to locate a Command for a supplied wiki context and HTTP request, incorporating the correct WikiPage into the command
+ * if required. This method will first determine what page the user requested by delegating to {@link #extractPageFromParameter(String, HttpServletRequest)}.
+ * If this page equates to a special page, we return the Command corresponding to that page. Otherwise, this method simply returns the
+ * Command for the supplied request context.</p>
+ * <p>The reason this method attempts to resolve against special pages is because some of them resolve to contexts that may be different
+ * from the one supplied. For example, a VIEW request context for the special page "UserPreferences" should return a PREFS context instead.</p>
+ * <p>When the caller supplies a request context and HTTP request that specifies an actual wiki page (rather than a special page),
+ * this method will return a "targeted" Command that includes the resolved WikiPage as the target. (See {@link #resolvePage(HttpServletRequest, String)}
+ * for the resolution algorithm). Specifically, the Command will return a non-<code>null</code> value for
+ * its {@link AbstractCommand#getTarget()} method.</p>
+ * <p><em>Note: if this method determines that the Command is the VIEW PageCommand, then the Command returned will always be targeted to
+ * the front page.</em></p>
+ *
+ * @param request the HTTP request; if <code>null</code>, delegates to {@link #findCommand(String)}
* @param defaultContext the request context to use by default
* @return the resolved wiki command
*/
- public Command findCommand( HttpServletRequest request, String defaultContext )
- {
+ public Command findCommand( final HttpServletRequest request, final String defaultContext ) {
// Corner case if request is null
- if ( request == null )
- {
+ if ( request == null ) {
return findCommand( defaultContext );
}
@@ -205,62 +164,49 @@ public final class CommandResolver
String pageName = extractPageFromParameter( defaultContext, request );
// Can we find a special-page command matching the extracted page?
- if ( pageName != null )
- {
+ if ( pageName != null ) {
command = m_specialPages.get( pageName );
}
- // If we haven't found a matching command yet, extract the JSP path
- // and compare to our list of special pages
- if ( command == null )
- {
+ // If we haven't found a matching command yet, extract the JSP path and compare to our list of special pages
+ if ( command == null ) {
command = extractCommandFromPath( request );
// Otherwise: use the default context
- if ( command == null )
- {
+ if ( command == null ) {
command = CONTEXTS.get( defaultContext );
- if ( command == null )
- {
+ if ( command == null ) {
throw new IllegalArgumentException( "Wiki context " + defaultContext + " is illegal." );
}
}
}
// For PageCommand.VIEW, default to front page if a page wasn't supplied
- if( PageCommand.VIEW.equals( command ) && pageName == null )
- {
+ if( PageCommand.VIEW.equals( command ) && pageName == null ) {
pageName = m_engine.getFrontPage();
}
// These next blocks handle targeting requirements
// If we were passed a page parameter, try to resolve it
- if ( command instanceof PageCommand && pageName != null )
- {
+ if ( command instanceof PageCommand && pageName != null ) {
// If there's a matching WikiPage, "wrap" the command
- WikiPage page = resolvePage( request, pageName );
- if ( page != null )
- {
- return command.targetedCommand( page );
- }
+ final WikiPage page = resolvePage( request, pageName );
+ return command.targetedCommand( page );
}
// If "create group" command, target this wiki
- String wiki = m_engine.getApplicationName();
- if ( WikiCommand.CREATE_GROUP.equals( command ) )
- {
+ final String wiki = m_engine.getApplicationName();
+ if ( WikiCommand.CREATE_GROUP.equals( command ) ) {
return WikiCommand.CREATE_GROUP.targetedCommand( wiki );
}
// If group command, see if we were passed a group name
- if ( command instanceof GroupCommand )
- {
+ if( command instanceof GroupCommand ) {
String groupName = request.getParameter( "group" );
groupName = TextUtil.replaceEntities( groupName );
- if ( groupName != null && groupName.length() > 0 )
- {
- GroupPrincipal group = new GroupPrincipal( groupName );
+ if ( groupName != null && groupName.length() > 0 ) {
+ final GroupPrincipal group = new GroupPrincipal( groupName );
return command.targetedCommand( group );
}
}
@@ -270,59 +216,40 @@ public final class CommandResolver
}
/**
- * <p>
- * Returns the correct page name, or <code>null</code>, if no such page can be found.
- * Aliases are considered.
- * </p>
- * <p>
- * In some cases, page names can refer to other pages. For example, when you
- * have matchEnglishPlurals set, then a page name "Foobars" will be
- * transformed into "Foobar", should a page "Foobars" not exist, but the
- * page "Foobar" would. This method gives you the correct page name to refer
- * to.
- * </p>
- * <p>
- * This facility can also be used to rewrite any page name, for example, by
- * using aliases. It can also be used to check the existence of any page.
- * </p>
+ * <p>Returns the correct page name, or <code>null</code>, if no such page can be found. Aliases are considered.</p>
+ * <p>In some cases, page names can refer to other pages. For example, when you have matchEnglishPlurals set, then a page name
+ * "Foobars" will be transformed into "Foobar", should a page "Foobars" not exist, but the page "Foobar" would. This method gives
+ * you the correct page name to refer to. </p>
+ * <p>This facility can also be used to rewrite any page name, for example, by using aliases. It can also be used to check the
+ * existence of any page.</p>
+ *
* @since 2.4.20
* @param page the page name.
* @return The rewritten page name, or <code>null</code>, if the page does not exist.
- * @throws ProviderException if the underlyng page provider that locates pages
- * throws an exception
+ * @throws ProviderException if the underlyng page provider that locates pages throws an exception
*/
- public String getFinalPageName( String page ) throws ProviderException
- {
+ public String getFinalPageName( final String page ) throws ProviderException {
boolean isThere = simplePageExists( page );
String finalName = page;
- if ( !isThere && m_matchEnglishPlurals )
- {
- if ( page.endsWith( "s" ) )
- {
+ if ( !isThere && m_matchEnglishPlurals ) {
+ if ( page.endsWith( "s" ) ) {
finalName = page.substring( 0, page.length() - 1 );
- }
- else
- {
+ } else {
finalName += "s";
}
isThere = simplePageExists( finalName );
}
- if( !isThere )
- {
+ if( !isThere ) {
finalName = MarkupParser.wikifyLink( page );
isThere = simplePageExists(finalName);
- if( !isThere && m_matchEnglishPlurals )
- {
- if( finalName.endsWith( "s" ) )
- {
+ if( !isThere && m_matchEnglishPlurals ) {
+ if( finalName.endsWith( "s" ) ) {
finalName = finalName.substring( 0, finalName.length() - 1 );
- }
- else
- {
+ } else {
finalName += "s";
}
@@ -334,74 +261,56 @@ public final class CommandResolver
}
/**
- * <p>
- * If the page is a special page, this method returns a direct URL to that
- * page; otherwise, it returns <code>null</code>.
- * </p>
- * <p>
- * Special pages are non-existant references to other pages. For example,
- * you could define a special page reference "RecentChanges" which would
- * always be redirected to "RecentChanges.jsp" instead of trying to find a
- * Wiki page called "RecentChanges".
- * </p>
+ * <p>If the page is a special page, this method returns a direct URL to that page; otherwise, it returns <code>null</code>.</p>
+ * <p>Special pages are non-existant references to other pages. For example, you could define a special page reference "RecentChanges"
+ * which would always be redirected to "RecentChanges.jsp" instead of trying to find a Wiki page called "RecentChanges".</p>
+ *
* @param page the page name ro search for
* @return the URL of the special page, if the supplied page is one, or <code>null</code>
*/
- public String getSpecialPageReference( String page )
- {
- Command command = m_specialPages.get( page );
-
- if ( command != null )
- {
+ public String getSpecialPageReference( final String page ) {
+ final Command command = m_specialPages.get( page );
+ if ( command != null ) {
return m_engine.getURLConstructor()
- .makeURL( command.getRequestContext(), command.getURLPattern(), true, null );
+ .makeURL( command.getRequestContext(), command.getURLPattern(), true, null );
}
return null;
}
/**
- * Extracts a Command based on the JSP path of an HTTP request.
- * If the JSP requested matches a Command's <code>getJSP()</code>
+ * Extracts a Command based on the JSP path of an HTTP request. If the JSP requested matches a Command's <code>getJSP()</code>
* value, that Command is returned.
+ *
* @param request the HTTP request
* @return the resolved Command, or <code>null</code> if not found
*/
- protected Command extractCommandFromPath( HttpServletRequest request )
- {
+ protected Command extractCommandFromPath( final HttpServletRequest request ) {
String jsp = request.getServletPath();
// Take everything to right of initial / and left of # or ?
- int hashMark = jsp.indexOf( '#' );
- if ( hashMark != -1 )
- {
+ final int hashMark = jsp.indexOf( '#' );
+ if ( hashMark != -1 ) {
jsp = jsp.substring( 0, hashMark );
}
- int questionMark = jsp.indexOf( '?' );
- if ( questionMark != -1 )
- {
+ final int questionMark = jsp.indexOf( '?' );
+ if ( questionMark != -1 ) {
jsp = jsp.substring( 0, questionMark );
}
- if ( jsp.startsWith( "/" ) )
- {
+ if ( jsp.startsWith( "/" ) ) {
jsp = jsp.substring( 1 );
}
// Find special page reference?
- for( Iterator< Map.Entry< String, Command > > i = m_specialPages.entrySet().iterator(); i.hasNext(); )
- {
- Map.Entry< String, Command > entry = i.next();
- Command specialCommand = entry.getValue();
- if ( specialCommand.getJSP().equals( jsp ) )
- {
+ for( final Map.Entry< String, Command > entry : m_specialPages.entrySet() ) {
+ final Command specialCommand = entry.getValue();
+ if( specialCommand.getJSP().equals( jsp ) ) {
return specialCommand;
}
}
- // Still haven't found a matching command?
- // Ok, see if we match against our standard list of JSPs
- if ( jsp.length() > 0 && JSPS.containsKey( jsp ) )
- {
+ // Still haven't found a matching command? Ok, see if we match against our standard list of JSPs
+ if ( jsp.length() > 0 && JSPS.containsKey( jsp ) ) {
return JSPS.get( jsp );
}
@@ -409,35 +318,27 @@ public final class CommandResolver
}
/**
- * Determines the correct wiki page based on a supplied request context and
- * HTTP request. This method attempts to determine the page requested by a
- * user, taking into acccount special pages. The resolution algorithm will:
+ * Determines the correct wiki page based on a supplied request context and HTTP request. This method attempts to determine the page
+ * requested by a user, taking into acccount special pages. The resolution algorithm will:
* <ul>
- * <li>Extract the page name from the URL according to the rules for the
- * current {@link org.apache.wiki.url.URLConstructor}. If a page name was
- * passed in the request, return the correct name after taking into account
- * potential plural matches.</li>
- * <li>If the extracted page name is <code>null</code>, attempt to see
- * if a "special page" was intended by examining the servlet path. For
- * example, the request path "/UserPreferences.jsp" will resolve to
- * "UserPreferences."</li>
- * <li>If neither of these methods work, this method returns
- * <code>null</code></li>
+ * <li>Extract the page name from the URL according to the rules for the current {@link org.apache.wiki.url.URLConstructor}. If a
+ * page name was passed in the request, return the correct name after taking into account potential plural matches.</li>
+ * <li>If the extracted page name is <code>null</code>, attempt to see if a "special page" was intended by examining the servlet path.
+ * For example, the request path "/UserPreferences.jsp" will resolve to "UserPreferences."</li>
+ * <li>If neither of these methods work, this method returns <code>null</code></li>
* </ul>
+ *
* @param requestContext the request context
* @param request the HTTP request
* @return the resolved page name
*/
protected String extractPageFromParameter( final String requestContext, final HttpServletRequest request ) {
- String page;
-
// Extract the page name from the URL directly
try {
- page = m_engine.getURLConstructor().parsePage( requestContext, request, m_engine.getContentEncoding() );
+ String page = m_engine.getURLConstructor().parsePage( requestContext, request, m_engine.getContentEncoding() );
if ( page != null ) {
try {
- // Look for singular/plural variants; if one
- // not found, take the one the user supplied
+ // Look for singular/plural variants; if one not found, take the one the user supplied
final String finalPage = getFinalPageName( page );
if ( finalPage != null ) {
page = finalPage;
@@ -448,8 +349,8 @@ public final class CommandResolver
return page;
}
} catch( final IOException e ) {
- m_log.error( "Unable to create context", e );
- throw new InternalWikiException( "Big internal booboo, please check logs." , e);
+ LOG.error( "Unable to create context", e );
+ throw new InternalWikiException( "Big internal booboo, please check logs." , e );
}
// Didn't resolve; return null
@@ -457,39 +358,28 @@ public final class CommandResolver
}
/**
- * Looks up and returns the correct, versioned WikiPage based on a supplied
- * page name and optional <code>version</code> parameter passed in an HTTP
- * request. If the <code>version</code> parameter does not exist in the
- * request, the latest version is returned.
+ * Looks up and returns the correct, versioned WikiPage based on a supplied page name and optional <code>version</code> parameter
+ * passed in an HTTP request. If the <code>version</code> parameter does not exist in the request, the latest version is returned.
+ *
* @param request the HTTP request
* @param page the name of the page to look up; this page <em>must</em> exist
* @return the wiki page
*/
- protected WikiPage resolvePage( HttpServletRequest request, String page )
- {
+ protected WikiPage resolvePage( final HttpServletRequest request, String page ) {
// See if the user included a version parameter
- WikiPage wikipage;
int version = WikiProvider.LATEST_VERSION;
- String rev = request.getParameter( "version" );
-
- if ( rev != null )
- {
- try
- {
+ final String rev = request.getParameter( "version" );
+ if ( rev != null ) {
+ try {
version = Integer.parseInt( rev );
- }
- catch( NumberFormatException e )
- {
- // This happens a lot with bots or other guys who are trying
- // to test if we are vulnerable to e.g. XSS attacks. We catch
+ } catch( final NumberFormatException e ) {
+ // This happens a lot with bots or other guys who are trying to test if we are vulnerable to e.g. XSS attacks. We catch
// it here so that the admin does not get tons of mail.
}
}
- wikipage = m_engine.getPageManager().getPage( page, version );
-
- if ( wikipage == null )
- {
+ WikiPage wikipage = m_engine.getPageManager().getPage( page, version );
+ if ( wikipage == null ) {
page = MarkupParser.cleanLink( page );
wikipage = new WikiPage( m_engine, page );
}
@@ -497,18 +387,15 @@ public final class CommandResolver
}
/**
- * Determines whether a "page" exists by examining the list of special pages
- * and querying the page manager.
+ * Determines whether a "page" exists by examining the list of special pages and querying the page manager.
+ *
* @param page the page to seek
- * @return <code>true</code> if the page exists, <code>false</code>
- * otherwise
+ * @return <code>true</code> if the page exists, <code>false</code> otherwise
* @throws ProviderException if the underlyng page provider that locates pages
* throws an exception
*/
- protected boolean simplePageExists( String page ) throws ProviderException
- {
- if ( m_specialPages.containsKey( page ) )
- {
+ protected boolean simplePageExists( final String page ) throws ProviderException {
+ if ( m_specialPages.containsKey( page ) ) {
return true;
}
return m_engine.getPageManager().pageExists( page );
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/EditorManager.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/EditorManager.java
index c66e810..217c1bd 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/EditorManager.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/EditorManager.java
@@ -31,7 +31,6 @@ import org.jdom2.Element;
import javax.servlet.jsp.PageContext;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -60,32 +59,30 @@ import java.util.Set;
*/
public class EditorManager extends ModuleManager {
- /** The property name for setting the editor. Current value is "jspwiki.editor" */
- /* not used anymore -- replaced by defaultpref.template.editor */
- public static final String PROP_EDITORTYPE = "jspwiki.editor";
+ /** The property name for setting the editor. Current value is "jspwiki.editor" - not used anymore: replaced by defaultpref.template.editor */
+ public static final String PROP_EDITORTYPE = "jspwiki.editor";
/** Parameter for changing editors at run-time */
- public static final String PARA_EDITOR = "editor";
+ public static final String PARA_EDITOR = "editor";
/** Known name for the plain wikimarkup editor. */
- public static final String EDITOR_PLAIN = "plain";
+ public static final String EDITOR_PLAIN = "plain";
/** Known name for the preview editor component. */
- public static final String EDITOR_PREVIEW = "preview";
+ public static final String EDITOR_PREVIEW = "preview";
/** Known attribute name for storing the user edited text inside a HTTP parameter. */
- public static final String REQ_EDITEDTEXT = "_editedtext";
+ public static final String REQ_EDITEDTEXT = "_editedtext";
/** Known attribute name for storing the user edited text inside a session or a page context */
- public static final String ATTR_EDITEDTEXT = REQ_EDITEDTEXT;
+ public static final String ATTR_EDITEDTEXT = REQ_EDITEDTEXT;
- private Map<String, WikiEditorInfo> m_editors;
+ private Map< String, WikiEditorInfo > m_editors;
- private static Logger log = Logger.getLogger( EditorManager.class );
+ private static final Logger log = Logger.getLogger( EditorManager.class );
- public EditorManager( WikiEngine engine )
- {
- super(engine);
+ public EditorManager( final WikiEngine engine ) {
+ super( engine );
}
/**
@@ -93,8 +90,7 @@ public class EditorManager extends ModuleManager {
*
* @param props Properties for setup.
*/
- public void initialize( Properties props )
- {
+ public void initialize( final Properties props ) {
registerEditors();
}
@@ -112,14 +108,12 @@ public class EditorManager extends ModuleManager {
//
// Get all resources of all modules
//
- List< Element > editors = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/editor" );
+ final List< Element > editors = XmlUtil.parse( PLUGIN_RESOURCE_LOCATION, "/modules/editor" );
+ for( final Element pluginEl : editors ) {
+ final String name = pluginEl.getAttributeValue( "name" );
+ final WikiEditorInfo info = WikiEditorInfo.newInstance( name, pluginEl );
- for( Iterator< Element > i = editors.iterator(); i.hasNext(); ) {
- Element pluginEl = i.next();
- String name = pluginEl.getAttributeValue( "name" );
- WikiEditorInfo info = WikiEditorInfo.newInstance( name, pluginEl );
-
- if( checkCompatibility(info) ) {
+ if( checkCompatibility( info ) ) {
m_editors.put( name, info );
log.debug( "Registered editor " + name );
} else {
@@ -129,10 +123,8 @@ public class EditorManager extends ModuleManager {
}
/**
- * Returns an editor for the current context. The editor names are matched in
- * a case insensitive manner. At the moment, the only place that this method
- * looks in is the property file, but in the future this will also look at
- * user preferences.
+ * Returns an editor for the current context. The editor names are matched in a case insensitive manner. At the moment, the only
+ * place that this method looks in is the property file, but in the future this will also look at user preferences.
* <p>
* Determines the editor to use by the following order of conditions:
* 1. Editor set in User Preferences
@@ -141,41 +133,30 @@ public class EditorManager extends ModuleManager {
* For the PREVIEW context, this method returns the "preview" editor.
*
* @param context The context that is chosen.
- * @return The name of the chosen editor. If no match could be found, will
- * revert to the default "plain" editor.
+ * @return The name of the chosen editor. If no match could be found, will revert to the default "plain" editor.
*/
- public String getEditorName( WikiContext context )
- {
- if( context.getRequestContext().equals(WikiContext.PREVIEW) )
+ public String getEditorName( final WikiContext context ) {
+ if( context.getRequestContext().equals( WikiContext.PREVIEW ) ) {
return EDITOR_PREVIEW;
-
- String editor = null;
+ }
// User has set an editor in preferences
- editor = Preferences.getPreference( context, PARA_EDITOR );
+ String editor = Preferences.getPreference( context, PARA_EDITOR );
/* FIXME: actual default 'editor' property is read by the Preferences class */
- if (editor == null)
- {
+ if( editor == null ) {
// or use the default editor in jspwiki.properties
- try
- {
+ try {
editor = m_engine.getVariableManager().getValue( context, PROP_EDITORTYPE );
- }
- catch( NoSuchVariableException e ) {} // This is fine
+ } catch( final NoSuchVariableException e ) {} // This is fine
}
- if (editor != null)
- {
- String[] editorlist = getEditorList();
-
+ if( editor != null ) {
+ final String[] editorlist = getEditorList();
editor = editor.trim();
-
- for( int i = 0; i < editorlist.length; i++ )
- {
- if( editorlist[i].equalsIgnoreCase(editor))
- {
- return editorlist[i];
+ for( final String s : editorlist ) {
+ if( s.equalsIgnoreCase( editor ) ) {
+ return s;
}
}
}
@@ -188,11 +169,9 @@ public class EditorManager extends ModuleManager {
*
* @return the list of available editors
*/
- public String[] getEditorList()
- {
- String[] editors = new String[m_editors.size()];
-
- Set<String> keys = m_editors.keySet();
+ public String[] getEditorList() {
+ final String[] editors = new String[ m_editors.size() ];
+ final Set< String > keys = m_editors.keySet();
return keys.toArray( editors );
}
@@ -200,23 +179,16 @@ public class EditorManager extends ModuleManager {
/**
* Convenience method for getting the path to the editor JSP file.
*
- * @param context
+ * @param context WikiContext from where the editor name is retrieved.
* @return e.g. "editors/plain.jsp"
*/
- public String getEditorPath( WikiContext context )
- {
- String path = null;
-
- String editor = getEditorName( context );
-
- WikiEditorInfo ed = m_editors.get( editor );
-
- if( ed != null )
- {
+ public String getEditorPath( final WikiContext context ) {
+ final String editor = getEditorName( context );
+ final WikiEditorInfo ed = m_editors.get( editor );
+ final String path;
+ if( ed != null ) {
path = ed.getPath();
- }
- else
- {
+ } else {
path = "editors/"+editor+".jsp";
}
@@ -224,56 +196,44 @@ public class EditorManager extends ModuleManager {
}
/**
- * Convenience function which examines the current context and attempts to figure
- * out whether the edited text is in the HTTP request parameters or somewhere in
- * the session.
+ * Convenience function which examines the current context and attempts to figure out whether the edited text is in the HTTP
+ * request parameters or somewhere in the session.
*
* @param ctx the JSP page context
* @return the edited text, if present in the session page context or as a parameter
*/
- public static String getEditedText( PageContext ctx )
- {
+ public static String getEditedText( final PageContext ctx ) {
String usertext = ctx.getRequest().getParameter( REQ_EDITEDTEXT );
-
- if( usertext == null )
- {
- usertext = (String)ctx.findAttribute( ATTR_EDITEDTEXT );
+ if( usertext == null ) {
+ usertext = ( String )ctx.findAttribute( ATTR_EDITEDTEXT );
}
return usertext;
}
- /**
- * Contains info about an editor.
- *
- */
- private static final class WikiEditorInfo
- extends WikiModuleInfo
- {
+ /** Contains info about an editor. */
+ private static final class WikiEditorInfo extends WikiModuleInfo {
private String m_path;
- protected static WikiEditorInfo newInstance( String name, Element el )
- {
- if( name == null || name.length() == 0 ) return null;
- WikiEditorInfo info = new WikiEditorInfo( name );
-
+ protected static WikiEditorInfo newInstance( final String name, final Element el ) {
+ if( name == null || name.length() == 0 ) {
+ return null;
+ }
+ final WikiEditorInfo info = new WikiEditorInfo( name );
info.initializeFromXML( el );
return info;
}
- protected void initializeFromXML( Element el )
- {
+ protected void initializeFromXML( final Element el ) {
super.initializeFromXML( el );
m_path = el.getChildText("path");
}
- private WikiEditorInfo( String name )
- {
- super(name);
+ private WikiEditorInfo( final String name ) {
+ super( name );
}
- public String getPath()
- {
+ public String getPath() {
return m_path;
}
}
@@ -290,8 +250,8 @@ public class EditorManager extends ModuleManager {
* {@inheritDoc}
*/
@Override
- public WikiEditorInfo getModuleInfo(String moduleName) {
- return m_editors.get(moduleName);
+ public WikiEditorInfo getModuleInfo( final String moduleName ) {
+ return m_editors.get( moduleName );
}
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/GenericHTTPHandler.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/GenericHTTPHandler.java
index 66f77b4..f6b3abe 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/GenericHTTPHandler.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/GenericHTTPHandler.java
@@ -22,15 +22,12 @@ import org.apache.wiki.WikiContext;
/**
* Provides a generic HTTP handler interface.
- *
*
*/
-public interface GenericHTTPHandler
-{
+public interface GenericHTTPHandler {
/**
- * Get an identifier for this particular AdminBean. This id MUST
- * conform to URI rules. The ID must also be unique across all HTTPHandlers.
+ * Get an identifier for this particular AdminBean. This id MUST conform to URI rules. The ID must also be unique across all HTTPHandlers.
*
* @return the identifier for the bean
*/
@@ -39,15 +36,16 @@ public interface GenericHTTPHandler
/**
* Return basic HTML.
*
- * @param context
+ * @param context associated WikiContext
* @return the HTML for the bean
*/
String doGet( WikiContext context );
/**
* Handles a POST response.
- * @param context
+ * @param context associated WikiContext
* @return the response string resulting from the POST
*/
String doPost( WikiContext context );
+
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/GroupCommand.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/GroupCommand.java
index f7af946..2466236 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/GroupCommand.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/GroupCommand.java
@@ -18,105 +18,105 @@
*/
package org.apache.wiki.ui;
-import java.security.Permission;
-
import org.apache.wiki.auth.GroupPrincipal;
import org.apache.wiki.auth.permissions.GroupPermission;
+import java.security.Permission;
+
/**
- * <p>Defines Commands for viewing, editing and deleting wiki groups.
- * GroupCommands can be combined with GroupPrincipals to produce
+ * <p>Defines Commands for viewing, editing and deleting wiki groups. GroupCommands can be combined with GroupPrincipals to produce
* targeted Commands.</p>
- * <p>This class is not <code>final</code>; it may be extended in
- * the future.</p>
+ * <p>This class is not <code>final</code>; it may be extended in the future.</p>
* @since 2.4.22
*/
-public final class GroupCommand extends AbstractCommand
-{
+public final class GroupCommand extends AbstractCommand {
/** GroupCommand for deleting a group. */
- public static final Command DELETE_GROUP
- = new GroupCommand( "deleteGroup", "%uDeleteGroup.jsp?group=%n", null, null, GroupPermission.DELETE_ACTION );
+ public static final Command DELETE_GROUP = new GroupCommand( "deleteGroup",
+ "%uDeleteGroup.jsp?group=%n",
+ null,
+ null,
+ GroupPermission.DELETE_ACTION );
/** GroupCommand for editing a group. */
- public static final Command EDIT_GROUP
- = new GroupCommand( "editGroup", "%uEditGroup.jsp?group=%n", "EditGroupContent.jsp", null, GroupPermission.EDIT_ACTION );
+ public static final Command EDIT_GROUP = new GroupCommand( "editGroup",
+ "%uEditGroup.jsp?group=%n",
+ "EditGroupContent.jsp",
+ null,
+ GroupPermission.EDIT_ACTION );
/** GroupCommand for viewing a group. */
- public static final Command VIEW_GROUP
- = new GroupCommand( "viewGroup", "%uGroup.jsp?group=%n", "GroupContent.jsp", null, GroupPermission.VIEW_ACTION );
+ public static final Command VIEW_GROUP = new GroupCommand( "viewGroup",
+ "%uGroup.jsp?group=%n",
+ "GroupContent.jsp",
+ null,
+ GroupPermission.VIEW_ACTION );
private final String m_action;
private final Permission m_permission;
/**
- * Constructs a new Command with a specified wiki context, URL pattern,
- * type, and content template. The WikiPage for this command is initialized
- * to <code>null</code>.
+ * Constructs a new Command with a specified wiki context, URL pattern, type, and content template. The WikiPage for this command is
+ * initialized to <code>null</code>.
+ *
* @param requestContext the request context
* @param urlPattern the URL pattern
* @param target the target of this command (a GroupPrincipal representing a Group); may be <code>null</code>
* @param action the action used to construct a suitable GroupPermission
* @param contentTemplate the content template; may be <code>null</code>
- * @throws IllegalArgumentException if the request content, URL pattern, or
- * type is <code>null</code>
+ * @throws IllegalArgumentException if the request content, URL pattern, or type is <code>null</code>
*/
- private GroupCommand( String requestContext, String urlPattern, String contentTemplate, GroupPrincipal target, String action )
- {
+ private GroupCommand( final String requestContext,
+ final String urlPattern,
+ final String contentTemplate,
+ final GroupPrincipal target,
+ final String action ) {
super( requestContext, urlPattern, contentTemplate, target );
m_action = action;
- if ( target == null || m_action == null )
- {
+ if ( target == null || m_action == null ) {
m_permission = null;
- }
- else
- {
+ } else {
m_permission = new GroupPermission( target.getName(), action );
}
}
/**
- * Creates and returns a targeted Command by combining a GroupPrincipal
- * with this Command. The supplied <code>target</code> object
- * must be non-<code>null</code> and of type GroupPrincipal.
- * If the target is not of the correct type, this method throws an
+ * Creates and returns a targeted Command by combining a GroupPrincipal with this Command. The supplied <code>target</code> object
+ * must be non-<code>null</code> and of type GroupPrincipal. If the target is not of the correct type, this method throws an
* {@link IllegalArgumentException}.
+ *
* @param target the GroupPrincipal to combine into the current Command
* @return the new, targeted command
*/
- public Command targetedCommand( Object target )
- {
- if ( !( target != null && target instanceof GroupPrincipal ) )
- {
+ public Command targetedCommand( final Object target ) {
+ if( !( target instanceof GroupPrincipal ) ) {
throw new IllegalArgumentException( "Target must non-null and of type GroupPrincipal." );
}
- return new GroupCommand( getRequestContext(), getURLPattern(), getContentTemplate(), (GroupPrincipal)target, m_action );
+ return new GroupCommand( getRequestContext(), getURLPattern(), getContentTemplate(), ( GroupPrincipal )target, m_action );
}
/**
- * Returns the name of the command, which will either be
- * the target (if specified), or the "friendly name" for the JSP.
+ * Returns the name of the command, which will either be the target (if specified), or the "friendly name" for the JSP.
+ *
* @return the name
* @see org.apache.wiki.ui.Command#getName()
*/
- public String getName()
- {
- Object target = getTarget();
- if ( target == null )
- {
+ public String getName() {
+ final Object target = getTarget();
+ if ( target == null ) {
return getJSPFriendlyName();
}
- return ( (GroupPrincipal) target ).getName();
+ return ( ( GroupPrincipal ) target ).getName();
}
/**
* Returns the permission required to execute this GroupCommand.
+ *
* @return the permission
* @see org.apache.wiki.ui.Command#requiredPermission()
*/
- public Permission requiredPermission()
- {
+ public Permission requiredPermission() {
return m_permission;
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/InputValidator.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/InputValidator.java
index ea71b53..65534b9 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/InputValidator.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/InputValidator.java
@@ -18,34 +18,32 @@
*/
package org.apache.wiki.ui;
+import org.apache.wiki.WikiContext;
+import org.apache.wiki.WikiSession;
+import org.apache.wiki.i18n.InternationalizationManager;
+import org.apache.wiki.preferences.Preferences;
+
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.wiki.*;
-import org.apache.wiki.i18n.InternationalizationManager;
-import org.apache.wiki.preferences.Preferences;
-
/**
- * Provides basic validation services for HTTP parameters. Three standard
- * validators are provided: email address, identifier and standard input. Standard input
- * validator will reject any HTML-like input, and any of a number of special
- * characters. ID validator rejects HTML and quoted strings, and a couple of special characters.
+ * Provides basic validation services for HTTP parameters. Three standard validators are provided: email address, identifier and
+ * standard input. Standard input validator will reject any HTML-like input, and any of a number of special characters. ID validator
+ * rejects HTML and quoted strings, and a couple of special characters.
+ *
* @since 2.3.54
*/
-public final class InputValidator
-{
+public final class InputValidator {
/** Standard input validator. */
- public static final int STANDARD = 0;
+ public static final int STANDARD = 0;
/** Input validator for e-mail addresses. **/
- public static final int EMAIL = 1;
+ public static final int EMAIL = 1;
- /**
- * @since 2.4.82
- */
- public static final int ID = 2;
+ /** @since 2.4.82 */
+ public static final int ID = 2;
protected static final Pattern EMAIL_PATTERN = Pattern.compile( "^[0-9a-zA-Z-_\\.\\+]+@([0-9a-zA-Z-_]+\\.)+[a-zA-Z]+$" );
@@ -62,111 +60,94 @@ public final class InputValidator
private final WikiContext m_context;
/**
- * Constructs a new input validator for a specific form and wiki session.
- * When validation errors are detected, they will be added to the wiki
- * session's messages.
- * @param form the ID or name of the form this validator should be
- * associated with
+ * Constructs a new input validator for a specific form and wiki session. When validation errors are detected, they will be added to
+ * the wiki session's messages.
+ *
+ * @param form the ID or name of the form this validator should be associated with
* @param context the wiki context
*/
- public InputValidator( String form, WikiContext context )
- {
+ public InputValidator( final String form, final WikiContext context ) {
m_form = form;
m_context = context;
m_session = context.getWikiSession();
}
/**
- * Validates a string against the {@link #STANDARD} validator and
- * additionally checks that the value is not <code>null</code> or blank.
+ * Validates a string against the {@link #STANDARD} validator and additionally checks that the value is not <code>null</code> or blank.
+ *
* @param input the string to validate
* @param label the label for the string or field ("E-mail address")
- * @return returns <code>true</code> if valid, <code>false</code>
- * otherwise
+ * @return returns <code>true</code> if valid, <code>false</code> otherwise
*/
- public boolean validateNotNull( String input, String label )
- {
+ public boolean validateNotNull( final String input, final String label ) {
return validateNotNull( input, label, STANDARD );
}
/**
- * Validates a string against a particular pattern type and additionally
- * checks that the value is not <code>null</code> or blank. Delegates to
- * {@link #validate(String, String, int)}.
+ * Validates a string against a particular pattern type and additionally checks that the value is not <code>null</code> or blank.
+ * Delegates to {@link #validate(String, String, int)}.
+ *
* @param input the string to validate
* @param label the label for the string or field ("E-mail address")
* @param type the pattern type to use (<em>e.g.</em>, {@link #STANDARD}, {@link #EMAIL}.
- * @return returns <code>true</code> if valid, <code>false</code>
- * otherwise
+ * @return returns <code>true</code> if valid, <code>false</code> otherwise
*/
- public boolean validateNotNull( String input, String label, int type )
- {
- if ( isBlank( input ) )
- {
- ResourceBundle rb = Preferences.getBundle( m_context, InternationalizationManager.CORE_BUNDLE );
-
- m_session.addMessage( m_form, MessageFormat.format( rb.getString("validate.cantbenull"),
- label ) );
+ public boolean validateNotNull( final String input, final String label, final int type ) {
+ if ( isBlank( input ) ) {
+ final ResourceBundle rb = Preferences.getBundle( m_context, InternationalizationManager.CORE_BUNDLE );
+ m_session.addMessage( m_form, MessageFormat.format( rb.getString("validate.cantbenull"), label ) );
return false;
}
return validate( input, label, type ) && !isBlank( input );
}
/**
- * Validates a string against a particular pattern type: e-mail address,
- * standard HTML input, etc. Note that a blank or null string will
+ * Validates a string against a particular pattern type: e-mail address, standard HTML input, etc. Note that a blank or null string will
* always validate.
+ *
* @param input the string to validate
* @param label the label for the string or field ("E-mail address")
- * @param type the target pattern to validate against ({@link #STANDARD},
- * {@link #EMAIL})
- * @return returns <code>true</code> if valid, <code>false</code>
- * otherwise
+ * @param type the target pattern to validate against ({@link #STANDARD}, {@link #EMAIL})
+ * @return returns <code>true</code> if valid, <code>false</code> otherwise
*/
- public boolean validate( String input, String label, int type )
- {
+ public boolean validate( final String input, final String label, final int type ) {
// If blank, it's valid
- if ( isBlank( input ) )
- {
+ if ( isBlank( input ) ) {
return true;
}
- ResourceBundle rb = Preferences.getBundle( m_context, InternationalizationManager.CORE_BUNDLE );
+ final ResourceBundle rb = Preferences.getBundle( m_context, InternationalizationManager.CORE_BUNDLE );
// Otherwise, see if it matches the pattern for the target type
- Matcher matcher;
- boolean valid;
- switch( type )
- {
+ final Matcher matcher;
+ final boolean valid;
+ switch( type ) {
case STANDARD:
matcher = UNSAFE_PATTERN.matcher( input );
valid = !matcher.find();
- if ( !valid )
- {
- //MessageTag already invokes replaceEntities()
- //Object[] args = { label, ""'<>;&[]#\\@{}%$" };
- Object[] args = { label, "\'\"<>;&[]#\\@{}%$" };
- m_session.addMessage( m_form, MessageFormat.format( rb.getString("validate.unsafechars"), args ) );
+ if ( !valid ) {
+ // MessageTag already invokes replaceEntities()
+ // Object[] args = { label, ""'<>;&[]#\\@{}%$" };
+ final Object[] args = { label, "\'\"<>;&[]#\\@{}%$" };
+ m_session.addMessage( m_form, MessageFormat.format( rb.getString( "validate.unsafechars" ), args ) );
}
return valid;
case EMAIL:
matcher = EMAIL_PATTERN.matcher( input );
valid = matcher.matches();
- if ( !valid )
- {
- Object[] args = { label };
- m_session.addMessage( m_form, MessageFormat.format( rb.getString("validate.invalidemail"), args ) );
+ if ( !valid ) {
+ final Object[] args = { label };
+ m_session.addMessage( m_form, MessageFormat.format( rb.getString( "validate.invalidemail" ), args ) );
}
return valid;
case ID:
matcher = ID_PATTERN.matcher( input );
valid = !matcher.find();
- if ( !valid )
- {
- //MessageTag already invokes replaceEntities()
- //Object[] args = { label, ""'<>;&{}" };
- Object[] args = { label, "\'\"<>;&{}" };
- m_session.addMessage( m_form, MessageFormat.format( rb.getString("validate.unsafechars"), args ) );
+ if ( !valid ) {
+ // MessageTag already invokes replaceEntities()
+ // Object[] args = { label, ""'<>;&{}" };
+ final Object[] args = { label, "\'\"<>;&{}" };
+ m_session.addMessage( m_form, MessageFormat.format( rb.getString( "validate.unsafechars" ), args ) );
}
return valid;
default:
@@ -177,12 +158,12 @@ public final class InputValidator
/**
* Returns <code>true</code> if a supplied string is null or blank
+ *
* @param input the string to check
- * @return <code>true</code> if <code>null</code> or blank (zero-length);
- * <code>false</code> otherwise
+ * @return <code>true</code> if <code>null</code> or blank (zero-length); <code>false</code> otherwise
*/
- public static boolean isBlank( String input )
- {
+ public static boolean isBlank( final String input ) {
return input == null || input.trim().length() < 1;
}
+
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/Installer.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/Installer.java
index f39a10f..243a67b 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/Installer.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/Installer.java
@@ -1,4 +1,4 @@
-/*
+/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
@@ -18,18 +18,6 @@
*/
package org.apache.wiki.ui;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.text.MessageFormat;
-import java.util.Properties;
-import java.util.ResourceBundle;
-import java.util.Set;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.http.HttpServletRequest;
-
import org.apache.wiki.WikiEngine;
import org.apache.wiki.WikiSession;
import org.apache.wiki.auth.NoSuchPrincipalException;
@@ -46,14 +34,25 @@ import org.apache.wiki.providers.BasicAttachmentProvider;
import org.apache.wiki.providers.FileSystemProvider;
import org.apache.wiki.util.TextUtil;
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.text.MessageFormat;
+import java.util.Properties;
+import java.util.ResourceBundle;
+import java.util.Set;
+
/**
- * Manages JSPWiki installation on behalf of <code>admin/Install.jsp</code>.
- * The contents of this class were previously part of <code>Install.jsp</code>.
+ * Manages JSPWiki installation on behalf of <code>admin/Install.jsp</code>. The contents of this class were previously part of
+ * <code>Install.jsp</code>.
*
* @since 2.4.20
*/
-public class Installer
-{
+public class Installer {
+
public static final String ADMIN_ID = "admin";
public static final String ADMIN_NAME = "Administrator";
public static final String INSTALL_INFO = "Installer.Info";
@@ -73,7 +72,7 @@ public class Installer
private HttpServletRequest m_request;
private boolean m_validated;
- public Installer( HttpServletRequest request, ServletConfig config ) throws IOException {
+ public Installer( final HttpServletRequest request, final ServletConfig config ) {
// Get wiki session for this user
m_engine = WikiEngine.getInstance( config );
m_session = WikiSession.getWikiSession( m_engine, request );
@@ -88,59 +87,47 @@ public class Installer
}
/**
- * Returns <code>true</code> if the administrative user had
- * been created previously.
+ * Returns <code>true</code> if the administrative user had been created previously.
+ *
* @return the result
*/
- public boolean adminExists()
- {
+ public boolean adminExists() {
// See if the admin user exists already
- UserManager userMgr = m_engine.getUserManager();
- UserDatabase userDb = userMgr.getUserDatabase();
-
- try
- {
+ final UserManager userMgr = m_engine.getUserManager();
+ final UserDatabase userDb = userMgr.getUserDatabase();
+ try {
userDb.findByLoginName( ADMIN_ID );
return true;
- }
- catch ( NoSuchPrincipalException e )
- {
+ } catch ( final NoSuchPrincipalException e ) {
return false;
}
}
/**
- * Creates an administrative user and returns the new password.
- * If the admin user exists, the password will be <code>null</code>.
+ * Creates an administrative user and returns the new password. If the admin user exists, the password will be <code>null</code>.
+ *
* @return the password
- * @throws WikiSecurityException
*/
- public String createAdministrator() throws WikiSecurityException
- {
- if ( !m_validated )
- {
+ public String createAdministrator() throws WikiSecurityException {
+ if ( !m_validated ) {
throw new WikiSecurityException( "Cannot create administrator because one or more of the installation settings are invalid." );
}
- if ( adminExists() )
- {
+ if ( adminExists() ) {
return null;
}
// See if the admin user exists already
- UserManager userMgr = m_engine.getUserManager();
- UserDatabase userDb = userMgr.getUserDatabase();
+ final UserManager userMgr = m_engine.getUserManager();
+ final UserDatabase userDb = userMgr.getUserDatabase();
String password = null;
- try
- {
+ try {
userDb.findByLoginName( ADMIN_ID );
- }
- catch ( NoSuchPrincipalException e )
- {
+ } catch( final NoSuchPrincipalException e ) {
// Create a random 12-character password
password = TextUtil.generateRandomPassword();
- UserProfile profile = userDb.newProfile();
+ final UserProfile profile = userDb.newProfile();
profile.setLoginName( ADMIN_ID );
profile.setFullname( ADMIN_NAME );
profile.setPassword( password );
@@ -148,15 +135,12 @@ public class Installer
}
// Create a new admin group
- GroupManager groupMgr = m_engine.getGroupManager();
- Group group = null;
- try
- {
+ final GroupManager groupMgr = m_engine.getGroupManager();
+ Group group;
+ try {
group = groupMgr.getGroup( ADMIN_GROUP );
group.add( new WikiPrincipal( ADMIN_NAME ) );
- }
- catch ( NoSuchPrincipalException e )
- {
+ } catch( final NoSuchPrincipalException e ) {
group = groupMgr.parseGroup( ADMIN_GROUP, ADMIN_NAME, true );
}
groupMgr.setGroup( m_session, group );
@@ -168,18 +152,16 @@ public class Installer
* Returns the properties as a "key=value" string separated by newlines
* @return the string
*/
- public String getPropertiesList()
- {
- StringBuilder result = new StringBuilder();
- Set<String> keys = m_props.stringPropertyNames();
- for (String key:keys) {
- result.append(key + " = " + m_props.getProperty(key) + "\n");
+ public String getPropertiesList() {
+ final StringBuilder result = new StringBuilder();
+ final Set< String > keys = m_props.stringPropertyNames();
+ for( final String key : keys ) {
+ result.append(key ).append( " = " ).append( m_props.getProperty( key ) ).append( "\n" );
}
return result.toString();
}
- public String getPropertiesPath()
- {
+ public String getPropertiesPath() {
return m_propertyFile.getAbsolutePath();
}
@@ -188,17 +170,13 @@ public class Installer
* @param key the property key
* @return the property value
*/
- public String getProperty( String key )
- {
+ public String getProperty( final String key ) {
return m_props.getProperty( key );
}
- public void parseProperties () throws Exception
- {
- ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE,
- m_session.getLocale() );
+ public void parseProperties () {
+ final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, m_session.getLocale() );
m_validated = false;
-
// Get application name
String nullValue = m_props.getProperty( APP_NAME, rb.getString( "install.installer.default.appname" ) );
@@ -219,85 +197,63 @@ public class Installer
m_props.setProperty( PageManager.PROP_PAGEPROVIDER, "VersioningFileProvider" );
}
- public void saveProperties()
- {
- ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, m_session.getLocale() );
+ public void saveProperties() {
+ final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, m_session.getLocale() );
// Write the file back to disk
- try
- {
- OutputStream out = null;
- try
- {
- out = new FileOutputStream( m_propertyFile );
+ try {
+ try( final OutputStream out = new FileOutputStream( m_propertyFile ) ) {
m_props.store( out, null );
}
- finally
- {
- if ( out != null )
- {
- out.close();
- }
- }
m_session.addMessage( INSTALL_INFO, MessageFormat.format(rb.getString("install.installer.props.saved"), m_propertyFile) );
- }
- catch( IOException e )
- {
- Object[] args = { e.getMessage(), m_props.toString() };
+ } catch( final IOException e ) {
+ final Object[] args = { e.getMessage(), m_props.toString() };
m_session.addMessage( INSTALL_ERROR, MessageFormat.format( rb.getString( "install.installer.props.notsaved" ), args ) );
}
}
- public boolean validateProperties() throws Exception
- {
- ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, m_session.getLocale() );
+ public boolean validateProperties() {
+ final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, m_session.getLocale() );
m_session.clearMessages( INSTALL_ERROR );
parseProperties();
validateNotNull( PAGE_DIR, rb.getString( "install.installer.validate.pagedir" ) );
validateNotNull( APP_NAME, rb.getString( "install.installer.validate.appname" ) );
validateNotNull( WORK_DIR, rb.getString( "install.installer.validate.workdir" ) );
- if ( m_session.getMessages( INSTALL_ERROR ).length == 0 )
- {
+ if ( m_session.getMessages( INSTALL_ERROR ).length == 0 ) {
m_validated = true;
}
return m_validated;
}
/**
- * Sets a property based on the value of an HTTP request parameter.
- * If the parameter is not found, a default value is used instead.
+ * Sets a property based on the value of an HTTP request parameter. If the parameter is not found, a default value is used instead.
+ *
* @param param the parameter containing the value we will extract
- * @param defaultValue the default to use if the parameter was not passed
- * in the request
+ * @param defaultValue the default to use if the parameter was not passed in the request
*/
- private void parseProperty( String param, String defaultValue )
- {
+ private void parseProperty( final String param, final String defaultValue ) {
String value = m_request.getParameter( param );
- if ( value == null )
- {
+ if( value == null ) {
value = defaultValue;
}
- m_props.put(param, value);
+ m_props.put( param, value );
}
/**
- * Simply sanitizes any path which contains backslashes (sometimes Windows
- * users may have them) by expanding them to double-backslashes
+ * Simply sanitizes any path which contains backslashes (sometimes Windows users may have them) by expanding them to double-backslashes
+ *
* @param key the key of the property to sanitize
*/
- private void sanitizePath( String key )
- {
+ private void sanitizePath( final String key ) {
String s = m_props.getProperty( key );
s = TextUtil.replaceString(s, "\\", "\\\\" );
s = s.trim();
m_props.put( key, s );
}
- private void validateNotNull( String key, String message )
- {
- String value = m_props.getProperty( key );
- if ( value == null || value.length() == 0 )
- {
+ private void validateNotNull( final String key, final String message ) {
+ final String value = m_props.getProperty( key );
+ if ( value == null || value.length() == 0 ) {
m_session.addMessage( INSTALL_ERROR, message );
}
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/PageCommand.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/PageCommand.java
index 5da646e..cd0d886 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/PageCommand.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/PageCommand.java
@@ -18,22 +18,19 @@
*/
package org.apache.wiki.ui;
-import java.security.Permission;
-
import org.apache.wiki.WikiPage;
import org.apache.wiki.auth.permissions.PagePermission;
import org.apache.wiki.auth.permissions.PermissionFactory;
+import java.security.Permission;
+
/**
- * <p>Defines Commands for editing, renaming, and viewing wiki pages.
- * PageCommands can be combined with WikiPages to produce
+ * <p>Defines Commands for editing, renaming, and viewing wiki pages. PageCommands can be combined with WikiPages to produce
* targeted Commands.</p>
- * <p>This class is not <code>final</code>; it may be extended in
- * the future.</p>
+ *
* @since 2.4.22
*/
-public final class PageCommand extends AbstractCommand
-{
+public final class PageCommand extends AbstractCommand {
public static final Command ATTACH
= new PageCommand( "att", "%uattach/%n", null, null, PagePermission.UPLOAD_ACTION );
@@ -81,66 +78,61 @@ public final class PageCommand extends AbstractCommand
private final Permission m_permission;
/**
- * Constructs a new Command with a specified wiki context, URL pattern,
- * type, and content template. The target for this command is initialized to
- * <code>null</code>.
+ * Constructs a new Command with a specified wiki context, URL pattern, type, and content template. The target for this command is
+ * initialized to <code>null</code>.
+ *
* @param requestContext the request context
* @param urlPattern the URL pattern
* @param target the target of the command (a WikiPage); may be <code>null</code>
* @param action the action used to construct a suitable PagePermission
* @param contentTemplate the content template; may be <code>null</code>
- * @throws IllegalArgumentException if the request content, URL pattern, or
- * type is <code>null</code>
+ * @throws IllegalArgumentException if the request content, URL pattern, or type is <code>null</code>
*/
- private PageCommand( String requestContext, String urlPattern, String contentTemplate, WikiPage target, String action )
- {
+ private PageCommand( final String requestContext,
+ final String urlPattern,
+ final String contentTemplate,
+ final WikiPage target,
+ final String action ) {
super( requestContext, urlPattern, contentTemplate, target );
m_action = action;
- if( target == null || m_action == null )
- {
+ if( target == null || m_action == null ) {
m_permission = null;
- }
- else
- {
+ } else {
m_permission = PermissionFactory.getPagePermission( target, action );
}
}
/**
- * Creates and returns a targeted Command by combining a WikiPage
- * with this Command. The supplied <code>target</code> object
+ * Creates and returns a targeted Command by combining a WikiPage with this Command. The supplied <code>target</code> object
* must be non-<code>null</code> and of type WikiPage.
+ *
* @param target the WikiPage to combine into the current Command
* @return the new targeted command
* @throws IllegalArgumentException if the target is not of the correct type
*/
- public Command targetedCommand( Object target )
- {
- if( !( target != null && target instanceof WikiPage ) )
- {
+ public Command targetedCommand( final Object target ) {
+ if( !( target instanceof WikiPage ) ) {
throw new IllegalArgumentException( "Target must non-null and of type WikiPage." );
}
- return new PageCommand( getRequestContext(), getURLPattern(), getContentTemplate(), (WikiPage)target, m_action );
+ return new PageCommand( getRequestContext(), getURLPattern(), getContentTemplate(), ( WikiPage )target, m_action );
}
/**
* @see org.apache.wiki.ui.Command#getName()
*/
- public String getName()
- {
- Object target = getTarget();
- if( target == null )
- {
+ public String getName() {
+ final Object target = getTarget();
+ if( target == null ) {
return getJSPFriendlyName();
}
- return ( (WikiPage) target ).getName();
+ return ( ( WikiPage )target ).getName();
}
/**
* @see org.apache.wiki.ui.Command#requiredPermission()
*/
- public Permission requiredPermission()
- {
+ public Permission requiredPermission() {
return m_permission;
}
+
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/RedirectCommand.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/RedirectCommand.java
index ba71971..cb098c2 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/RedirectCommand.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/RedirectCommand.java
@@ -21,68 +21,53 @@ package org.apache.wiki.ui;
import java.security.Permission;
/**
- * <p>Defines Commands for redirections to off-site special pages.
- * RedirectCommands do not have associated
- * permissions; the {@link #requiredPermission()} method will
- * always return <code>null</code>. When combined with a supplied String
- * url, the {@link #getTarget()} method will return a String, the
- * {@link #getURLPattern()} method will return the supplied target URL,
+ * <p>Defines Commands for redirections to off-site special pages. RedirectCommands do not have associated permissions; the
+ * {@link #requiredPermission()} method will always return <code>null</code>. When combined with a supplied String url,
+ * the {@link #getTarget()} method will return a String, the {@link #getURLPattern()} method will return the supplied target URL,
* and {@link #getJSP()} method will return the "cleansed" URL.</p>
- * <p>This class is not <code>final</code>; it may be extended in
- * the future.</p>
+ *
* @since 2.4.22
*/
-public final class RedirectCommand extends AbstractCommand
-{
+public final class RedirectCommand extends AbstractCommand {
- public static final Command REDIRECT
- = new RedirectCommand( "", "%u%n", null, null );
+ public static final Command REDIRECT = new RedirectCommand( "", "%u%n", null, null );
/**
- * Constructs a new Command with a specified wiki context, URL pattern,
- * type, and content template. The WikiPage for this action is initialized
- * to <code>null</code>.
+ * Constructs a new Command with a specified wiki context, URL pattern, type, and content template. The WikiPage for this action is
+ * initialized to <code>null</code>.
+ *
* @param requestContext the request context
* @param urlPattern the URL pattern
* @param contentTemplate the content template; may be <code>null</code>
* @param target the target of the command
- * @throws IllegalArgumentException if the request content, URL pattern, or
- * type is <code>null</code>
+ * @throws IllegalArgumentException if the request content, URL pattern, or type is <code>null</code>
*/
- private RedirectCommand( String requestContext, String urlPattern, String contentTemplate, String target )
- {
+ private RedirectCommand( final String requestContext, final String urlPattern, final String contentTemplate, final String target ) {
super( requestContext, urlPattern, contentTemplate, target );
}
/**
- * Creates and returns a targeted Command by combining a URL
- * (as String) with this Command. The supplied <code>target</code>
- * object must be non-<code>null</code> and of type String.
- * The URL passed to the constructor is actually an
- * URL pattern, but it will be converted to a JSP page if it is a partial
- * URL. If it is a full URL (beginning with <code>http://</code> or
- * <code>https://</code>), it will be "passed through" without
- * conversion, and the URL pattern will be <code>null</code>.
+ * Creates and returns a targeted Command by combining a URL (as String) with this Command. The supplied <code>target</code>
+ * object must be non-<code>null</code> and of type String. The URL passed to the constructor is actually an URL pattern, but it
+ * will be converted to a JSP page if it is a partial URL. If it is a full URL (beginning with <code>http://</code> or
+ * <code>https://</code>), it will be "passed through" without conversion, and the URL pattern will be <code>null</code>.
+ *
* @param target the object to combine
* @throws IllegalArgumentException if the target is not of the correct type
*/
- public Command targetedCommand( Object target )
- {
- if ( !( target != null && target instanceof String ) )
- {
+ public Command targetedCommand( final Object target ) {
+ if ( !( target instanceof String ) ) {
throw new IllegalArgumentException( "Target must non-null and of type String." );
}
- return new RedirectCommand( getRequestContext(), (String)target, getContentTemplate(), (String)target );
+ return new RedirectCommand( getRequestContext(), ( String )target, getContentTemplate(), ( String )target );
}
/**
* @see org.apache.wiki.ui.Command#getName()
*/
- public String getName()
- {
- Object target = getTarget();
- if ( target == null )
- {
+ public String getName() {
+ final Object target = getTarget();
+ if ( target == null ) {
return getJSPFriendlyName();
}
return target.toString();
@@ -90,10 +75,11 @@ public final class RedirectCommand extends AbstractCommand
/**
* No-op; always returns <code>null</code>.
+ *
* @see org.apache.wiki.ui.Command#requiredPermission()
*/
- public Permission requiredPermission()
- {
+ public Permission requiredPermission() {
return null;
}
+
}
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 ce5192f..c2db396 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
@@ -56,8 +56,7 @@ import java.util.Vector;
/**
- * This class takes care of managing JSPWiki templates. This class also provides
- * the ResourceRequest mechanism.
+ * This class takes care of managing JSPWiki templates. This class also provides the ResourceRequest mechanism.
*
* @since 2.1.62
*/
@@ -65,29 +64,19 @@ public class TemplateManager extends ModuleManager {
private static final String SKIN_DIRECTORY = "skins";
- /**
- * Requests a JavaScript function to be called during window.onload. Value is {@value}.
- */
+ /** Requests a JavaScript function to be called during window.onload. Value is {@value}. */
public static final String RESOURCE_JSFUNCTION = "jsfunction";
- /**
- * Requests a JavaScript associative array with all localized strings.
- */
+ /** Requests a JavaScript associative array with all localized strings. */
public static final String RESOURCE_JSLOCALIZEDSTRINGS = "jslocalizedstrings";
- /**
- * Requests a stylesheet to be inserted. Value is {@value}.
- */
+ /** Requests a stylesheet to be inserted. Value is {@value}. */
public static final String RESOURCE_STYLESHEET = "stylesheet";
- /**
- * Requests a script to be loaded. Value is {@value}.
- */
+ /** Requests a script to be loaded. Value is {@value}. */
public static final String RESOURCE_SCRIPT = "script";
- /**
- * Requests inlined CSS. Value is {@value}.
- */
+ /** Requests inlined CSS. Value is {@value}. */
public static final String RESOURCE_INLINECSS = "inlinecss";
/** The default directory for the properties. Value is {@value}. */
@@ -97,41 +86,32 @@ public class TemplateManager extends ModuleManager {
public static final String DEFAULT_TEMPLATE = "default";
/** Name of the file that contains the properties. */
-
public static final String PROPERTYFILE = "template.properties";
/** Location of I18N Resource bundles, and path prefix and suffixes */
-
public static final String I18NRESOURCE_PREFIX = "templates/default_";
public static final String I18NRESOURCE_SUFFIX = ".properties";
/** The default (en) RESOURCE name and id. */
-
public static final String I18NRESOURCE_EN = "templates/default.properties";
public static final String I18NRESOURCE_EN_ID = "en";
/** I18N string to mark the default locale */
-
public static final String I18NDEFAULT_LOCALE = "prefs.user.language.default";
/** I18N string to mark the server timezone */
-
public static final String I18NSERVER_TIMEZONE = "prefs.user.timezone.server";
/** Prefix of the default timeformat properties. */
-
public static final String TIMEFORMATPROPERTIES = "jspwiki.defaultprefs.timeformat.";
- /**
- * The name under which the resource includes map is stored in the
- * WikiContext.
- */
+ /** The name under which the resource includes map is stored in the WikiContext. */
public static final String RESOURCE_INCLUDES = "jspwiki.resourceincludes";
// private Cache m_propertyCache;
- protected static final Logger log = Logger.getLogger(TemplateManager.class);
+ private static final Logger log = Logger.getLogger( TemplateManager.class );
/** Requests a HTTP header. Value is {@value}. */
public static final String RESOURCE_HTTPHEADER = "httpheader";
@@ -142,9 +122,8 @@ public class TemplateManager extends ModuleManager {
* @param engine The owning engine.
* @param properties The property list used to initialize this.
*/
- public TemplateManager( WikiEngine engine, Properties properties )
- {
- super(engine);
+ public TemplateManager( final WikiEngine engine, final Properties properties ) {
+ super( engine );
//
// Uses the unlimited cache.
@@ -156,21 +135,20 @@ public class TemplateManager extends ModuleManager {
* Check the existence of a template.
*/
// FIXME: Does not work yet
- public boolean templateExists( String templateName ) {
- ServletContext context = m_engine.getServletContext();
+ public boolean templateExists( final String templateName ) {
+ final ServletContext context = m_engine.getServletContext();
try( final InputStream in = context.getResourceAsStream( getPath( templateName ) + "ViewTemplate.jsp" ) ) {
if( in != null ) {
return true;
}
- } catch( IOException e ) {
+ } catch( final IOException e ) {
log.error( e.getMessage(), e );
}
return false;
}
/**
- * Tries to locate a given resource from the template directory. If the
- * given resource is not found under the current name, returns the
+ * Tries to locate a given resource from the template directory. If the given resource is not found under the current name, returns the
* path to the corresponding one in the default template.
*
* @param sContext The servlet context
@@ -200,54 +178,47 @@ public class TemplateManager extends ModuleManager {
* @param name
* @return the Resource for the given template and name.
*/
- private static String findResource( ServletContext sContext, String template, String name )
- {
- if( name.charAt(0) == '/' )
- {
+ private static String findResource( final ServletContext sContext, final String template, final String name ) {
+ if( name.charAt(0) == '/' ) {
// This is already a full path
return findResource( sContext, name );
}
-
- String fullname = makeFullJSPName( template, name );
-
+ final String fullname = makeFullJSPName( template, name );
return findResource( sContext, fullname );
}
/**
- * An utility method for finding a JSP page. It searches only under
- * either current context or by the absolute name.
+ * An utility method for finding a JSP page. It searches only under either current context or by the absolute name.
*
* @param pageContext the JSP PageContext
* @param name The name of the JSP page to look for (e.g "Wiki.jsp")
* @return The context path to the resource
*/
- public String findJSP( PageContext pageContext, String name )
- {
- ServletContext sContext = pageContext.getServletContext();
-
+ public String findJSP( final PageContext pageContext, final String name ) {
+ final ServletContext sContext = pageContext.getServletContext();
return findResource( sContext, name );
}
/**
* Removes the template part of a name.
*/
- private static String removeTemplatePart( String name )
- {
+ private static String removeTemplatePart( String name ) {
int idx = 0;
- if( name.startsWith( "/" ) ) idx = 1;
+ if( name.startsWith( "/" ) ) {
+ idx = 1;
+ }
idx = name.indexOf('/', idx);
- if( idx != -1 )
- {
+ if( idx != -1 ) {
idx = name.indexOf('/', idx+1); // Find second "/"
-
- if( idx != -1 )
- {
+ if( idx != -1 ) {
name = name.substring( idx+1 );
}
}
- if( log.isDebugEnabled() ) log.debug( "Final name = "+name );
+ if( log.isDebugEnabled() ) {
+ log.debug( "Final name = "+name );
+ }
return name;
}
@@ -258,45 +229,36 @@ public class TemplateManager extends ModuleManager {
* @param name The name of the resource.
* @return The full name for a template.
*/
- private static String makeFullJSPName( String template, String name )
- {
- return "/"+DIRECTORY+"/"+template+"/"+name;
+ private static String makeFullJSPName( final String template, final String name ) {
+ return "/" + DIRECTORY + "/" + template + "/" + name;
}
/**
- * Attempts to locate a resource under the given template. If that template
- * does not exist, or the page does not exist under that template, will
- * attempt to locate a similarly named file under the default template.
+ * Attempts to locate a resource under the given template. If that template does not exist, or the page does not exist under that
+ * template, will attempt to locate a similarly named file under the default template.
* <p>
- * Even though the name suggests only JSP files can be located, but in fact
- * this method can find also other resources than JSP files.
+ * Even though the name suggests only JSP files can be located, but in fact this method can find also other resources than JSP files.
*
* @param pageContext The JSP PageContext
* @param template From which template we should seek initially?
* @param name Which resource are we looking for (e.g. "ViewTemplate.jsp")
* @return path to the JSP page; null, if it was not found.
*/
- public String findJSP( PageContext pageContext, String template, String name )
- {
- if( name == null || template == null )
- {
- log.fatal("findJSP() was asked to find a null template or name ("+template+","+name+")."+
- " JSP page '"+
- ((HttpServletRequest)pageContext.getRequest()).getRequestURI()+"'");
- throw new InternalWikiException("Illegal arguments to findJSP(); please check logs.");
+ public String findJSP( final PageContext pageContext, final String template, final String name ) {
+ if( name == null || template == null ) {
+ log.fatal("findJSP() was asked to find a null template or name (" + template + "," + name + ")." + " JSP page '" +
+ ( ( HttpServletRequest )pageContext.getRequest() ).getRequestURI() + "'" );
+ throw new InternalWikiException( "Illegal arguments to findJSP(); please check logs." );
}
return findResource( pageContext.getServletContext(), template, name );
}
/**
- * Attempts to locate a resource under the given template. This matches the
- * functionality findJSP(), but uses the WikiContext as the argument. If there
- * is no servlet context (i.e. this is embedded), will just simply return
- * a best-guess.
+ * Attempts to locate a resource under the given template. This matches the functionality findJSP(), but uses the WikiContext as
+ * the argument. If there is no servlet context (i.e. this is embedded), will just simply return a best-guess.
* <p>
- * This method is typically used to locate any resource, including JSP pages, images,
- * scripts, etc.
+ * This method is typically used to locate any resource, including JSP pages, images, scripts, etc.
*
* @since 2.6
* @param ctx the wiki context
@@ -304,10 +266,8 @@ public class TemplateManager extends ModuleManager {
* @param name the name of the resource to fine
* @return the path to the resource
*/
- public String findResource( WikiContext ctx, String template, String name )
- {
- if( m_engine.getServletContext() != null )
- {
+ public String findResource( final WikiContext ctx, final String template, final String name ) {
+ if( m_engine.getServletContext() != null ) {
return findResource( m_engine.getServletContext(), template, name );
}
@@ -315,8 +275,7 @@ public class TemplateManager extends ModuleManager {
}
/**
- * Returns a property, as defined in the template. The evaluation
- * is lazy, i.e. the properties are not loaded until the template is
+ * Returns a property, as defined in the template. The evaluation is lazy, i.e. the properties are not loaded until the template is
* actually used for the first time.
*/
/*
@@ -356,16 +315,13 @@ public class TemplateManager extends ModuleManager {
/**
* Returns an absolute path to a given template.
*/
- private static String getPath( String template )
- {
- return "/"+DIRECTORY+"/"+template+"/";
+ private static String getPath( final String template ) {
+ return "/" + DIRECTORY + "/" + template + "/";
}
/**
- * Lists the skins available under this template. Returns an
- * empty Set, if there are no extra skins available. Note that
- * this method does not check whether there is anything actually
- * in the directories, it just lists them. This may change
+ * Lists the skins available under this template. Returns an empty Set, if there are no extra skins available. Note that
+ * this method does not check whether there is anything actually in the directories, it just lists them. This may change
* in the future.
*
* @param pageContext the JSP PageContext
@@ -373,33 +329,26 @@ public class TemplateManager extends ModuleManager {
* @return Set of Strings with the skin names.
* @since 2.3.26
*/
- public Set< String > listSkins( PageContext pageContext, String template )
- {
- String place = makeFullJSPName( template, SKIN_DIRECTORY );
-
- ServletContext sContext = pageContext.getServletContext();
-
- Set<String> skinSet = sContext.getResourcePaths( place );
- TreeSet<String> resultSet = new TreeSet<>();
-
- if( log.isDebugEnabled() ) log.debug( "Listings skins from "+place );
-
- if( skinSet != null )
- {
- String[] skins = {};
-
- skins = skinSet.toArray(skins);
-
- for (int i = 0; i < skins.length; i++)
- {
- String[] s = StringUtils.split(skins[i], "/");
+ public Set< String > listSkins( final PageContext pageContext, final String template ) {
+ final String place = makeFullJSPName( template, SKIN_DIRECTORY );
+ final ServletContext sContext = pageContext.getServletContext();
+ final Set< String > skinSet = sContext.getResourcePaths( place );
+ final Set< String > resultSet = new TreeSet<>();
+
+ if( log.isDebugEnabled() ) {
+ log.debug( "Listings skins from " + place );
+ }
- if (s.length > 2 && skins[i].endsWith("/"))
- {
- String skinName = s[s.length - 1];
- resultSet.add(skinName);
- if (log.isDebugEnabled())
- log.debug("...adding skin '" + skinName + "'");
+ if( skinSet != null ) {
+ final String[] skins = skinSet.toArray( new String[]{} );
+ for( final String skin : skins ) {
+ final String[] s = StringUtils.split( skin, "/" );
+ if( s.length > 2 && skin.endsWith( "/" ) ) {
+ final String skinName = s[ s.length - 1 ];
+ resultSet.add( skinName );
+ if( log.isDebugEnabled() ) {
+ log.debug( "...adding skin '" + skinName + "'" );
+ }
}
}
}
@@ -416,28 +365,23 @@ public class TemplateManager extends ModuleManager {
* @return map of installed Languages
* @since 2.7.x
*/
- public Map< String, String > listLanguages(PageContext pageContext)
- {
- Map< String, String > resultMap = new LinkedHashMap<>();
- String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString();
-
- List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY );
+ public Map< String, String > listLanguages( final PageContext pageContext ) {
+ final Map< String, String > resultMap = new LinkedHashMap<>();
+ final String clientLanguage = pageContext.getRequest().getLocale().toString();
+ final List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY );
for( String name : entries ) {
- if ( name.equals( I18NRESOURCE_EN ) ||
- (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) )
- {
- if (name.equals( I18NRESOURCE_EN )) {
+ if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) {
+ if( name.equals( I18NRESOURCE_EN ) ) {
name = I18NRESOURCE_EN_ID;
- } else {
- name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX));
+ } else {
+ name = name.substring( I18NRESOURCE_PREFIX.length(), name.lastIndexOf( I18NRESOURCE_SUFFIX ) );
}
- Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5)));
+ final Locale locale = new Locale( name.substring( 0, 2 ), ( ( name.indexOf( "_" ) == -1 ) ? "" : name.substring( 3, 5 ) ) );
String defaultLanguage = "";
- if (clientLanguage.startsWith(name))
- {
- defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE);
+ if( clientLanguage.startsWith( name ) ) {
+ defaultLanguage = LocaleSupport.getLocalizedMessage( pageContext, I18NDEFAULT_LOCALE );
}
- resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage);
+ resultMap.put( name, locale.getDisplayName( locale ) + " " + defaultLanguage );
}
}
@@ -452,40 +396,36 @@ public class TemplateManager extends ModuleManager {
* @return map of TimeFormats
* @since 2.7.x
*/
- public Map< String, String > listTimeFormats(PageContext pageContext)
- {
- WikiContext context = WikiContext.findContext( pageContext );
- Properties props = m_engine.getWikiProperties();
- ArrayList<String> tfArr = new ArrayList<>(40);
- LinkedHashMap<String,String> resultMap = new LinkedHashMap<>();
+ public Map< String, String > listTimeFormats( final PageContext pageContext ) {
+ final WikiContext context = WikiContext.findContext( pageContext );
+ final Properties props = m_engine.getWikiProperties();
+ final ArrayList< String > tfArr = new ArrayList<>(40);
+ final LinkedHashMap< String, String > resultMap = new LinkedHashMap<>();
/* filter timeformat properties */
- for (Enumeration< ? > e = props.propertyNames(); e.hasMoreElements();)
- {
- String name = (String) e.nextElement();
-
- if (name.startsWith(TIMEFORMATPROPERTIES))
- {
- tfArr.add(name);
+ for( final Enumeration< ? > e = props.propertyNames(); e.hasMoreElements(); ) {
+ final String name = ( String )e.nextElement();
+ if( name.startsWith( TIMEFORMATPROPERTIES ) ) {
+ tfArr.add( name );
}
}
/* fetch actual formats */
- 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");
+ 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 {
- Collections.sort(tfArr);
+ Collections.sort( tfArr );
for (int i = 0; i < tfArr.size(); i++) {
tfArr.set(i, props.getProperty(tfArr.get(i)));
}
}
- String prefTimeZone = Preferences.getPreference( context, "TimeZone" );
+ final String prefTimeZone = Preferences.getPreference( context, "TimeZone" );
//TimeZone tz = TimeZone.getDefault();
- TimeZone tz = TimeZone.getTimeZone(prefTimeZone);
+ final TimeZone tz = TimeZone.getTimeZone(prefTimeZone);
/*try
{
tz.setRawOffset(Integer.parseInt(prefTimeZone));
@@ -494,30 +434,21 @@ public class TemplateManager extends ModuleManager {
{
}*/
- Date d = new Date(); // current date
- try
- {
+ final Date d = new Date(); // current date
+ try {
// dummy format pattern
- SimpleDateFormat fmt = Preferences.getDateFormat( context, TimeFormat.DATETIME );
- fmt.setTimeZone(tz);
-
- for (int i = 0; i < tfArr.size(); i++)
- {
- try
- {
- String f = tfArr.get(i);
- fmt.applyPattern(f);
-
- resultMap.put(f, fmt.format(d));
- }
- catch (IllegalArgumentException e)
- {
- } // skip parameter
+ final SimpleDateFormat fmt = Preferences.getDateFormat( context, TimeFormat.DATETIME );
+ fmt.setTimeZone( tz );
+
+ for( int i = 0; i < tfArr.size(); i++ ) {
+ try {
+ final String f = tfArr.get( i );
+ fmt.applyPattern( f );
+ resultMap.put( f, fmt.format( d ) );
+ } catch( final IllegalArgumentException e ) {} // skip parameter
}
}
- catch (IllegalArgumentException e)
- {
- } // skip parameter
+ catch( final IllegalArgumentException e ) {} // skip parameter
return resultMap;
}
@@ -529,11 +460,10 @@ public class TemplateManager extends ModuleManager {
* @return map of TimeZones
* @since 2.7.x
*/
- public Map< String, String > listTimeZones(PageContext pageContext)
- {
- Map<String,String> resultMap = new LinkedHashMap<>();
-
- String[][] tzs = { { "GMT-12", "Enitwetok, Kwajalien" },
+ public Map< String, String > listTimeZones( final PageContext pageContext ) {
+ final Map<String,String> resultMap = new LinkedHashMap<>();
+ final String[][] tzs = {
+ { "GMT-12", "Enitwetok, Kwajalien" },
{ "GMT-11", "Nome, Midway Island, Samoa" },
{ "GMT-10", "Hawaii" },
{ "GMT-9", "Alaska" },
@@ -564,22 +494,17 @@ public class TemplateManager extends ModuleManager {
{ "GMT+11", "Magadan, New Caledonia, Solomon Islands" },
{ "GMT+12", "Auckland, Wellington, Fiji, Marshall Island" } };
- java.util.TimeZone servertz = java.util.TimeZone.getDefault();
-
- for( int i = 0; i < tzs.length; i++ )
- {
- String tzID = tzs[i][0];
- java.util.TimeZone tz = java.util.TimeZone.getTimeZone(tzID);
-
+ final TimeZone servertz = TimeZone.getDefault();
+ for( final String[] strings : tzs ) {
+ String tzID = strings[ 0 ];
+ final TimeZone tz = TimeZone.getTimeZone( tzID );
String serverTimeZone = "";
-
- if( servertz.getRawOffset() == tz.getRawOffset() )
- {
- serverTimeZone = LocaleSupport.getLocalizedMessage(pageContext, I18NSERVER_TIMEZONE);
+ if( servertz.getRawOffset() == tz.getRawOffset() ) {
+ serverTimeZone = LocaleSupport.getLocalizedMessage( pageContext, I18NSERVER_TIMEZONE );
tzID = servertz.getID();
}
- resultMap.put(tzID, "(" + tzs[i][0] + ") "+tzs[i][1] + " " + serverTimeZone);
+ resultMap.put( tzID, "(" + strings[ 0 ] + ") " + strings[ 1 ] + " " + serverTimeZone );
}
return resultMap;
@@ -620,49 +545,34 @@ public class TemplateManager extends ModuleManager {
* @param type the marker
* @return the generated marker comment
*/
- public static String getMarker(WikiContext context, String type )
- {
- if( type.equals(RESOURCE_JSLOCALIZEDSTRINGS) )
- {
+ public static String getMarker( final WikiContext context, final String type ) {
+ if( type.equals( RESOURCE_JSLOCALIZEDSTRINGS ) ) {
return getJSLocalizedStrings( context );
- }
- else if( type.equals(RESOURCE_JSFUNCTION) )
- {
+ } else if( type.equals( RESOURCE_JSFUNCTION ) ) {
return "/* INCLUDERESOURCES ("+type+") */";
}
return "<!-- INCLUDERESOURCES ("+type+") -->";
}
/**
- * Extract all i18n strings in the javascript domain. (javascript.*)
- * Returns a javascript snippet which defines the LocalizedStings array.
+ * Extract all i18n strings in the javascript domain. (javascript.*) Returns a javascript snippet which defines the LocalizedStings array.
*
* @param context the {@link WikiContext}
* @return Javascript snippet which defines the LocalizedStrings array
* @since 2.5.108
*/
- private static String getJSLocalizedStrings( WikiContext context )
- {
- StringBuilder sb = new StringBuilder();
-
+ private static String getJSLocalizedStrings( final WikiContext context ) {
+ final StringBuilder sb = new StringBuilder();
sb.append( "var LocalizedStrings = {\n");
-
- ResourceBundle rb = Preferences.getBundle( context, InternationalizationManager.DEF_TEMPLATE );
-
+ final ResourceBundle rb = Preferences.getBundle( context, InternationalizationManager.DEF_TEMPLATE );
boolean first = true;
- for( Enumeration< String > en = rb.getKeys(); en.hasMoreElements(); )
- {
- String key = en.nextElement();
-
- if( key.startsWith("javascript") )
- {
- if( first )
- {
+ for( final Enumeration< String > en = rb.getKeys(); en.hasMoreElements(); ) {
+ final String key = en.nextElement();
+ if( key.startsWith("javascript") ) {
+ if( first ) {
first = false;
- }
- else
- {
+ } else {
sb.append( ",\n" );
}
sb.append( "\""+key+"\":\""+rb.getString(key)+"\"" );
@@ -674,103 +584,84 @@ public class TemplateManager extends ModuleManager {
}
/**
- * Adds a resource request to the current request context.
- * The content will be added at the resource-type marker
+ * Adds a resource request to the current request context. The content will be added at the resource-type marker
* (see IncludeResourcesTag) in WikiJSPFilter.
* <p>
- * The resources can be of different types. For RESOURCE_SCRIPT and RESOURCE_STYLESHEET
- * this is an URI path to the resource (a script file or an external stylesheet)
- * that needs to be included. For RESOURCE_INLINECSS
- * the resource should be something that can be added between <style></style> in the
- * header file (commonheader.jsp). For RESOURCE_JSFUNCTION it is the name of the Javascript
- * function that should be run at page load.
+ * The resources can be of different types. For RESOURCE_SCRIPT and RESOURCE_STYLESHEET this is an URI path to the resource
+ * (a script file or an external stylesheet) that needs to be included. For RESOURCE_INLINECSS the resource should be something
+ * that can be added between <style></style> in the header file (commonheader.jsp). For RESOURCE_JSFUNCTION it is the name
+ * of the Javascript function that should be run at page load.
* <p>
- * The IncludeResourceTag inserts code in the template files, which is then filled
- * by the WikiFilter after the request has been rendered but not yet sent to the recipient.
+ * The IncludeResourceTag inserts code in the template files, which is then filled by the WikiFilter after the request has been
+ * rendered but not yet sent to the recipient.
* <p>
- * Note that ALL resource requests get rendered, so this method does not check if
- * the request already exists in the resources. Therefore, if you have a plugin which
- * makes a new resource request every time, you'll end up with multiple resource requests
- * rendered. It's thus a good idea to make this request only once during the page
- * life cycle.
+ * Note that ALL resource requests get rendered, so this method does not check if the request already exists in the resources.
+ * Therefore, if you have a plugin which makes a new resource request every time, you'll end up with multiple resource requests
+ * rendered. It's thus a good idea to make this request only once during the page life cycle.
*
* @param ctx The current wiki context
* @param type What kind of a request should be added?
* @param resource The resource to add.
*/
@SuppressWarnings("unchecked")
- public static void addResourceRequest( WikiContext ctx, String type, String resource )
- {
- HashMap<String,Vector<String>> resourcemap = (HashMap<String,Vector<String>>) ctx.getVariable( RESOURCE_INCLUDES );
-
- if( resourcemap == null )
- {
+ public static void addResourceRequest( final WikiContext ctx, final String type, final String resource ) {
+ HashMap< String, Vector< String > > resourcemap = ( HashMap< String, Vector< String > > ) ctx.getVariable( RESOURCE_INCLUDES );
+ if( resourcemap == null ) {
resourcemap = new HashMap<>();
}
- Vector<String> resources = resourcemap.get( type );
-
- if( resources == null )
- {
+ Vector< String > resources = resourcemap.get( type );
+ if( resources == null ) {
resources = new Vector<>();
}
String resourceString = null;
-
- if( type.equals(RESOURCE_SCRIPT) )
- {
- resourceString = "<script type='text/javascript' src='"+resource+"'></script>";
- }
- else if( type.equals(RESOURCE_STYLESHEET) )
- {
- resourceString = "<link rel='stylesheet' type='text/css' href='"+resource+"' />";
- }
- else if( type.equals(RESOURCE_INLINECSS) )
- {
- resourceString = "<style type='text/css'>\n"+resource+"\n</style>\n";
- }
- else if( type.equals(RESOURCE_JSFUNCTION) )
- {
- resourceString = resource;
- }
- else if( type.equals(RESOURCE_HTTPHEADER) )
- {
+ switch( type ) {
+ case RESOURCE_SCRIPT:
+ resourceString = "<script type='text/javascript' src='" + resource + "'></script>";
+ break;
+ case RESOURCE_STYLESHEET:
+ resourceString = "<link rel='stylesheet' type='text/css' href='" + resource + "' />";
+ break;
+ case RESOURCE_INLINECSS:
+ resourceString = "<style type='text/css'>\n" + resource + "\n</style>\n";
+ break;
+ case RESOURCE_JSFUNCTION:
+ case RESOURCE_HTTPHEADER:
resourceString = resource;
+ break;
}
- if( resourceString != null )
- {
+ if( resourceString != null ) {
resources.add( resourceString );
}
- log.debug("Request to add a resource: "+resourceString);
+ log.debug( "Request to add a resource: " + resourceString );
resourcemap.put( type, resources );
ctx.setVariable( RESOURCE_INCLUDES, resourcemap );
}
/**
- * Returns resource requests for a particular type. If there are no resources,
- * returns an empty array.
+ * Returns resource requests for a particular type. If there are no resources, returns an empty array.
*
* @param ctx WikiContext
* @param type The resource request type
* @return a String array for the resource requests
*/
-
@SuppressWarnings("unchecked")
- public static String[] getResourceRequests( WikiContext ctx, String type )
- {
- HashMap<String,Vector<String>> hm = (HashMap<String,Vector<String>>) ctx.getVariable( RESOURCE_INCLUDES );
-
- if( hm == null ) return new String[0];
-
- Vector<String> resources = hm.get( type );
-
- if( resources == null ) return new String[0];
+ public static String[] getResourceRequests( final WikiContext ctx, final String type ) {
+ final HashMap< String, Vector< String > > hm = ( HashMap< String, Vector< String > > ) ctx.getVariable( RESOURCE_INCLUDES );
+ if( hm == null ) {
+ return new String[0];
+ }
- String[] res = new String[resources.size()];
+ final Vector<String> resources = hm.get( type );
+ if( resources == null ){
+ return new String[0];
+ }
+ final String[] res = new String[resources.size()];
return resources.toArray( res );
}
@@ -781,18 +672,12 @@ public class TemplateManager extends ModuleManager {
* @return the array of types requested
*/
@SuppressWarnings("unchecked")
- public static String[] getResourceTypes( WikiContext ctx )
- {
+ public static String[] getResourceTypes( final WikiContext ctx ) {
String[] res = new String[0];
-
- if( ctx != null )
- {
- HashMap<String,String> hm = (HashMap<String,String>) ctx.getVariable( RESOURCE_INCLUDES );
-
- if( hm != null )
- {
- Set<String> keys = hm.keySet();
-
+ if( ctx != null ) {
+ final HashMap< String, String > hm = ( HashMap< String, String > ) ctx.getVariable( RESOURCE_INCLUDES );
+ if( hm != null ) {
+ final Set< String > keys = hm.keySet();
res = keys.toArray( res );
}
}
@@ -801,14 +686,12 @@ public class TemplateManager extends ModuleManager {
}
/**
- * Returns an empty collection, since at the moment the TemplateManager
- * does not manage any modules.
+ * Returns an empty collection, since at the moment the TemplateManager does not manage any modules.
*
* @return {@inheritDoc}
*/
@Override
- public Collection< WikiModuleInfo > modules()
- {
+ public Collection< WikiModuleInfo > modules() {
return new ArrayList<>();
}
@@ -817,7 +700,8 @@ public class TemplateManager extends ModuleManager {
* {@inheritDoc}
*/
@Override
- public WikiModuleInfo getModuleInfo(String moduleName) {
+ public WikiModuleInfo getModuleInfo( final String moduleName ) {
return null;
}
+
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiCommand.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiCommand.java
index 84fc2f1..1f22b44 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiCommand.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiCommand.java
@@ -18,23 +18,19 @@
*/
package org.apache.wiki.ui;
-import java.security.Permission;
-
import org.apache.wiki.auth.permissions.AllPermission;
import org.apache.wiki.auth.permissions.WikiPermission;
+import java.security.Permission;
+
/**
- * <p>Defines Commands for wiki-wide operations such as creating groups, editing
- * preferences and profiles, and logging in/out. WikiCommands can be combined
- * with Strings (representing the name of a wiki instance) to produce
- * targeted Commands.</p>
- * <p>This class is not <code>final</code>; it may be extended in
- * the future.</p>
+ * <p>Defines Commands for wiki-wide operations such as creating groups, editing preferences and profiles, and logging in/out.
+ * WikiCommands can be combined with Strings (representing the name of a wiki instance) to produce targeted Commands.</p>
+ *
* @see org.apache.wiki.WikiEngine#getApplicationName()
* @since 2.4.22
*/
-public final class WikiCommand extends AbstractCommand
-{
+public final class WikiCommand extends AbstractCommand {
public static final Command CREATE_GROUP
= new WikiCommand( "createGroup", "%uNewGroup.jsp", "NewGroupContent.jsp", null, WikiPermission.CREATE_GROUPS_ACTION );
@@ -71,31 +67,25 @@ public final class WikiCommand extends AbstractCommand
private final Permission m_permission;
/**
- * Constructs a new Command with a specified wiki context, URL pattern,
- * type, and content template. The WikiPage for this action is initialized
- * to <code>null</code>.
+ * Constructs a new Command with a specified wiki context, URL pattern, type, and content template. The WikiPage for this action is
+ * initialized to <code>null</code>.
+ *
* @param requestContext the request context
* @param urlPattern the URL pattern
- * @param type the type
* @param contentTemplate the content template; may be <code>null</code>
* @param action The action
- * @throws IllegalArgumentException if the request content, URL pattern, or
- * type is <code>null</code>
+ * @throws IllegalArgumentException if the request content, URL pattern, or type is <code>null</code>
*/
- private WikiCommand( String requestContext,
- String urlPattern,
- String contentTemplate,
- String target,
- String action )
- {
+ private WikiCommand( final String requestContext,
+ final String urlPattern,
+ final String contentTemplate,
+ final String target,
+ final String action ) {
super( requestContext, urlPattern, contentTemplate, target );
m_action = action;
- if ( target == null || m_action == null )
- {
+ if ( target == null || m_action == null ) {
m_permission = null;
- }
- else
- {
+ } else {
m_permission = new WikiPermission( target, action );
}
}
@@ -107,28 +97,22 @@ public final class WikiCommand extends AbstractCommand
* @param urlPattern
* @param contentTemplate
*/
- private WikiCommand( String requestContext,
- String urlPattern,
- String contentTemplate,
- String target )
- {
+ private WikiCommand( final String requestContext, final String urlPattern, final String contentTemplate, final String target ) {
super( requestContext, urlPattern, contentTemplate, target );
m_action = null;
-
m_permission = new AllPermission( target );
}
+
/**
- * Creates and returns a targeted Command by combining a wiki
- * (a String) with this Command. The supplied <code>target</code>
+ * Creates and returns a targeted Command by combining a wiki (a String) with this Command. The supplied <code>target</code>
* object must be non-<code>null</code> and of type String.
+ *
* @param target the name of the wiki to combine into the current Command
* @return the new targeted command
* @throws IllegalArgumentException if the target is not of the correct type
*/
- public Command targetedCommand( Object target )
- {
- if ( !( target != null && target instanceof String ) )
- {
+ public Command targetedCommand( final Object target ) {
+ if ( !( target instanceof String ) ) {
throw new IllegalArgumentException( "Target must non-null and of type String." );
}
return new WikiCommand( getRequestContext(), getURLPattern(), getContentTemplate(), (String)target, m_action );
@@ -136,18 +120,18 @@ public final class WikiCommand extends AbstractCommand
/**
* Always returns the "friendly" JSP name.
+ *
* @see org.apache.wiki.ui.Command#getName()
*/
- public String getName()
- {
+ public String getName() {
return getJSPFriendlyName();
}
/**
* @see org.apache.wiki.ui.Command#requiredPermission()
*/
- public Permission requiredPermission()
- {
+ public Permission requiredPermission() {
return m_permission;
}
+
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiJSPFilter.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiJSPFilter.java
index 7dee58c..d7d1fe2 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiJSPFilter.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiJSPFilter.java
@@ -48,23 +48,17 @@ import java.nio.charset.Charset;
/**
- * This filter goes through the generated page response prior and
- * places requested resources at the appropriate inclusion markers.
- * This is done to let dynamic content (e.g. plugins, editors)
- * include custom resources, even after the HTML head section is
- * in fact built. This filter is typically the last filter to execute,
- * and it <em>must</em> run after servlet or JSP code that performs
+ * This filter goes through the generated page response prior and places requested resources at the appropriate inclusion markers.
+ * This is done to let dynamic content (e.g. plugins, editors) include custom resources, even after the HTML head section is
+ * in fact built. This filter is typically the last filter to execute, and it <em>must</em> run after servlet or JSP code that performs
* redirections or sends error codes (such as access control methods).
* <p>
- * Inclusion markers are placed by the IncludeResourcesTag; the
- * default content templates (see .../templates/default/commonheader.jsp)
- * are configured to do this. As an example, a JavaScript resource marker
- * is added like this:
+ * Inclusion markers are placed by the IncludeResourcesTag; the default content templates (see .../templates/default/commonheader.jsp)
+ * are configured to do this. As an example, a JavaScript resource marker is added like this:
* <pre>
* <wiki:IncludeResources type="script"/>
* </pre>
- * Any code that requires special resources must register a resource
- * request with the TemplateManager. For example:
+ * Any code that requires special resources must register a resource request with the TemplateManager. For example:
* <pre>
* <wiki:RequestResource type="script" path="scripts/custom.js" />
* </pre>
@@ -83,32 +77,24 @@ public class WikiJSPFilter extends WikiServletFilter {
private boolean useEncoding;
/** {@inheritDoc} */
- public void init( FilterConfig config ) throws ServletException
- {
+ public void init( final FilterConfig config ) throws ServletException {
super.init( config );
m_wiki_encoding = m_engine.getWikiProperties().getProperty(WikiEngine.PROP_ENCODING);
- useEncoding = !(new Boolean(m_engine.getWikiProperties().getProperty(WikiEngine.PROP_NO_FILTER_ENCODING, "false").trim()).booleanValue());
+ useEncoding = !( Boolean.valueOf( m_engine.getWikiProperties().getProperty( WikiEngine.PROP_NO_FILTER_ENCODING, "false" ).trim() ).booleanValue() );
}
- public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
- throws ServletException, IOException
- {
- WatchDog w = m_engine.getCurrentWatchDog();
- try
- {
+ public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws ServletException, IOException {
+ final WatchDog w = m_engine.getCurrentWatchDog();
+ try {
NDC.push( m_engine.getApplicationName()+":"+((HttpServletRequest)request).getRequestURI() );
-
w.enterState("Filtering for URL "+((HttpServletRequest)request).getRequestURI(), 90 );
- HttpServletResponseWrapper responseWrapper;
-
- responseWrapper = new JSPWikiServletResponseWrapper( (HttpServletResponse)response, m_wiki_encoding, useEncoding);
+ final HttpServletResponseWrapper responseWrapper = new JSPWikiServletResponseWrapper( ( HttpServletResponse )response, m_wiki_encoding, useEncoding );
// fire PAGE_REQUESTED event
- String pagename = DefaultURLConstructor.parsePageFromURL( ( HttpServletRequest )request,
- Charset.forName( response.getCharacterEncoding() ) );
+ final String pagename = DefaultURLConstructor.parsePageFromURL( ( HttpServletRequest )request,
+ Charset.forName( response.getCharacterEncoding() ) );
fireEvent( WikiPageEvent.PAGE_REQUESTED, pagename );
-
super.doFilter( request, responseWrapper, chain );
// The response is now complete. Lets replace the markers now.
@@ -116,42 +102,32 @@ public class WikiJSPFilter extends WikiServletFilter {
// WikiContext is only available after doFilter! (That is after
// interpreting the jsp)
- try
- {
+ try {
w.enterState( "Delivering response", 30 );
- WikiContext wikiContext = getWikiContext( request );
- String r = filter( wikiContext, responseWrapper );
-
- if (useEncoding)
- {
- OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(),
- response.getCharacterEncoding());
- out.write(r);
+ final WikiContext wikiContext = getWikiContext( request );
+ final String r = filter( wikiContext, responseWrapper );
+
+ if( useEncoding ) {
+ final OutputStreamWriter out = new OutputStreamWriter( response.getOutputStream(), response.getCharacterEncoding() );
+ out.write( r );
out.flush();
out.close();
- }
- else
- {
+ } else {
response.getWriter().write(r);
}
// Clean up the UI messages and loggers
- if( wikiContext != null )
- {
+ if( wikiContext != null ) {
wikiContext.getWikiSession().clearMessages();
}
// fire PAGE_DELIVERED event
fireEvent( WikiPageEvent.PAGE_DELIVERED, pagename );
- }
- finally
- {
+ } finally {
w.exitState();
}
- }
- finally
- {
+ } finally {
w.exitState();
NDC.pop();
NDC.remove();
@@ -165,34 +141,25 @@ public class WikiJSPFilter extends WikiServletFilter {
* @param response The source string
* @return The modified string with all the insertions in place.
*/
- private String filter(WikiContext wikiContext, HttpServletResponse response )
- {
+ private String filter( final WikiContext wikiContext, final HttpServletResponse response ) {
String string = response.toString();
- if( wikiContext != null )
- {
- String[] resourceTypes = TemplateManager.getResourceTypes( wikiContext );
-
- for( int i = 0; i < resourceTypes.length; i++ )
- {
- string = insertResources( wikiContext, string, resourceTypes[i] );
+ if( wikiContext != null ) {
+ final String[] resourceTypes = TemplateManager.getResourceTypes( wikiContext );
+ for( final String resourceType : resourceTypes ) {
+ string = insertResources( wikiContext, string, resourceType );
}
- //
// Add HTTP header Resource Requests
- //
- String[] headers = TemplateManager.getResourceRequests( wikiContext,
- TemplateManager.RESOURCE_HTTPHEADER );
+ final String[] headers = TemplateManager.getResourceRequests( wikiContext, TemplateManager.RESOURCE_HTTPHEADER );
- for( int i = 0; i < headers.length; i++ )
- {
- String key = headers[i];
+ for( final String header : headers ) {
+ String key = header;
String value = "";
- int split = headers[i].indexOf(':');
- if( split > 0 && split < headers[i].length()-1 )
- {
- key = headers[i].substring( 0, split );
- value = headers[i].substring( split+1 );
+ final int split = header.indexOf( ':' );
+ if( split > 0 && split < header.length() - 1 ) {
+ key = header.substring( 0, split );
+ value = header.substring( split + 1 );
}
response.addHeader( key.trim(), value.trim() );
@@ -203,48 +170,35 @@ public class WikiJSPFilter extends WikiServletFilter {
}
/**
- * Inserts whatever resources
- * were requested by any plugins or other components for this particular
- * type.
+ * Inserts whatever resources were requested by any plugins or other components for this particular type.
*
* @param wikiContext The usual processing context
* @param string The source string
* @param type Type identifier for insertion
* @return The filtered string.
*/
- private String insertResources(WikiContext wikiContext, String string, String type )
- {
- if( wikiContext == null )
- {
+ private String insertResources( final WikiContext wikiContext, final String string, final String type ) {
+ if( wikiContext == null ) {
return string;
}
- String marker = TemplateManager.getMarker( wikiContext, type );
- int idx = string.indexOf( marker );
-
- if( idx == -1 )
- {
+ final String marker = TemplateManager.getMarker( wikiContext, type );
+ final int idx = string.indexOf( marker );
+ if( idx == -1 ) {
return string;
}
log.debug("...Inserting...");
- String[] resources = TemplateManager.getResourceRequests( wikiContext, type );
+ final String[] resources = TemplateManager.getResourceRequests( wikiContext, type );
+ final StringBuilder concat = new StringBuilder( resources.length * 40 );
- StringBuilder concat = new StringBuilder( resources.length * 40 );
-
- for( int i = 0; i < resources.length; i++ )
- {
- log.debug("...:::"+resources[i]);
- concat.append( resources[i] );
+ for( final String resource : resources ) {
+ log.debug( "...:::" + resource );
+ concat.append( resource );
}
- string = TextUtil.replaceString( string,
- idx,
- idx+marker.length(),
- concat.toString() );
-
- return string;
+ return TextUtil.replaceString( string, idx, idx + marker.length(), concat.toString() );
}
/**
@@ -259,108 +213,89 @@ public class WikiJSPFilter extends WikiServletFilter {
private HttpServletResponse m_response;
private boolean useEncoding;
- /**
- * How large the initial buffer should be. This should be tuned to achieve
- * a balance in speed and memory consumption.
- */
+ /** How large the initial buffer should be. This should be tuned to achieve a balance in speed and memory consumption. */
private static final int INIT_BUFFER_SIZE = 0x8000;
-
- public JSPWikiServletResponseWrapper( HttpServletResponse r, final String wiki_encoding, boolean useEncoding)
- throws UnsupportedEncodingException {
- super(r);
- m_output = new ByteArrayOutputStream(INIT_BUFFER_SIZE);
- m_servletOut = new ByteArrayServletOutputStream(m_output);
- m_writer = new PrintWriter(new OutputStreamWriter(m_servletOut, wiki_encoding), true);
+ public JSPWikiServletResponseWrapper( final HttpServletResponse r, final String wikiEncoding, final boolean useEncoding ) throws UnsupportedEncodingException {
+ super( r );
+ m_output = new ByteArrayOutputStream( INIT_BUFFER_SIZE );
+ m_servletOut = new ByteArrayServletOutputStream( m_output );
+ m_writer = new PrintWriter( new OutputStreamWriter( m_servletOut, wikiEncoding ), true );
this.useEncoding = useEncoding;
m_response = r;
}
/**
- * Returns a writer for output; this wraps the internal buffer
- * into a PrintWriter.
+ * Returns a writer for output; this wraps the internal buffer into a PrintWriter.
*/
- public PrintWriter getWriter()
- {
+ public PrintWriter getWriter() {
return m_writer;
}
- public ServletOutputStream getOutputStream()
- {
+ public ServletOutputStream getOutputStream() {
return m_servletOut;
}
- public void flushBuffer() throws IOException
- {
+ public void flushBuffer() throws IOException {
m_writer.flush();
super.flushBuffer();
}
- class ByteArrayServletOutputStream extends ServletOutputStream
- {
+ class ByteArrayServletOutputStream extends ServletOutputStream {
+
ByteArrayOutputStream m_buffer;
- public ByteArrayServletOutputStream(ByteArrayOutputStream byteArrayOutputStream)
- {
+ public ByteArrayServletOutputStream( final ByteArrayOutputStream byteArrayOutputStream ) {
super();
m_buffer = byteArrayOutputStream;
}
+ //
+ /**{@inheritDoc} */
@Override
- public void write(int aInt) throws IOException
- {
+ public void write( final int aInt ) {
m_buffer.write( aInt );
}
- @Override
- public boolean isReady()
- {
+ /**{@inheritDoc} */
+ @Override
+ public boolean isReady() {
return false;
}
- @Override
- public void setWriteListener(WriteListener writeListener)
- {
+ /**{@inheritDoc} */
+ @Override
+ public void setWriteListener( final WriteListener writeListener ) {
}
}
- /**
- * Returns whatever was written so far into the Writer.
- */
- public String toString()
- {
- try
- {
+ /** Returns whatever was written so far into the Writer. */
+ public String toString() {
+ try {
flushBuffer();
- } catch (IOException e)
- {
+ } catch( final IOException e ) {
log.error( e );
return StringUtils.EMPTY;
}
- try
- {
- if (useEncoding)
- {
- return m_output.toString(m_response.getCharacterEncoding());
+ try {
+ if( useEncoding ) {
+ return m_output.toString( m_response.getCharacterEncoding() );
}
return m_output.toString();
- }
- catch( UnsupportedEncodingException e )
- {
+ } catch( final UnsupportedEncodingException e ) {
log.error( e );
return StringUtils.EMPTY;
}
}
- }
+ }
// events processing .......................................................
-
/**
* Fires a WikiPageEvent of the provided type and page name
* to all registered listeners of the current WikiEngine.
@@ -369,11 +304,9 @@ public class WikiJSPFilter extends WikiServletFilter {
* @param type the event type to be fired
* @param pagename the wiki page name as a String
*/
- protected final void fireEvent( int type, String pagename )
- {
- if ( WikiEventManager.isListening(m_engine) )
- {
- WikiEventManager.fireEvent(m_engine,new WikiPageEvent(m_engine,type,pagename));
+ protected final void fireEvent( final int type, final String pagename ) {
+ if( WikiEventManager.isListening( m_engine ) ) {
+ WikiEventManager.fireEvent( m_engine, new WikiPageEvent( m_engine, type, pagename ) );
}
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiRequestWrapper.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiRequestWrapper.java
index 1d72c58..a0a9f48 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiRequestWrapper.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiRequestWrapper.java
@@ -18,115 +18,90 @@
*/
package org.apache.wiki.ui;
-import java.security.Principal;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
import org.apache.wiki.WikiEngine;
import org.apache.wiki.WikiSession;
import org.apache.wiki.auth.SessionMonitor;
import org.apache.wiki.auth.authorize.Role;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import java.security.Principal;
+
/**
- * Servlet request wrapper that encapsulates an incoming HTTP request and
- * overrides its security methods so that the request returns JSPWiki-specific
- * values.
+ * Servlet request wrapper that encapsulates an incoming HTTP request and overrides its security methods so that the request returns
+ * JSPWiki-specific values.
*
* @since 2.8
*/
-public class WikiRequestWrapper extends HttpServletRequestWrapper
-{
+public class WikiRequestWrapper extends HttpServletRequestWrapper {
+
private final WikiSession m_session;
/**
* Constructs a new wrapped request.
*
- * @param engine
- * the wiki engine
- * @param request
- * the request to wrap
+ * @param engine the wiki engine
+ * @param request the request to wrap
*/
- public WikiRequestWrapper(WikiEngine engine, HttpServletRequest request)
- {
- super(request);
+ public WikiRequestWrapper( final WikiEngine engine, final HttpServletRequest request ) {
+ super( request );
// Get and stash a reference to the current WikiSession
- m_session = SessionMonitor.getInstance(engine).find(request.getSession());
+ m_session = SessionMonitor.getInstance( engine ).find( request.getSession() );
}
/**
- * Returns the remote user for the HTTP request, taking into account both
- * container and JSPWiki custom authentication status. Specifically, if the
- * wrapped request contains a remote user, this method returns that remote
- * user. Otherwise, if the user's WikiSession is an authenticated session
- * (that is, {@link WikiSession#isAuthenticated()} returns <code>true</code>,
- * this method returns the name of the principal returned by
- * {@link WikiSession#getLoginPrincipal()}.
+ * Returns the remote user for the HTTP request, taking into account both container and JSPWiki custom authentication status.
+ * Specifically, if the wrapped request contains a remote user, this method returns that remote user. Otherwise, if the user's
+ * WikiSession is an authenticated session (that is, {@link WikiSession#isAuthenticated()} returns <code>true</code>,
+ * this method returns the name of the principal returned by {@link WikiSession#getLoginPrincipal()}.
*/
- public String getRemoteUser()
- {
- if (super.getRemoteUser() != null)
- {
+ public String getRemoteUser() {
+ if( super.getRemoteUser() != null ) {
return super.getRemoteUser();
}
- if (m_session.isAuthenticated())
- {
+ if( m_session.isAuthenticated() ) {
return m_session.getLoginPrincipal().getName();
}
return null;
}
/**
- * Returns the user principal for the HTTP request, taking into account both
- * container and JSPWiki custom authentication status. Specifically, if the
- * wrapped request contains a user principal, this method returns that
- * principal. Otherwise, if the user's WikiSession is an authenticated
- * session (that is, {@link WikiSession#isAuthenticated()} returns
- * <code>true</code>, this method returns the value of
- * {@link WikiSession#getLoginPrincipal()}.
+ * Returns the user principal for the HTTP request, taking into account both container and JSPWiki custom authentication status.
+ * Specifically, if the wrapped request contains a user principal, this method returns that principal. Otherwise, if the user's
+ * WikiSession is an authenticated session (that is, {@link WikiSession#isAuthenticated()} returns
+ * <code>true</code>, this method returns the value of {@link WikiSession#getLoginPrincipal()}.
*/
- public Principal getUserPrincipal()
- {
- if (super.getUserPrincipal() != null)
- {
+ public Principal getUserPrincipal() {
+ if( super.getUserPrincipal() != null ) {
return super.getUserPrincipal();
}
- if (m_session.isAuthenticated())
- {
+ if( m_session.isAuthenticated() ) {
return m_session.getLoginPrincipal();
}
return null;
}
/**
- * Determines whether the current user possesses a supplied role, taking
- * into account both container and JSPWIki custom authentication status.
- * Specifically, if the wrapped request shows that the user possesses the
- * role, this method returns <code>true</code>. If not, this method
- * iterates through the built-in Role objects (<em>e.g.</em>, ANONYMOUS,
- * ASSERTED, AUTHENTICATED) returned by {@link WikiSession#getRoles()} and
- * checks to see if any of these principals' names match the supplied role.
+ * Determines whether the current user possesses a supplied role, taking into account both container and JSPWIki custom authentication
+ * status. Specifically, if the wrapped request shows that the user possesses the role, this method returns <code>true</code>. If not,
+ * this method iterates through the built-in Role objects (<em>e.g.</em>, ANONYMOUS, ASSERTED, AUTHENTICATED) returned by
+ * {@link WikiSession#getRoles()} and checks to see if any of these principals' names match the supplied role.
*/
- public boolean isUserInRole(String role)
- {
- boolean hasContainerRole = super.isUserInRole(role);
- if (hasContainerRole)
- {
+ public boolean isUserInRole( final String role ) {
+ final boolean hasContainerRole = super.isUserInRole(role);
+ if( hasContainerRole ) {
return true;
}
// Iterate through all of the built-in roles and look for a match
- Principal[] principals = m_session.getRoles();
- for (int i = 0; i < principals.length; i++)
- {
- if (principals[i] instanceof Role)
- {
- Role principal = (Role) principals[i];
- if (Role.isBuiltInRole(principal) && principal.getName().equals(role))
- {
+ final Principal[] principals = m_session.getRoles();
+ for( final Principal value : principals ) {
+ if( value instanceof Role ) {
+ final Role principal = ( Role )value;
+ if( Role.isBuiltInRole( principal ) && principal.getName().equals( role ) ) {
return true;
}
}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiServletFilter.java b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiServletFilter.java
index 4d8e08f..33c9454 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiServletFilter.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/ui/WikiServletFilter.java
@@ -154,18 +154,18 @@ public class WikiServletFilter implements Filter {
*/
protected WikiContext getWikiContext( final ServletRequest request ) {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
- return (WikiContext) httpRequest.getAttribute( WikiContext.ATTR_CONTEXT );
+ return ( WikiContext )httpRequest.getAttribute( WikiContext.ATTR_CONTEXT );
}
/**
* Determines whether the request has been previously wrapped with a WikiRequestWrapper.
* We find the wrapper by recursively unwrapping successive request wrappers, if they have been supplied.
+ *
* @param request the current HTTP request
- * @return <code>true</code> if the request has previously been wrapped;
- * <code>false</code> otherwise
+ * @return <code>true</code> if the request has previously been wrapped; <code>false</code> otherwise
*/
private boolean isWrapped( ServletRequest request ) {
- while( !(request instanceof WikiRequestWrapper ) && request != null && request instanceof HttpServletRequestWrapper ) {
+ while( !(request instanceof WikiRequestWrapper ) && request instanceof HttpServletRequestWrapper ) {
request = ( ( HttpServletRequestWrapper ) request ).getRequest();
}
return request instanceof WikiRequestWrapper;