diff --git a/LICENSE.txt b/LICENSE.txt index 87e037cacb..aea26f2bd7 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -2,11 +2,11 @@ LICENSE.txt - Roller licensing terms Roller is licensed under the Apache License Version 2.0, see below. -Roller also uses the JDOM XML parser library, licensed under the +Roller also uses the JDOM XML parser library, licensed under the terms of the JDOM license (a BSD-like license listed at end of this file). And Roller contains some snippets of code from the Blojsom and Pebble -blog servers, which are both licensed under the terms of the BSD license +blog servers, which are both licensed under the terms of the BSD license (http://www.opensource.org/licenses/bsd-license.php). @@ -219,33 +219,33 @@ blog servers, which are both licensed under the terms of the BSD license The JDOM License Copyright (C) 2000-2002 Jason Hunter & Brett McLaughlin. All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions, and the disclaimer that follows - these conditions in the documentation and/or other materials + notice, this list of conditions, and the disclaimer that follows + these conditions in the documentation and/or other materials provided with the distribution. 3. The name "JDOM" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact . - + 4. Products derived from this software may not be called "JDOM", nor may "JDOM" appear in their name, without prior written permission from the JDOM Project Management . - - In addition, we request (but do not require) that you include in the - end-user documentation provided with the redistribution and/or in the + + In addition, we request (but do not require) that you include in the + end-user documentation provided with the redistribution and/or in the software itself an acknowledgement equivalent to the following: "This product includes software developed by the JDOM Project (http://www.jdom.org/)." - Alternatively, the acknowledgment may be graphical using the logos + Alternatively, the acknowledgment may be graphical using the logos available at http://www.jdom.org/images/logos. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED @@ -261,8 +261,8 @@ blog servers, which are both licensed under the terms of the BSD license OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - This software consists of voluntary contributions made by many - individuals on behalf of the JDOM Project and was originally + This software consists of voluntary contributions made by many + individuals on behalf of the JDOM Project and was originally created by Jason Hunter and Brett McLaughlin . For more information on the JDOM Project, please see . diff --git a/NOTICE.txt b/NOTICE.txt index 4b8c2f9645..88ce0b90a9 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -5,8 +5,8 @@ COPYRIGHT NOTICES This product includes: -* Software developed by the Apache Software Foundation (http://www.apache.org) - Copyright 2006 The Apache Software Foundation. +* Software developed by the Apache Software Foundation (http://www.apache.org) + Copyright 2006 The Apache Software Foundation. * Software developed by the ROME project Copyright 2003-2006 Sun Microsystems, Inc. @@ -20,7 +20,7 @@ This product includes: * Snippets of code from the Pebble blog server Copyright 2003 Simon Brown, All rights reserved. -* Code written by Sun Microsystems, Inc. +* Code written by Sun Microsystems, Inc. Copyright 2005 Sun Microsystems, Inc. * Code written by Dave Johnson for RSS and Atom in Action @@ -30,7 +30,7 @@ This product includes: Copyright 2002-2003 by OpenSymphony * A Struts LinkTag and LinkParamTag by BSquare Software - Copyright 2001 Bsquare Projects + Copyright 2001 Bsquare Projects * The Xinha WYSIWYG editor, which includes HTMLArea Copyright dynarch.com, 2003-2004 @@ -52,11 +52,11 @@ OTHER NOTICES CREDITS -Roller committers (in chronological order): +Roller committers (in chronological order): David M Johnson -Lance Lanvandowska -Matt Raible +Lance Lanvandowska +Matt Raible Mindaguas Idzelis (retired) Jaap Van Der Molen (retired) Anil Gangolli diff --git a/README.txt b/README.txt index ed5a68440a..efd501f48c 100644 --- a/README.txt +++ b/README.txt @@ -35,7 +35,7 @@ indicated above, the following command will build and run all unit tests: mvn install After doing that, you should find the newly built Roller webapp, suitable -for use with Tomcat in weblogger-web/target/roller. +for use with Tomcat in weblogger-web/target/roller. To build Roller release files, you do this: @@ -47,7 +47,7 @@ To build Roller release files, you do this: mvn -Dtomcat=true install cd .. -After that, you'll find Roller distribution files in weblogger-assembly/target. +After that, you'll find Roller distribution files in weblogger-assembly/target. The Tomcat specific release files will have 'for-tomcat' in their names. See the script build-tomcat-release.sh to see the sequence of commands used @@ -58,11 +58,11 @@ to create Roller releases for Tomcat. BUILDING FOR JAVA EE 6 The Tomcat build includes extra things that are not needed on a full Java EE -application server. In fact, the Tomcat release won't work on some Java EE -servers. If we leave those extra things out, Roller can run on most Java EE +application server. In fact, the Tomcat release won't work on some Java EE +servers. If we leave those extra things out, Roller can run on most Java EE servers. -If you add a 'javaee' flag to the Roller build invocation, you can create +If you add a 'javaee' flag to the Roller build invocation, you can create Roller release files that will work on a Java EE 6 app server. mvn clean @@ -76,10 +76,10 @@ Roller release files that will work on a Java EE 6 app server. mvn -Djavaee=true install cd .. -When that finishes, you will find Roller distribution files in -weblogger-assembly/target. The Java EE specific release files will have +When that finishes, you will find Roller distribution files in +weblogger-assembly/target. The Java EE specific release files will have 'for-javaee' in their names. - + See the script build-javaee-release.sh to see the sequence of commands used to create Roller releases for Java EE. @@ -88,7 +88,7 @@ to create Roller releases for Java EE. BUILDING FOR JBOSS 6 JBoss 6 is a Java EE server, but due to differences in JNDI naming, it needs -a separate build. If you add a 'jboss' flag to the Roller build invocation, +a separate build. If you add a 'jboss' flag to the Roller build invocation, you can create Roller release files that will work on a JBoss 6 app server. mvn clean @@ -102,10 +102,10 @@ you can create Roller release files that will work on a JBoss 6 app server. mvn -Djboss=true install cd .. -When that finishes, you will find Roller distribution files in -weblogger-assembly/target. The Java EE specific release files will have +When that finishes, you will find Roller distribution files in +weblogger-assembly/target. The Java EE specific release files will have 'for-jboss' in their names. - + See the script build-jbossee-release.sh to see the sequence of commands used to create Roller releases for JBoss. @@ -115,7 +115,7 @@ NOTES 1) Set MAVEN_OPTS to include your preferred server -If you always build for one server, then you might wish to define +If you always build for one server, then you might wish to define MAVEN_OPTS to include your preferred server flag, for example: export MAVEN_OPTS=${MAVEN_OPTS} -Dtomcat=true diff --git a/planet-business/pom.xml b/planet-business/pom.xml index b3c71bab91..eee17d02a8 100644 --- a/planet-business/pom.xml +++ b/planet-business/pom.xml @@ -28,7 +28,7 @@ - + org.apache.roller roller-core ${roller.version} @@ -198,7 +198,7 @@ once -javaagent:${user.home}/.m2/repository/org/apache/openjpa/openjpa/2.0.1/openjpa-2.0.1.jar - + catalina.base @@ -357,7 +357,7 @@ jboss - + java:/RollerDS @@ -368,12 +368,12 @@ !jboss - + jdbc/rollerdb - + openjpa @@ -381,7 +381,7 @@ !javaee - + org.apache.openjpa @@ -418,7 +418,7 @@ - + diff --git a/planet-business/src/main/java/org/apache/roller/planet/PlanetException.java b/planet-business/src/main/java/org/apache/roller/planet/PlanetException.java index 3eb5c2f26a..e2f13852a1 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/PlanetException.java +++ b/planet-business/src/main/java/org/apache/roller/planet/PlanetException.java @@ -25,13 +25,13 @@ * A base exception class for Roller Planet. */ public class PlanetException extends RollerException { - - + + public PlanetException() { super(); } - - + + /** * Construct PlanetException with message string. * @@ -40,8 +40,8 @@ public PlanetException() { public PlanetException(String s) { super(s); } - - + + /** * Construct PlanetException, wrapping existing throwable. * @@ -51,8 +51,8 @@ public PlanetException(String s) { public PlanetException(String s, Throwable t) { super(s, t); } - - + + /** * Construct PlanetException, wrapping existing throwable. * @@ -61,5 +61,5 @@ public PlanetException(String s, Throwable t) { public PlanetException(Throwable t) { super(t); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/AbstractManagerImpl.java b/planet-business/src/main/java/org/apache/roller/planet/business/AbstractManagerImpl.java index d8c60536da..cdd8449645 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/AbstractManagerImpl.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/AbstractManagerImpl.java @@ -24,19 +24,19 @@ * implemenations can just override them if needed. */ public abstract class AbstractManagerImpl implements Manager { - + public void initialize() throws InitializationException { // no-op } - - + + public void release() { // no-op } - - + + public void shutdown() { // no-op } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/BootstrapException.java b/planet-business/src/main/java/org/apache/roller/planet/business/BootstrapException.java index 4144b461ea..eff086e150 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/BootstrapException.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/BootstrapException.java @@ -25,13 +25,13 @@ * Exception generated from Weblogger bootstrapping process. */ public class BootstrapException extends PlanetException { - + public BootstrapException(String msg) { super(msg); } - + public BootstrapException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/DatabaseProvider.java b/planet-business/src/main/java/org/apache/roller/planet/business/DatabaseProvider.java index b8298e83d9..36c4228eff 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/DatabaseProvider.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/DatabaseProvider.java @@ -36,9 +36,9 @@ /** * Encapsulates Roller database configuration via JDBC properties or JNDI. * - *

To keep the logs from filling up with DB connection errors, will only + *

To keep the logs from filling up with DB connection errors, will only * attempt to connect once.

- * + * *

Keeps startup exception and log so we can present useful debugging * information to whoever is installing Roller Planet.

* @@ -47,10 +47,10 @@ *
  * # Specify database configuration type of 'jndi' or 'jdbc'
  * database.configurationType=jndi
- * 
+ *
  * # For database configuration type 'jndi',this will be used
  * database.jndi.name=jdbc/rollerdb
- * 
+ *
  * # For database configuration type of 'jdbc', you MUST override these
  * database.jdbc.driverClass=
  * database.jdbc.connectionURL=
@@ -59,31 +59,31 @@
  * 
*/ public class DatabaseProvider { - + private static Log log = LogFactory.getLog(DatabaseProvider.class); public enum ConfigurationType {JNDI_NAME, JDBC_PROPERTIES;} private ConfigurationType type = ConfigurationType.JNDI_NAME; private List startupLog = new ArrayList(); - - private DataSource dataSource = null; - private String jndiName = null; - + + private DataSource dataSource = null; + private String jndiName = null; + private String jdbcDriverClass = null; private String jdbcConnectionURL = null; private String jdbcPassword = null; private String jdbcUsername = null; private Properties props = null; - - + + /** * Reads configuraiton, loads driver or locates data-source and attempts * to get test connecton so that we can fail early. - */ + */ public DatabaseProvider() throws StartupException { - - String connectionTypeString = - PlanetConfig.getProperty("database.configurationType"); + + String connectionTypeString = + PlanetConfig.getProperty("database.configurationType"); if ("jdbc".equals(connectionTypeString)) { type = ConfigurationType.JDBC_PROPERTIES; } @@ -92,7 +92,7 @@ public DatabaseProvider() throws StartupException { jdbcConnectionURL = PlanetConfig.getProperty("database.jdbc.connectionURL"); jdbcUsername = PlanetConfig.getProperty("database.jdbc.username"); jdbcPassword = PlanetConfig.getProperty("database.jdbc.password"); - + successMessage("SUCCESS: Got parameters. Using configuration type " + type); // If we're doing JDBC then attempt to load JDBC driver class @@ -104,63 +104,63 @@ public DatabaseProvider() throws StartupException { try { Class.forName(getJdbcDriverClass()); } catch (ClassNotFoundException ex) { - String errorMsg = + String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass()+ "]. " +"Likely problem: JDBC driver jar missing from server classpath."; errorMessage(errorMsg); throw new StartupException(errorMsg, ex, startupLog); } successMessage("SUCCESS: loaded JDBC driver class [" +getJdbcDriverClass()+ "]"); - + if (getJdbcUsername() != null || getJdbcPassword() != null) { props = new Properties(); if (getJdbcUsername() != null) props.put("user", getJdbcUsername()); if (getJdbcPassword() != null) props.put("password", getJdbcPassword()); } - + // Else attempt to locate JNDI datasource - } else { + } else { String name = "java:comp/env/" + getJndiName(); successMessage("-- Using JNDI datasource name: " + name); try { InitialContext ic = new InitialContext(); dataSource = (DataSource)ic.lookup(name); } catch (NamingException ex) { - String errorMsg = + String errorMsg = "ERROR: cannot locate JNDI DataSource [" +name+ "]. " +"Likely problem: no DataSource or datasource is misconfigured."; errorMessage(errorMsg); throw new StartupException(errorMsg, ex, startupLog); - } + } successMessage("SUCCESS: located JNDI DataSource [" +name+ "]"); } - + // So far so good. Now, can we get a connection? - try { + try { Connection testcon = getConnection(); testcon.close(); } catch (Throwable t) { - String errorMsg = + String errorMsg = "ERROR: unable to obtain database connection. " +"Likely problem: bad connection parameters or database unavailable."; errorMessage(errorMsg); throw new StartupException(errorMsg, t, startupLog); } } - - + + private void successMessage(String msg) { startupLog.add(msg); log.info(msg); } - + private void errorMessage(String msg) { startupLog.add(msg); log.error(msg); } - - /** + + /** * List of success and error messages when class was first instantiated. **/ public List getStartupLog() { @@ -168,7 +168,7 @@ public List getStartupLog() { } /** - * Get database connection from data-source or driver manager, depending + * Get database connection from data-source or driver manager, depending * on which is configured. */ public Connection getConnection() throws SQLException { @@ -177,7 +177,7 @@ public Connection getConnection() throws SQLException { } else { return dataSource.getConnection(); } - } + } public ConfigurationType getType() { return type; diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/GuicePlanetProvider.java b/planet-business/src/main/java/org/apache/roller/planet/business/GuicePlanetProvider.java index b479b7e860..e4832fe2d7 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/GuicePlanetProvider.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/GuicePlanetProvider.java @@ -28,71 +28,71 @@ * A Guice specific implementation of a PlanetProvider. */ public class GuicePlanetProvider implements PlanetProvider { - + // Guice injector private final Injector injector; - + // maintain our own singleton instance of Planet private Planet planetInstance = null; - - + + /** - * Instantiate a new GuicePlanetProvider using default guice module + * Instantiate a new GuicePlanetProvider using default guice module * configured in PlanetConfig via 'guice.backend.module' property. */ public GuicePlanetProvider() { - + String moduleClassname = PlanetConfig.getProperty("guice.backend.module"); if(moduleClassname == null) { throw new NullPointerException("unable to lookup default guice module via property 'guice.backend.module'"); } - + try { Class moduleClass = Class.forName(moduleClassname); Module module = (Module)moduleClass.newInstance(); injector = Guice.createInjector(module); - } catch (Throwable e) { + } catch (Throwable e) { // Fatal misconfiguration, cannot recover throw new RuntimeException("Error instantiating backend module " + moduleClassname, e); } } - - + + /** * Instantiate a new GuicePlanetProvider using the given Guice module. * * @param moduleClassname The full classname of the Guice module to use. */ public GuicePlanetProvider(String moduleClassname) { - + if(moduleClassname == null) { throw new NullPointerException("moduleClassname cannot be null"); } - + try { Class moduleClass = Class.forName(moduleClassname); Module module = (Module)moduleClass.newInstance(); injector = Guice.createInjector(module); - } catch (Throwable e) { + } catch (Throwable e) { // Fatal misconfiguration, cannot recover throw new RuntimeException("Error instantiating backend module " + moduleClassname, e); } } - - + + /** * @inheritDoc */ public void bootstrap() { planetInstance = injector.getInstance(Planet.class); } - - + + /** * @inheritDoc */ public Planet getPlanet() { return planetInstance; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/InitializationException.java b/planet-business/src/main/java/org/apache/roller/planet/business/InitializationException.java index 619811a7ee..9da404adb6 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/InitializationException.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/InitializationException.java @@ -25,13 +25,13 @@ * Exception generated from Weblogger initialization process. */ public class InitializationException extends PlanetException { - + public InitializationException(String msg) { super(msg); } - + public InitializationException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/Manager.java b/planet-business/src/main/java/org/apache/roller/planet/business/Manager.java index e663bc2273..12ff7982d2 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/Manager.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/Manager.java @@ -25,22 +25,22 @@ * TODO: there should probably be a startup() method. */ public interface Manager { - + /** * Initialize the Manager. Called once after instantiation. */ public void initialize() throws InitializationException; - - + + /** * Release all resources associated with session. */ public void release(); - - + + /** * Cleanup for application shutdown. */ public void shutdown(); - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java b/planet-business/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java index 9d1fe0ce0c..26810c4ea7 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java @@ -31,117 +31,117 @@ * */ public class MultiPlanetURLStrategy implements URLStrategy { - - + + /** * Get root url for a given weblog. Optionally for a certain locale. */ public String getPlanetURL(String planet) { - + if(planet == null) { return null; } - + StringBuffer url = new StringBuffer(); - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + url.append(PlanetRuntimeConfig.getProperty("site.absoluteurl")); url.append("/").append(planet).append("/"); - + return url.toString(); } - - + + /** * Get url for a single weblog entry on a given weblog. */ public String getPlanetGroupURL(String planet, String group, int pageNum) { - + if(planet == null || group == null) { return null; } - + StringBuffer url = new StringBuffer(); - + url.append(getPlanetURL(planet)); url.append("group/").append(group).append("/"); - + if(pageNum > 0) { url.append("?page="); url.append(pageNum); } - + return url.toString(); } - - + + /** * Get url for a feed on a given weblog. */ public String getPlanetGroupFeedURL(String planet, String group, String format) { - + if(planet == null || group == null) { return null; } - + StringBuffer url = new StringBuffer(); - + url.append(getPlanetGroupURL(planet, group, -1)); url.append("feed/").append(format); - + return url.toString(); } - - + + /** * Get url for opml file on a given planet group. */ public String getPlanetGroupOpmlURL(String planet, String group) { - + if(planet == null || group == null) { return null; } - + StringBuffer url = new StringBuffer(); - + url.append(getPlanetGroupURL(planet, group, -1)); url.append("opml"); - + return url.toString(); } - - + + /** * Compose a map of key=value params into a query string. */ public String getQueryString(Map params) { - + if(params == null) { return null; } - + StringBuffer queryString = new StringBuffer(); - + for(Iterator keys = params.keySet().iterator(); keys.hasNext();) { String key = (String) keys.next(); String value = (String) params.get(key); - + if (queryString.length() == 0) { queryString.append("?"); } else { queryString.append("&"); } - + queryString.append(key); queryString.append("="); queryString.append(value); } - + return queryString.toString(); } - - + + /** * URL encode a string using UTF-8. */ @@ -154,8 +154,8 @@ public String encode(String str) { } return encodedStr; } - - + + /** * URL decode a string using UTF-8. */ @@ -168,5 +168,5 @@ public String decode(String str) { } return decodedStr; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/Planet.java b/planet-business/src/main/java/org/apache/roller/planet/business/Planet.java index 1087181b34..f4f25adfdc 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/Planet.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/Planet.java @@ -27,53 +27,53 @@ * The main entry point interface of the Roller business tier. */ public interface Planet { - + /** * Get PlanetManager associated with this Roller instance. */ public PlanetManager getPlanetManager(); - - + + /** * Get PropertiesManager. */ public PropertiesManager getPropertiesManager(); - - + + /** * Get the configured URLStrategy. */ public URLStrategy getURLStrategy(); - - + + /** * Get the configured FeedFetcher. */ public FeedFetcher getFeedFetcher(); - - + + /** * Flush object states. */ public void flush() throws PlanetException; - - + + /** * Initialize any resources necessary for this instance of Roller. */ public void initialize() throws InitializationException; - + /** * Release any resources associated with a session. */ public void release(); - - + + /** * Shutdown the application. */ public void shutdown(); - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/PlanetManager.java b/planet-business/src/main/java/org/apache/roller/planet/business/PlanetManager.java index 488483ee2c..3bb86ad760 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/PlanetManager.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/PlanetManager.java @@ -33,105 +33,105 @@ * Manages Planets, Groups, Subscriptions, and Entries. */ public interface PlanetManager extends Manager { - - + + public void savePlanet(Planet planet) throws PlanetException; - - + + public void deletePlanet(Planet planet) throws PlanetException; - - + + public Planet getPlanet(String handle) throws PlanetException; - - + + public Planet getPlanetById(String id) throws PlanetException; - - + + public List getPlanets() throws PlanetException; - - + + /** * Save new or update existing a group */ public void saveGroup(PlanetGroup sub) throws PlanetException; - - - /** - * Delete group and any subscriptions that are orphaned. + + + /** + * Delete group and any subscriptions that are orphaned. */ public void deleteGroup(PlanetGroup group) throws PlanetException; - - + + public PlanetGroup getGroup(Planet planet, String handle) throws PlanetException; - - + + /** * Get group by ID rather than handle. */ public PlanetGroup getGroupById(String id) throws PlanetException; - - + + /** * Save or update a subscription */ public void saveSubscription(Subscription sub) throws PlanetException; - - - /** - * Delete subscription, remove it from groups, cache, etc. + + + /** + * Delete subscription, remove it from groups, cache, etc. */ public void deleteSubscription(Subscription group) throws PlanetException; - - + + /** * Get subscription by feedUrl. */ public Subscription getSubscription(String feedUrl) throws PlanetException; - - + + /** * Get subscription by ID rather than feedUrl. */ public Subscription getSubscriptionById(String id) throws PlanetException; - - + + /** * Get all subscriptions. */ public List getSubscriptions() throws PlanetException; - - + + /** * Get total number of subscriptions. */ public int getSubscriptionCount() throws PlanetException; - - + + /** * Get top X subscriptions. */ public List getTopSubscriptions(int offset, int len) throws PlanetException; - - + + /** * Get top X subscriptions, restricted by group. */ - public List getTopSubscriptions(PlanetGroup group, int offset, int len) + public List getTopSubscriptions(PlanetGroup group, int offset, int len) throws PlanetException; - - + + /** * Save new or update existing entry */ public void saveEntry(SubscriptionEntry entry) throws PlanetException; - - - /** - * Delete entry. + + + /** + * Delete entry. */ public void deleteEntry(SubscriptionEntry entry) throws PlanetException; - - + + /** * Delete all entries for a subscription. * @@ -139,21 +139,21 @@ public List getTopSubscriptions(PlanetGroup group, int offset, int len) * @throws PlanetException If there is a problem doing the delete. */ public void deleteEntries(Subscription sub) throws PlanetException; - - + + /** * Lookup an entry by id. */ public SubscriptionEntry getEntryById(String id) throws PlanetException; - - + + /** * Get entries in a single feed as list of SubscriptionEntry objects. */ - public List getEntries(Subscription sub, int offset, int len) + public List getEntries(Subscription sub, int offset, int len) throws PlanetException; - - + + /** * Get Entries for a Group in reverse chonological order. * @@ -161,12 +161,12 @@ public List getEntries(Subscription sub, int offset, int len) * @param offset Offset into results (for paging) * @param len Maximum number of results to return (for paging) */ - public List getEntries(PlanetGroup group, int offset, int len) + public List getEntries(PlanetGroup group, int offset, int len) throws PlanetException; - - + + /** - * Get Entries for a Group in reverse chonological order, optionally + * Get Entries for a Group in reverse chonological order, optionally * constrained to a certain timeframe. * * @param group Restrict to entries from one group. @@ -175,10 +175,10 @@ public List getEntries(PlanetGroup group, int offset, int len) * @param offset Offset into results (for paging) * @param len Maximum number of results to return (for paging) */ - public List getEntries(PlanetGroup group, - Date startDate, + public List getEntries(PlanetGroup group, + Date startDate, Date endDate, - int offset, + int offset, int len) throws PlanetException; - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/PlanetProvider.java b/planet-business/src/main/java/org/apache/roller/planet/business/PlanetProvider.java index 7a169fa81b..76af2345f3 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/PlanetProvider.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/PlanetProvider.java @@ -23,16 +23,16 @@ * Provides access to a Planet instance. */ public interface PlanetProvider { - + /** * Trigger bootstrapping. */ public void bootstrap() throws BootstrapException; - - + + /** * Get a Planet instance. */ public Planet getPlanet(); - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/PropertiesManager.java b/planet-business/src/main/java/org/apache/roller/planet/business/PropertiesManager.java index 3fc5740c8c..b8d3cb3639 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/PropertiesManager.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/PropertiesManager.java @@ -27,28 +27,28 @@ * Manages global runtime properties. */ public interface PropertiesManager extends Manager { - - /** - * Save a single property + + /** + * Save a single property */ public void saveProperty(RuntimeConfigProperty property) throws PlanetException; - - - /** - * Save a list of properties + + + /** + * Save a list of properties */ public void saveProperties(Map properties) throws PlanetException; - - - /** - * Retrieve a single property by name + + + /** + * Retrieve a single property by name */ public RuntimeConfigProperty getProperty(String name) throws PlanetException; - - - /** - * Retrieve a list of all properties + + + /** + * Retrieve a list of all properties */ public Map getProperties() throws PlanetException; - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/URLStrategy.java b/planet-business/src/main/java/org/apache/roller/planet/business/URLStrategy.java index d03937a059..f569b1837b 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/URLStrategy.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/URLStrategy.java @@ -28,7 +28,7 @@ * all of the public urls used by Roller Planet. */ public interface URLStrategy { - + /** * Get root url for a given planet. * @@ -36,8 +36,8 @@ public interface URLStrategy { * @returns The url to the planet. */ public String getPlanetURL(String planetHandle); - - + + /** * Get url for a specific aggregation group of a planet. * @@ -47,8 +47,8 @@ public interface URLStrategy { * @returns The url to the planet group. */ public String getPlanetGroupURL(String planetHandle, String groupHandle, int pageNum); - - + + /** * Get url to a feed for a specific group of a planet, in the given format. * @@ -58,8 +58,8 @@ public interface URLStrategy { * @returns The url to the feed. */ public String getPlanetGroupFeedURL(String planetHandle, String groupHandle, String format); - - + + /** * Get url to a opml file for a specific group of a planet. * @@ -68,23 +68,23 @@ public interface URLStrategy { * @returns The url to the feed. */ public String getPlanetGroupOpmlURL(String planetHandle, String groupHandle); - - + + /** * Compose a map of key=value params into a query string. */ public String getQueryString(Map params); - - + + /** * URL encode a string. */ public String encode(String str); - - + + /** * URL decode a string. */ public String decode(String str); - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FeedFetcher.java b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FeedFetcher.java index 9cafe70f78..5be66b2fd6 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FeedFetcher.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FeedFetcher.java @@ -25,11 +25,11 @@ /** * A FeedFetcher is what is responsible for actually pulling subscriptions from * their source and transforming them into Roller Planet Subscriptions and Entries. - * + * * It does not perform any persistence of feeds. */ public interface FeedFetcher { - + /** * Fetch a single subscription. * @@ -37,9 +37,9 @@ public interface FeedFetcher { * return a transient instance of a Subscription representing the * given feed. * - * It is important to understand that this method will *NOT* return a + * It is important to understand that this method will *NOT* return a * persistent version of an existing Subscription if it happens to - * exist. This method is only here to pull feeds from their source + * exist. This method is only here to pull feeds from their source * so that they may be used in any way desired by the rest of the system. * * @param feedURL The feed url to use when fetching the subscription. @@ -47,8 +47,8 @@ public interface FeedFetcher { * @throws FetcherException If there is an error fetching the subscription. */ public Subscription fetchSubscription(String feedURL) throws FetcherException; - - + + /** * Conditionally fetch a single subscription. * @@ -58,9 +58,9 @@ public interface FeedFetcher { * a more efficient way to fetch subscriptions which are being updated so * subscriptions are not continually fetched when unnecessary. * - * It is important to understand that this method will *NOT* return a + * It is important to understand that this method will *NOT* return a * persistent version of an existing Subscription if it happens to - * exist. This method is only here to pull feeds from their source + * exist. This method is only here to pull feeds from their source * so that they may be used in any way desired by the rest of the system. * * @param feedURL The feed url to use when fetching the subscription. diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FetcherException.java b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FetcherException.java index 47f90d4dab..615a6b8b94 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FetcherException.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/FetcherException.java @@ -27,16 +27,16 @@ * Exception generated from FeedFetcher. */ public class FetcherException extends PlanetException { - + public FetcherException(String msg) { super(msg); } - + public FetcherException(String msg, Throwable t) { super(msg, t); } - - + + /** * Print stack trace for exception and for root cause exception if htere is one. * @see java.lang.Throwable#printStackTrace() @@ -51,8 +51,8 @@ public void printStackTrace() { getRootCause().printStackTrace(); } } - - + + /** * Print stack trace for exception and for root cause exception if htere is one. * @param s Stream to print to. @@ -67,8 +67,8 @@ public void printStackTrace(PrintStream s) { getRootCause().printStackTrace(s); } } - - + + /** * Print stack trace for exception and for root cause exception if htere is one. * @param s Writer to write to. @@ -83,5 +83,5 @@ public void printStackTrace(PrintWriter s) { getRootCause().printStackTrace(s); } } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/RomeFeedFetcher.java b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/RomeFeedFetcher.java index 5100cd9955..a1cf33ed5b 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/RomeFeedFetcher.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/fetcher/RomeFeedFetcher.java @@ -50,37 +50,37 @@ * A FeedFetcher based on the ROME RSS/Atom feed parser (http://rome.dev.java.net). */ public class RomeFeedFetcher implements org.apache.roller.planet.business.fetcher.FeedFetcher { - + private static Log log = LogFactory.getLog(RomeFeedFetcher.class); - - + + public RomeFeedFetcher() { // no-op } - - + + /** * @inheritDoc */ - public Subscription fetchSubscription(String feedURL) + public Subscription fetchSubscription(String feedURL) throws FetcherException { return fetchSubscription(feedURL, null); } - - + + /** * @inheritDoc */ - public Subscription fetchSubscription(String feedURL, Date lastModified) + public Subscription fetchSubscription(String feedURL, Date lastModified) throws FetcherException { - + if(feedURL == null) { throw new IllegalArgumentException("feed url cannot be null"); } - + // setup Rome feed fetcher FeedFetcher feedFetcher = getRomeFetcher(); - + // fetch the feed log.debug("Fetching feed: "+feedURL); SyndFeed feed; @@ -89,9 +89,9 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) } catch (Exception ex) { throw new FetcherException("Error fetching subscription - "+feedURL, ex); } - + log.debug("Feed pulled, extracting data into Subscription"); - + // build planet subscription from fetched feed Subscription newSub = new Subscription(); newSub.setFeedURL(feedURL); @@ -99,8 +99,8 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) newSub.setTitle(feed.getTitle()); newSub.setAuthor(feed.getAuthor()); newSub.setLastUpdated(feed.getPublishedDate()); - - + + // normalize any data that couldn't be properly extracted if(newSub.getSiteURL() == null) { // set the site url to the feed url then @@ -125,18 +125,18 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) // should never happen since we check this above } } - + // check if feed is unchanged and bail now if so if(lastModified != null && newSub.getLastUpdated() != null && !newSub.getLastUpdated().after(lastModified)) { return null; } - + if(log.isDebugEnabled()) { log.debug("Subscription is: "+newSub.toString()); } - - + + // some kludge to deal with feeds w/ no entry dates // we assign arbitrary dates chronologically by entry starting either // from the current time or the last update time of the subscription @@ -147,43 +147,43 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) cal.setTime(new Date()); cal.add(Calendar.DATE, -1); } - + // add entries List feedEntries = feed.getEntries(); for( SyndEntry feedEntry : feedEntries ) { SubscriptionEntry newEntry = buildEntry(feedEntry); - + // some kludge to handle feeds with no entry dates if (newEntry.getPubTime() == null) { log.debug("No published date, assigning fake date for "+feedURL); newEntry.setPubTime(new Timestamp(cal.getTimeInMillis())); cal.add(Calendar.DATE, -1); } - + if(newEntry != null) { newSub.addEntry(newEntry); } } - + log.debug(feedEntries.size()+" entries included"); - + return newSub; } - - + + // build a SubscriptionEntry from Rome SyndEntry and SyndFeed private SubscriptionEntry buildEntry(SyndEntry romeEntry) { - + // if we don't have a permalink then we can't continue if(romeEntry.getLink() == null) { return null; } - + SubscriptionEntry newEntry = new SubscriptionEntry(); - + newEntry.setTitle(romeEntry.getTitle()); newEntry.setPermalink(romeEntry.getLink()); - + // Play some games to get the author DCModule entrydc = (DCModule)romeEntry.getModule(DCModule.URI); if (romeEntry.getAuthor() != null) { @@ -191,13 +191,13 @@ private SubscriptionEntry buildEntry(SyndEntry romeEntry) { } else { newEntry.setAuthor(entrydc.getCreator()); // use } - + // Play some games to get the updated date if (romeEntry.getUpdatedDate() != null) { newEntry.setUpdateTime(new Timestamp(romeEntry.getUpdatedDate().getTime())); } // TODO: should we set a default update time here? - + // And more games getting publish date if (romeEntry.getPublishedDate() != null) { newEntry.setPubTime(new Timestamp(romeEntry.getPublishedDate().getTime())); // use @@ -206,7 +206,7 @@ private SubscriptionEntry buildEntry(SyndEntry romeEntry) { } else { newEntry.setPubTime(newEntry.getUpdateTime()); } - + // get content and unescape if it is 'text/plain' if (romeEntry.getContents().size() > 0) { SyndContent content= (SyndContent)romeEntry.getContents().get(0); @@ -216,14 +216,14 @@ private SubscriptionEntry buildEntry(SyndEntry romeEntry) { newEntry.setText(content.getValue()); } } - + // no content, try summary if (newEntry.getText() == null || newEntry.getText().trim().length() == 0) { if (romeEntry.getDescription() != null) { newEntry.setText(romeEntry.getDescription().getValue()); } } - + // copy categories if (romeEntry.getCategories().size() > 0) { List list = new ArrayList(); @@ -234,32 +234,32 @@ private SubscriptionEntry buildEntry(SyndEntry romeEntry) { } newEntry.setCategoriesString(list); } - + return newEntry; } - - + + // get a feed fetcher cache, if possible private FeedFetcherCache getRomeFetcherCache() { - + String cacheDirPath = PlanetConfig.getProperty("cache.dir"); - + // can't continue without cache dir if (cacheDirPath == null) { log.warn("Planet cache directory not set, feeds cannot be cached."); return null; } - + // allow ${user.home} in cache dir property String cacheDirName = cacheDirPath.replaceFirst( "\\$\\{user.home}",System.getProperty("user.home")); - + // allow ${catalina.home} in cache dir property if (System.getProperty("catalina.home") != null) { cacheDirName = cacheDirName.replaceFirst( "\\$\\{catalina.home}",System.getProperty("catalina.home")); } - + // create cache dir if it does not exist File cacheDir = null; try { @@ -269,34 +269,34 @@ private FeedFetcherCache getRomeFetcherCache() { log.error("Unable to create planet cache directory: " + cacheDir.getPath(), e); return null; } - + // abort if cache dir is not writable if (!cacheDir.canWrite()) { log.error("Planet cache directory is not writable: " + cacheDir.getPath()); return null; } - + return new DiskFeedInfoCache(cacheDirName); } // get a feed fetcher private FeedFetcher getRomeFetcher() { - + FeedFetcherCache feedCache = getRomeFetcherCache(); - + FeedFetcher feedFetcher = null; if(feedCache != null) { feedFetcher = new HttpURLFeedFetcher(feedCache); } else { feedFetcher = new HttpURLFeedFetcher(); } - + // set options feedFetcher.setUsingDeltaEncoding(false); feedFetcher.setUserAgent("RollerPlanetAggregator"); - + return feedFetcher; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPersistenceStrategy.java b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPersistenceStrategy.java index 92cc30ec5a..36c4b62415 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPersistenceStrategy.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPersistenceStrategy.java @@ -49,22 +49,22 @@ */ @com.google.inject.Singleton public class JPAPersistenceStrategy { - - private static Log logger = + + private static Log logger = LogFactory.getFactory().getInstance(JPAPersistenceStrategy.class); - - + + /** * The thread local EntityManager. */ private final ThreadLocal threadLocalEntityManager = new ThreadLocal(); - + /** * The EntityManagerFactory for this Roller instance. */ protected EntityManagerFactory emf; - - + + /** * Construct by finding JPA EntityManagerFactory. * @throws org.apache.roller.planet.PlanetException on any error @@ -88,8 +88,8 @@ protected JPAPersistenceStrategy() throws PlanetException { Enumeration keys = PlanetConfig.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); - if ( key.startsWith("javax.persistence.") - || key.startsWith("openjpa.") + if ( key.startsWith("javax.persistence.") + || key.startsWith("openjpa.") || key.startsWith("hibernate.")) { String value = PlanetConfig.getProperty(key); logger.info(key + ": " + value); @@ -115,8 +115,8 @@ protected JPAPersistenceStrategy() throws PlanetException { } } } - - + + /** * Flush changes to the datastore, commit transaction, release em. * @throws org.apache.roller.planet.PlanetException on any error @@ -129,7 +129,7 @@ public void flush() throws PlanetException { throw new PlanetException(pe); } } - + /** * Release database session, rolls back any uncommitted changes. */ @@ -141,7 +141,7 @@ public void release() { em.close(); setThreadLocalEntityManager(null); } - + /** * Store object using an existing transaction. * @param obj the object to persist @@ -156,7 +156,7 @@ public Object store(Object obj) throws PlanetException { } return obj; } - + /** * Remove object from persistence storage. * @param clazz the class of object to remove @@ -168,7 +168,7 @@ public void remove(Class clazz, String id) throws PlanetException { Object po = em.find(clazz, id); em.remove(po); } - + /** * Remove object from persistence storage. * @param po the persistent object to remove @@ -178,7 +178,7 @@ public void remove(Object po) throws PlanetException { EntityManager em = getEntityManager(true); em.remove(po); } - + /** * Remove object from persistence storage. * @param pos the persistent objects to remove @@ -190,8 +190,8 @@ public void removeAll(Collection pos) throws PlanetException { Object obj = iterator.next(); em.remove(obj); } - } - + } + /** * Retrieve object, no transaction needed. * @param clazz the class of object to retrieve @@ -204,7 +204,7 @@ public Object load(Class clazz, String id) EntityManager em = getEntityManager(false); return em.find(clazz, id); } - + /** * Return true if a transaction is active on the current EntityManager. * @param em the persistence manager @@ -217,7 +217,7 @@ private boolean isTransactionActive(EntityManager em) { } return em.getTransaction().isActive(); } - + /** * Get the EntityManager associated with the current thread of control. * @param isTransactionRequired true if a transaction is begun if not @@ -231,7 +231,7 @@ private EntityManager getEntityManager(boolean isTransactionRequired) { } return em; } - + /** * Get the current ThreadLocal EntityManager */ @@ -243,14 +243,14 @@ private EntityManager getThreadLocalEntityManager() { } return em; } - + /** * Set the current ThreadLocal EntityManager */ private void setThreadLocalEntityManager(Object em) { threadLocalEntityManager.set(em); } - + /** * Get named query with FlushModeType.COMMIT * @param queryName the name of the query @@ -264,7 +264,7 @@ public Query getNamedQuery(String queryName) q.setFlushMode(FlushModeType.COMMIT); return q; } - + /** * Create query from queryString with FlushModeType.COMMIT * @param queryString the quuery @@ -278,7 +278,7 @@ public Query getDynamicQuery(String queryString) q.setFlushMode(FlushModeType.COMMIT); return q; } - + /** * Get named update query with default flush mode * @param queryName the name of the query @@ -290,7 +290,7 @@ public Query getNamedUpdate(String queryName) Query q = em.createNamedQuery(queryName); return q; } - + /** * Loads properties from given resourceName using given class loader * @param resourceName The name of the resource containing properties @@ -321,10 +321,10 @@ protected static Properties loadPropertiesFromResourceName( } } } - + return props; } - + /** * Get the context class loader associated with the current thread. This is * done in a doPrivileged block because it is a secure method. @@ -337,5 +337,5 @@ public Object run() { return Thread.currentThread().getContextClassLoader(); } }); - } + } } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetImpl.java b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetImpl.java index aa3fe9319a..79c4f86d5d 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetImpl.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetImpl.java @@ -30,52 +30,52 @@ import org.apache.roller.planet.business.PropertiesManager; /** - * Implements Planet, the entry point interface for the Roller-Planet business + * Implements Planet, the entry point interface for the Roller-Planet business * tier APIs using the Java Persistence API (JPA). */ @com.google.inject.Singleton -public class JPAPlanetImpl extends AbstractManagerImpl implements Planet { - +public class JPAPlanetImpl extends AbstractManagerImpl implements Planet { + private static Log log = LogFactory.getLog(JPAPlanetImpl.class); - + // a persistence utility class private final JPAPersistenceStrategy strategy; - + // references to the managers we maintain private final PlanetManager planetManager; private final PropertiesManager propertiesManager; - + // url strategy private final URLStrategy urlStrategy; - + // feed fetcher private final FeedFetcher feedFetcher; - - - @com.google.inject.Inject + + + @com.google.inject.Inject protected JPAPlanetImpl( - JPAPersistenceStrategy strategy, - PlanetManager planetManager, + JPAPersistenceStrategy strategy, + PlanetManager planetManager, PropertiesManager propertiesManager, URLStrategy urlStrategy, FeedFetcher feedFetcher) throws PlanetException { - + this.strategy = strategy; this.propertiesManager = propertiesManager; this.planetManager = planetManager; this.urlStrategy = urlStrategy; this.feedFetcher = feedFetcher; } - + @Override public void initialize() throws InitializationException { - + log.info("Initializing Roller Planet business tier"); - + getPropertiesManager().initialize(); getPlanetManager().initialize(); - + // we always need to do a flush after initialization because it's // possible that some changes need to be persisted try { @@ -83,28 +83,28 @@ public void initialize() throws InitializationException { } catch(PlanetException ex) { throw new InitializationException("Error flushing after initialization", ex); } - + log.info("Roller Planet business tier successfully initialized"); } - - + + public void flush() throws PlanetException { this.strategy.flush(); } - + @Override public void release() { this.strategy.release(); } - + @Override public void shutdown() { this.release(); } - - + + /** * @see org.apache.roller.business.Roller#getBookmarkManager() */ @@ -112,22 +112,22 @@ public PlanetManager getPlanetManager() { return planetManager; } - + /** * @see org.apache.roller.business.Roller#getBookmarkManager() */ public PropertiesManager getPropertiesManager() { return propertiesManager; } - - + + public URLStrategy getURLStrategy() { return this.urlStrategy; } - - + + public FeedFetcher getFeedFetcher() { return this.feedFetcher; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetManagerImpl.java b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetManagerImpl.java index c98bb2c888..87b060a651 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetManagerImpl.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/jpa/JPAPlanetManagerImpl.java @@ -46,32 +46,32 @@ */ @com.google.inject.Singleton public class JPAPlanetManagerImpl extends AbstractManagerImpl implements PlanetManager { - + private static Log log = LogFactory.getLog(JPAPlanetManagerImpl.class); - + /** The strategy for this manager. */ private final JPAPersistenceStrategy strategy; - + protected Map lastUpdatedByGroup = new HashMap(); protected static final String NO_GROUP = "zzz_nogroup_zzz"; - - - @com.google.inject.Inject + + + @com.google.inject.Inject protected JPAPlanetManagerImpl(JPAPersistenceStrategy strategy) { log.debug("Instantiating JPA Planet Manager"); - + this.strategy = strategy; } - - + + public void saveGroup(PlanetGroup group) throws PlanetException { strategy.store(group); } - + public void saveEntry(SubscriptionEntry entry) throws PlanetException { strategy.store(entry); } - + public void saveSubscription(Subscription sub) throws PlanetException { Subscription existing = getSubscription(sub.getFeedURL()); @@ -81,20 +81,20 @@ public void saveSubscription(Subscription sub) throw new PlanetException("ERROR: duplicate feed URLs not allowed"); } } - + public void deleteEntry(SubscriptionEntry entry) throws PlanetException { strategy.remove(entry); } - + public void deleteGroup(PlanetGroup group) throws PlanetException { strategy.remove(group); } - + public void deleteSubscription(Subscription sub) throws PlanetException { strategy.remove(sub); } - + public Subscription getSubscription(String feedUrl) throws PlanetException { Query q = strategy.getNamedQuery("Subscription.getByFeedURL"); @@ -105,13 +105,13 @@ public Subscription getSubscription(String feedUrl) return null; } } - + public Subscription getSubscriptionById(String id) throws PlanetException { return (Subscription) strategy.load( Subscription.class, id); } - + public Iterator getAllSubscriptions() { try { return ((List)strategy.getNamedQuery( @@ -121,17 +121,17 @@ public Iterator getAllSubscriptions() { "ERROR fetching subscription collection", e); } } - + public int getSubscriptionCount() throws PlanetException { Query q = strategy.getNamedQuery("Subscription.getAll"); return q.getResultList().size(); } - + public List getTopSubscriptions(int offset, int length) throws PlanetException { return getTopSubscriptions(null, offset, length); } - + /** * Get top X subscriptions, restricted by group. */ @@ -154,7 +154,7 @@ public List getTopSubscriptions( } return result; } - + public PlanetGroup getGroup(String handle) throws PlanetException { Query q = strategy.getNamedQuery("PlanetGroup.getByHandle"); q.setParameter(1, handle); @@ -164,18 +164,18 @@ public PlanetGroup getGroup(String handle) throws PlanetException { return null; } } - + public PlanetGroup getGroupById(String id) throws PlanetException { return (PlanetGroup) strategy.load(PlanetGroup.class, id); - } - + } + public void release() {} - - + + public void savePlanet(Planet planet) throws PlanetException { strategy.store(planet); } - + public Planet getPlanet(String handle) throws PlanetException { Query q = strategy.getNamedQuery("Planet.getByHandle"); q.setParameter(1, handle); @@ -185,15 +185,15 @@ public Planet getPlanet(String handle) throws PlanetException { return null; } } - + public Planet getPlanetById(String id) throws PlanetException { return (Planet)strategy.load(Planet.class, id); } - + public List getPlanets() throws PlanetException { return (List)strategy.getNamedQuery("Planet.getAll").getResultList(); } - + public List getGroupHandles(Planet planet) throws PlanetException { List handles = new ArrayList(); Iterator list = getGroups(planet).iterator(); @@ -203,13 +203,13 @@ public List getGroupHandles(Planet planet) throws PlanetException { } return handles; } - + public List getGroups(Planet planet) throws PlanetException { Query q = strategy.getNamedQuery("PlanetGroup.getByPlanet"); q.setParameter(1, planet.getHandle()); return q.getResultList(); } - + public PlanetGroup getGroup(Planet planet, String handle) throws PlanetException { Query q = strategy.getNamedQuery("PlanetGroup.getByPlanetAndHandle"); q.setParameter(1, planet.getHandle()); @@ -220,22 +220,22 @@ public PlanetGroup getGroup(Planet planet, String handle) throws PlanetException return null; } } - + public void deletePlanet(Planet planet) throws PlanetException { strategy.remove(planet); } - - public void deleteEntries(Subscription sub) + + public void deleteEntries(Subscription sub) throws PlanetException { Iterator entries = sub.getEntries().iterator(); while(entries.hasNext()) { strategy.remove(entries.next()); } - + // make sure and clear the other side of the assocation sub.getEntries().clear(); } - + public List getSubscriptions() throws PlanetException { Query q = strategy.getNamedQuery("Subscription.getAllOrderByFeedURL"); return q.getResultList(); @@ -245,7 +245,7 @@ public SubscriptionEntry getEntryById(String id) throws PlanetException { return (SubscriptionEntry) strategy.load(SubscriptionEntry.class, id); } - public List getEntries(Subscription sub, int offset, int len) throws PlanetException { + public List getEntries(Subscription sub, int offset, int len) throws PlanetException { if (sub == null) { throw new PlanetException("subscription cannot be null"); } @@ -262,24 +262,24 @@ public List getEntries(PlanetGroup group, int offset, int len) throws PlanetExce public List getEntries(PlanetGroup group, Date startDate, Date endDate, int offset, int len) throws PlanetException { StringBuffer queryString = new StringBuffer(); - + if (group == null) { throw new PlanetException("group cannot be null or empty"); } - + List ret = null; try { long startTime = System.currentTimeMillis(); - + StringBuffer sb = new StringBuffer(); List params = new ArrayList(); int size = 0; sb.append("SELECT e FROM SubscriptionEntry e "); sb.append("JOIN e.subscription.groups g "); - + params.add(size++, group.getHandle()); sb.append("WHERE g.handle = ?").append(size); - + if (startDate != null) { params.add(size++, new Timestamp(startDate.getTime())); sb.append(" AND e.pubTime > ?").append(size); @@ -289,7 +289,7 @@ public List getEntries(PlanetGroup group, Date startDate, Date endDate, int offs sb.append(" AND e.pubTime < :?").append(size); } sb.append(" ORDER BY e.pubTime DESC"); - + Query query = strategy.getDynamicQuery(sb.toString()); for (int i=0; i startupLog; - - + + public StartupException(String msg) { super(msg); this.startupLog = Collections.EMPTY_LIST; } - + public StartupException(String msg, Throwable t) { super(msg, t); this.startupLog = Collections.EMPTY_LIST; } - + public StartupException(String msg, List log) { super(msg); - + if(log != null) { this.startupLog = log; } else { this.startupLog = Collections.EMPTY_LIST; } } - + public StartupException(String msg, Throwable t, List log) { super(msg, t); - + if(log != null) { this.startupLog = log; } else { this.startupLog = Collections.EMPTY_LIST; } } - - + + public List getStartupLog() { return startupLog; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/updater/FeedUpdater.java b/planet-business/src/main/java/org/apache/roller/planet/business/updater/FeedUpdater.java index 715dbab1ab..be9fc71d77 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/updater/FeedUpdater.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/updater/FeedUpdater.java @@ -25,7 +25,7 @@ /** * A FeedUpdater is responsible for processing the updates of all Subscriptions * and their entries. It is intended to combine the use of the FeedFetcher for - * pulling fresh feed data with the PlanetManager for updating and persisting + * pulling fresh feed data with the PlanetManager for updating and persisting * the updated data. * * NOTE: it must be explicitly stated that the operations of the FeedUpdater are @@ -33,33 +33,33 @@ * So callers of these methods should bear that in mind when using this class. */ public interface FeedUpdater { - + /** * Update a single Subscription. * * This method takes in an existing Subscription and updates it with - * the data from the subscriptions source after fetching an updated version + * the data from the subscriptions source after fetching an updated version * of the subscription. * * @param subscription The PlanetSubscription to be updated. * @throws FetcherException If there is an error updating the subscription. */ public void updateSubscription(Subscription sub) throws UpdaterException; - - + + /** * Update all Subscriptions in the system. * * @throws UpdaterException If there is an error during the update and the operation cannot continue. */ public void updateSubscriptions() throws UpdaterException; - - + + /** * Update all Subscriptions that are part of the specified group. * * @throws UpdaterException If there is an error during the update and the operation cannot continue. */ public void updateSubscriptions(PlanetGroup group) throws UpdaterException; - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/updater/SingleThreadedFeedUpdater.java b/planet-business/src/main/java/org/apache/roller/planet/business/updater/SingleThreadedFeedUpdater.java index 3fa4c81804..e914863832 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/updater/SingleThreadedFeedUpdater.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/updater/SingleThreadedFeedUpdater.java @@ -38,30 +38,30 @@ * A single threaded implementation of a FeedUpdater. */ public class SingleThreadedFeedUpdater implements FeedUpdater { - + private static Log log = LogFactory.getLog(SingleThreadedFeedUpdater.class); - - + + public SingleThreadedFeedUpdater() { // no-op } - - + + /** * @inheritDoc */ public void updateSubscription(Subscription sub) throws UpdaterException { - + if (sub == null) { throw new IllegalArgumentException("cannot update null subscription"); } - + updateProxySettings(); - + log.debug("updating feed: "+sub.getFeedURL()); - + long subStartTime = System.currentTimeMillis(); - + Subscription updatedSub; try { // fetch the latest version of the subscription @@ -69,73 +69,73 @@ public void updateSubscription(Subscription sub) throws UpdaterException { FeedFetcher fetcher = PlanetFactory.getPlanet().getFeedFetcher(); log.debug("Using fetcher class: " + fetcher.getClass().getName()); updatedSub = fetcher.fetchSubscription(sub.getFeedURL(), sub.getLastUpdated()); - + } catch (FetcherException ex) { throw new UpdaterException("Error fetching updated subscription", ex); } - + log.debug("Got updatedSub = " + updatedSub); // if sub was unchanged then we are done if (updatedSub == null) { return; } - + // if this subscription hasn't changed since last update then we're done if (sub.getLastUpdated() != null && updatedSub.getLastUpdated() != null && !updatedSub.getLastUpdated().after(sub.getLastUpdated())) { log.debug("Skipping update, feed hasn't changed - "+sub.getFeedURL()); } - + // update subscription attributes sub.setSiteURL(updatedSub.getSiteURL()); sub.setTitle(updatedSub.getTitle()); sub.setAuthor(updatedSub.getAuthor()); sub.setLastUpdated(updatedSub.getLastUpdated()); - + // update subscription entries int entries = 0; Set newEntries = updatedSub.getEntries(); log.debug("newEntries.size() = " + newEntries.size()); if (newEntries.size() > 0) try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + // clear out old entries pmgr.deleteEntries(sub); - + // add fresh entries sub.getEntries().clear(); sub.addEntries(newEntries); - + // save and flush pmgr.saveSubscription(sub); PlanetFactory.getPlanet().flush(); log.debug("Added entries"); - entries += newEntries.size(); + entries += newEntries.size(); } catch(PlanetException ex) { throw new UpdaterException("Error persisting updated subscription", ex); } - + long subEndTime = System.currentTimeMillis(); log.debug("updated feed -- "+sub.getFeedURL()+" -- in "+ ((subEndTime-subStartTime)/1000.0)+" seconds. "+entries+ " entries updated."); } - - + + /** * @inheritDoc */ public void updateSubscriptions() throws UpdaterException { - + updateProxySettings(); - + log.debug("--- BEGIN --- Updating all subscriptions"); - + long startTime = System.currentTimeMillis(); - + try { // update all subscriptions in the system PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); @@ -143,52 +143,52 @@ public void updateSubscriptions() throws UpdaterException { } catch (PlanetException ex) { throw new UpdaterException("Error getting subscriptions list", ex); } - + long endTime = System.currentTimeMillis(); log.info("--- DONE --- Updated subscriptions in " + ((endTime-startTime)/1000.0) + " seconds"); } - - + + /** * @inheritDoc */ public void updateSubscriptions(PlanetGroup group) throws UpdaterException { - + if(group == null) { throw new IllegalArgumentException("cannot update null group"); } - + updateProxySettings(); - + log.debug("--- BEGIN --- Updating subscriptions in group = "+group.getHandle()); - + long startTime = System.currentTimeMillis(); - + updateSubscriptions(group.getSubscriptions()); - + long endTime = System.currentTimeMillis(); log.info("--- DONE --- Updated subscriptions in " + ((endTime-startTime)/1000.0) + " seconds"); } - - + + // convenience method which handles updating any arbitrary collection of subs private void updateSubscriptions(Collection subscriptions) { - + PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + Iterator subs = subscriptions.iterator(); while (subs.hasNext()) { Subscription sub = (Subscription)subs.next(); - + try { // reattach sub. sub gets detached as we iterate sub = pmgr.getSubscriptionById(sub.getId()); } catch (PlanetException ex) { log.warn("Subscription went missing while doing update: "+ex.getMessage()); } - + // this updates and saves try { updateSubscription(sub); @@ -201,14 +201,14 @@ private void updateSubscriptions(Collection subscriptions) { if(cause.getCause() != null) { cause = cause.getCause(); } - + if (log.isDebugEnabled()) { log.debug("Error updating subscription - "+sub.getFeedURL(), cause); } else { log.warn("Error updating subscription - "+sub.getFeedURL() + " turn on debug logging for more info"); } - + } catch(Exception ex) { if (log.isDebugEnabled()) { log.warn("Error updating subscription - "+sub.getFeedURL(), ex); @@ -219,8 +219,8 @@ private void updateSubscriptions(Collection subscriptions) { } } } - - + + // upate proxy settings for jvm based on planet configuration private void updateProxySettings() { String proxyHost = PlanetRuntimeConfig.getProperty("site.proxyhost"); @@ -234,5 +234,5 @@ private void updateProxySettings() { System.setProperty("sun.net.client.defaultConnectTimeout", "15000"); System.setProperty("sun.net.client.defaultReadTimeout", "15000"); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/business/updater/UpdaterException.java b/planet-business/src/main/java/org/apache/roller/planet/business/updater/UpdaterException.java index b4c05ef561..b2706677eb 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/business/updater/UpdaterException.java +++ b/planet-business/src/main/java/org/apache/roller/planet/business/updater/UpdaterException.java @@ -25,13 +25,13 @@ * Exception generated from FeedUpdater. */ public class UpdaterException extends PlanetException { - + public UpdaterException(String msg) { super(msg); } - + public UpdaterException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/PlanetConfig.java b/planet-business/src/main/java/org/apache/roller/planet/config/PlanetConfig.java index ff1f3499ba..1a6df5dad2 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/PlanetConfig.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/PlanetConfig.java @@ -32,7 +32,7 @@ * This is the single entry point for accessing configuration properties in Roller. */ public class PlanetConfig { - + private static String default_config = "/org/apache/roller/planet/config/planet.properties"; private static String custom_config = "/planet-custom.properties"; private static String custom_jvm_param = "planet.custom.config"; @@ -41,8 +41,8 @@ public class PlanetConfig { private static Properties mConfig; private static Log log = LogFactory.getLog(PlanetConfig.class); - - + + /* * Static block run once at class loading * @@ -141,11 +141,11 @@ public static String getProperty(String key) { log.debug("Fetching property ["+key+"="+mConfig.getProperty(key)+"]"); return mConfig.getProperty(key); } - + /** * Retrieve a property value * @param key Name of the property - * @param defaultValue Default value of property if not found + * @param defaultValue Default value of property if not found * @return String Value of property requested or defaultValue */ public static String getProperty(String key, String defaultValue) { @@ -153,7 +153,7 @@ public static String getProperty(String key, String defaultValue) { String value = mConfig.getProperty(key); if(value == null) return defaultValue; - + return value; } @@ -204,11 +204,11 @@ public static int getIntProperty(String name, int defaultValue) { public static Enumeration keys() { return mConfig.keys(); } - + /** * Set the "context.realpath" property at runtime. *

- * Properties are meant to be read-only, but we make this exception to make + * Properties are meant to be read-only, but we make this exception to make * it possible for unit tests to control the cache directory. *

* This property is *not* persisted in any way. diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/PlanetRuntimeConfig.java b/planet-business/src/main/java/org/apache/roller/planet/config/PlanetRuntimeConfig.java index 2065fee811..5219ec4fb3 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/PlanetRuntimeConfig.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/PlanetRuntimeConfig.java @@ -38,102 +38,102 @@ * We also provide some methods for converting to different data types. */ public class PlanetRuntimeConfig { - + private static Log log = LogFactory.getLog(PlanetRuntimeConfig.class); - + private static String runtime_config = "/org/apache/roller/planet/config/planetRuntimeConfigDefs.xml"; private static RuntimeConfigDefs configDefs = null; - + // special case for our context urls private static String relativeContextURL = null; private static String absoluteContextURL = null; - - + + // prevent instantiations private PlanetRuntimeConfig() {} - - + + /** * Retrieve a single property from the PropertiesManager ... returns null * if there is an error **/ public static String getProperty(String name) { - + String value = null; - + try { PropertiesManager pmgr = PlanetFactory.getPlanet().getPropertiesManager(); value = pmgr.getProperty(name).getValue(); } catch(Exception e) { log.warn("Trouble accessing property: "+name, e); } - + log.debug("fetched property ["+name+"="+value+"]"); return value; } - - + + /** * Retrieve a property as a boolean ... defaults to false if there is an error **/ public static boolean getBooleanProperty(String name) { - + // get the value first, then convert String value = PlanetRuntimeConfig.getProperty(name); - + if(value == null) return false; - + return (new Boolean(value)).booleanValue(); } - - + + /** * Retrieve a property as an int ... defaults to -1 if there is an error **/ public static int getIntProperty(String name) { - + // get the value first, then convert String value = PlanetRuntimeConfig.getProperty(name); - + if(value == null) return -1; - + int intval = -1; try { intval = Integer.parseInt(value); } catch(Exception e) { log.warn("Trouble converting to int: "+name, e); } - + return intval; } - - + + public static RuntimeConfigDefs getRuntimeConfigDefs() { - + if(configDefs == null) { - + // unmarshall the config defs file try { - InputStream is = + InputStream is = PlanetRuntimeConfig.class.getResourceAsStream(runtime_config); - + RuntimeConfigDefsParser parser = new RuntimeConfigDefsParser(); configDefs = parser.unmarshall(is); - + } catch(Exception e) { // error while parsing :( log.error("Error parsing runtime config defs", e); } - + } - + return configDefs; } - - + + /** * Get the runtime configuration definitions XML file as a string. * @@ -143,27 +143,27 @@ public static RuntimeConfigDefs getRuntimeConfigDefs() { * the display for editing those properties. */ public static String getRuntimeConfigDefsAsString() { - + log.debug("Trying to load runtime config defs file"); - + try { InputStreamReader reader = new InputStreamReader(PlanetConfig.class.getResourceAsStream(runtime_config)); StringWriter configString = new StringWriter(); - + char[] buf = new char[8196]; int length = 0; while((length = reader.read(buf)) > 0) configString.write(buf, 0, length); - + reader.close(); - + return configString.toString(); } catch(Exception e) { log.error("Error loading runtime config defs file", e); } - + return ""; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/ConfigDef.java b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/ConfigDef.java index d42db83113..aaf89b734e 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/ConfigDef.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/ConfigDef.java @@ -27,47 +27,47 @@ * Each ConfigDef may contain 0 or more DisplayGroups. */ public class ConfigDef { - + private List displayGroups = null; private String name = null; - - + + public ConfigDef() { this.displayGroups = new ArrayList(); } - + public ConfigDef(List displaygroups) { this.displayGroups = displaygroups; } - - + + public boolean addDisplayGroup(DisplayGroup group) { return this.displayGroups.add(group); } - + public boolean removeDisplayGroup(DisplayGroup group) { return this.displayGroups.remove(group); } - - + + public String toString() { return name; } - + public List getDisplayGroups() { return displayGroups; } - + public void setDisplayGroups(List displayGroups) { this.displayGroups = displayGroups; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/DisplayGroup.java b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/DisplayGroup.java index c9353a3aee..0a86d3f221 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/DisplayGroup.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/DisplayGroup.java @@ -27,57 +27,57 @@ * Each DisplayGroup may contain 0 or more PropertyDefs. */ public class DisplayGroup { - + private List propertyDefs = null; private String name = null; private String key = null; - - + + public DisplayGroup() { this.propertyDefs = new ArrayList(); } - + public DisplayGroup(List propdefs) { this.propertyDefs = propdefs; } - - + + public boolean addPropertyDef(PropertyDef prop) { return this.propertyDefs.add(prop); } - + public boolean removePropertyDef(PropertyDef prop) { return this.propertyDefs.remove(prop); } - - + + public String toString() { return name+","+key; } - + public List getPropertyDefs() { return propertyDefs; } - + public void setPropertyDefs(List propertyDefs) { this.propertyDefs = propertyDefs; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getKey() { return key; } - + public void setKey(String key) { this.key = key; } - - + + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/PropertyDef.java b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/PropertyDef.java index cae8a9f457..0a4dd68635 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/PropertyDef.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/PropertyDef.java @@ -30,62 +30,62 @@ * - cols (optional) */ public class PropertyDef { - + private String name = null; private String key = null; private String type = null; private String defaultValue = null; private int rows = 5; private int cols = 25; - - + + /** Creates a new instance of PropertyDef */ public PropertyDef() {} - + public String toString() { return "["+name+","+key+","+type+","+defaultValue+","+rows+","+cols+"]"; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getKey() { return key; } - + public void setKey(String key) { this.key = key; } - + public String getType() { return type; } - + public void setType(String type) { this.type = type; } - + public String getDefaultValue() { return defaultValue; } - + public void setDefaultValue(String defaultvalue) { this.defaultValue = defaultvalue; } - + public int getRows() { return rows; } - + public void setRows(int rows) { this.rows = rows; } - + public void setRows(String rows) { //convert to int try { @@ -98,11 +98,11 @@ public void setRows(String rows) { public int getCols() { return cols; } - + public void setCols(int cols) { this.cols = cols; } - + public void setCols(String cols) { //convert to int try { diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefs.java b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefs.java index 8d6e0a9842..484d5bce76 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefs.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefs.java @@ -26,34 +26,34 @@ * Represents the collection of all ConfigDefs. */ public class RuntimeConfigDefs { - + private List configDefs = null; - - + + public RuntimeConfigDefs() { this.configDefs = new ArrayList(); } - + public RuntimeConfigDefs(List configs) { this.configDefs = configs; } - - + + public boolean addConfigDef(ConfigDef config) { return this.configDefs.add(config); } - + public boolean removeConfigDef(ConfigDef config) { return this.configDefs.remove(config); } - - + + public List getConfigDefs() { return configDefs; } - + public void setConfigDefs(List configDefs) { this.configDefs = configDefs; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefsParser.java b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefsParser.java index 5893b91e30..b517ce468f 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefsParser.java +++ b/planet-business/src/main/java/org/apache/roller/planet/config/runtime/RuntimeConfigDefsParser.java @@ -33,26 +33,26 @@ * This class uses jdom to unmarshall the xml into a series of java objects. */ public class RuntimeConfigDefsParser { - + /** Creates a new instance of RuntimeConfigDefsParser */ public RuntimeConfigDefsParser() {} - - + + /** * Unmarshall the given input stream into our defined * set of Java objects. **/ public RuntimeConfigDefs unmarshall(InputStream instream) throws IOException, JDOMException { - + if(instream == null) throw new IOException("InputStream is null!"); - + RuntimeConfigDefs configs = new RuntimeConfigDefs(); - + SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(instream); - + Element root = doc.getRootElement(); List configdefs = root.getChildren("config-def"); Iterator iter = configdefs.iterator(); @@ -60,63 +60,63 @@ public RuntimeConfigDefs unmarshall(InputStream instream) Element e = (Element) iter.next(); configs.addConfigDef(this.elementToConfigDef(e)); } - + return configs; } - - + + private ConfigDef elementToConfigDef(Element element) { - + ConfigDef configdef = new ConfigDef(); - + configdef.setName(element.getAttributeValue("name")); - + List displaygroups = element.getChildren("display-group"); Iterator iter = displaygroups.iterator(); while (iter.hasNext()) { Element e = (Element) iter.next(); configdef.addDisplayGroup(this.elementToDisplayGroup(e)); } - + return configdef; } - - + + private DisplayGroup elementToDisplayGroup(Element element) { - + DisplayGroup displaygroup = new DisplayGroup(); - + displaygroup.setName(element.getAttributeValue("name")); displaygroup.setKey(element.getAttributeValue("key")); - + List displaygroups = element.getChildren("property-def"); Iterator iter = displaygroups.iterator(); while (iter.hasNext()) { Element e = (Element) iter.next(); displaygroup.addPropertyDef(this.elementToPropertyDef(e)); } - + return displaygroup; } - - + + private PropertyDef elementToPropertyDef(Element element) { - + PropertyDef prop = new PropertyDef(); - + prop.setName(element.getAttributeValue("name")); prop.setKey(element.getAttributeValue("key")); prop.setType(element.getChildText("type")); prop.setDefaultValue(element.getChildText("default-value")); - + // optional elements if(element.getChild("rows") != null) prop.setRows(element.getChildText("rows")); - + if(element.getChild("cols") != null) prop.setCols(element.getChildText("cols")); - + return prop; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/Author.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/Author.java index df57a74022..15986557c7 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/Author.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/Author.java @@ -22,10 +22,10 @@ * Represents the author of an entry. */ public class Author { - + private String fullName = null; private String userName = null; - + public String getFullName() { return fullName; @@ -42,5 +42,5 @@ public String getUserName() { public void setUserName(String userName) { this.userName = userName; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/Category.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/Category.java index 95bfd93d91..c5436b03f9 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/Category.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/Category.java @@ -22,10 +22,10 @@ * Represents a category of an entry. */ public class Category { - + private String name = null; private String path = null; - + public String getName() { return name; @@ -42,5 +42,5 @@ public String getPath() { public void setPath(String path) { this.path = path; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/Planet.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/Planet.java index 1f4781f3d8..48aee39720 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/Planet.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/Planet.java @@ -25,29 +25,29 @@ /** * A Roller "Planet". - * + * * @hibernate.class lazy="true" table="rag_planet" */ public class Planet implements Comparable { - + private String id = UUIDGenerator.generateUUID(); private String handle = null; private String title = null; private String description = null; private Set groups = new TreeSet(); - - + + public Planet() { } - - + + public Planet(String handle, String title, String desc) { this.title = title; this.handle = handle; this.description = desc; } - - + + /** * For comparing planets and sorting, ordered by Title. */ @@ -55,8 +55,8 @@ public int compareTo(Object o) { Planet other = (Planet) o; return getTitle().compareTo(other.getTitle()); } - - + + /** * @hibernate.id column="id" generator-class="assigned" */ @@ -67,8 +67,8 @@ public String getId() { public void setId(String id) { this.id = id; } - - + + /** * @hibernate.property column="handle" non-null="true" unique="true" */ @@ -79,8 +79,8 @@ public String getHandle() { public void setHandle(String handle) { this.handle = handle; } - - + + /** * @hibernate.property column="title" non-null="true" unique="false" */ @@ -91,8 +91,8 @@ public String getTitle() { public void setTitle(String title) { this.title = title; } - - + + /** * @hibernate.property column="description" non-null="false" unique="false" */ @@ -104,8 +104,8 @@ public void setDescription(String description) { this.description = description; } - - /** + + /** * @hibernate.set lazy="true" inverse="true" cascade="all" sort="natural" * @hibernate.collection-key column="planet_id" * @hibernate.collection-one-to-many class="org.apache.roller.planet.pojos.PlanetGroup" @@ -117,5 +117,5 @@ public Set getGroups() { public void setGroups(Set groups) { this.groups = groups; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/PlanetGroup.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/PlanetGroup.java index a54a95c378..b362e4e118 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/PlanetGroup.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/PlanetGroup.java @@ -33,9 +33,9 @@ * @hibernate.class lazy="true" table="rag_group" */ public class PlanetGroup implements Serializable, Comparable { - + transient private String[] catArray = null; - + // attributes private String id = UUIDGenerator.generateUUID(); private String handle = null; @@ -43,25 +43,25 @@ public class PlanetGroup implements Serializable, Comparable { private String description = null; private int maxPageEntries = 45; private int maxFeedEntries = 45; - + // is this really used? private String categoryRestriction = null; - + // associations private Planet planet = null; private Set subscriptions = new TreeSet(); - - + + public PlanetGroup() {} - + public PlanetGroup(Planet planet, String handle, String title, String desc) { this.planet = planet; this.handle = handle; this.title = title; this.description = desc; } - - + + /** * For comparing groups and sorting, ordered by Title. */ @@ -69,105 +69,105 @@ public int compareTo(Object o) { PlanetGroup other = (PlanetGroup) o; return getTitle().compareTo(other.getTitle()); } - - + + /** * @hibernate.id column="id" generator-class="assigned" */ public String getId() { return id; } - + public void setId(String id) { this.id = id; } - - + + /** * @hibernate.property column="handle" non-null="false" unique="false" */ public String getHandle() { return handle; } - + public void setHandle(String handle) { this.handle = handle; } - - + + /** * @hibernate.property column="title" non-null="false" unique="false" */ public String getTitle() { return title; } - + public void setTitle(String title) { this.title = title; } - - + + /** * @hibernate.property column="description" non-null="false" unique="false" */ public String getDescription() { return description; } - + public void setDescription(String description) { this.description = description; } - - + + /** * @hibernate.property column="max_feed_entries" non-null="false" unique="false" */ public int getMaxFeedEntries() { return maxFeedEntries; } - + public void setMaxFeedEntries(int maxFeedEntries) { this.maxFeedEntries = maxFeedEntries; } - - + + /** * @hibernate.property column="max_page_entries" non-null="false" unique="false" */ public int getMaxPageEntries() { return maxPageEntries; } - + public void setMaxPageEntries(int maxPageEntries) { this.maxPageEntries = maxPageEntries; } - - + + /** * @hibernate.property column="cat_restriction" non-null="false" unique="false" */ public String getCategoryRestriction() { return categoryRestriction; } - + public void setCategoryRestriction(String categoryRestriction) { this.categoryRestriction = categoryRestriction; catArray = null; } - - + + /** * @hibernate.many-to-one column="planet_id" cascade="none" non-null="false" */ public Planet getPlanet() { return planet; } - + public void setPlanet(Planet planet) { this.planet = planet; } - - + + /** * @hibernate.set table="rag_group_subscription" lazy="true" invert="true" cascade="none" sort="natural" * @hibernate.collection-key column="group_id" @@ -176,12 +176,12 @@ public void setPlanet(Planet planet) { public Set getSubscriptions() { return subscriptions; } - + public void setSubscriptions(Set subscriptions) { this.subscriptions = subscriptions; } - - + + /** * Return a list of the most recent 10 entries from this group. */ @@ -193,8 +193,8 @@ public List getRecentEntries() { return Collections.EMPTY_LIST; } } - - + + /** * Returns true if entry is qualified for inclusion in this group. */ @@ -206,19 +206,19 @@ public boolean qualified(SubscriptionEntry entry) { } return false; } - - + + private String[] getCategoryRestrictionAsArray() { if (catArray == null && categoryRestriction != null) { StringTokenizer toker = new StringTokenizer(categoryRestriction,","); catArray = new String[toker.countTokens()]; int i = 0; - + while (toker.hasMoreTokens()) { catArray[i++] = toker.nextToken(); } } return catArray; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/RuntimeConfigProperty.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/RuntimeConfigProperty.java index cfbaaf5be8..07d3af2f81 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/RuntimeConfigProperty.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/RuntimeConfigProperty.java @@ -25,25 +25,25 @@ /** * Represents a single runtime property of the system. - * + * * @hibernate.cache usage="read-write" * @hibernate.class lazy="true" table="rag_properties" */ public class RuntimeConfigProperty implements Serializable { - + private String name = null; private String value = null; - - + + public RuntimeConfigProperty() {} - - + + public RuntimeConfigProperty(String name, String value) { this.name = name; this.value = value; } - - + + /** * Getter for property name. * @@ -52,20 +52,20 @@ public RuntimeConfigProperty(String name, String value) { * @hibernate.id column="name" generator-class="assigned" */ public String getName() { - + return this.name; } - + /** * Setter for property name. * * @param name New value of property name. */ public void setName(String name) { - + this.name = name; } - + /** * Getter for property value. * @@ -74,26 +74,26 @@ public void setName(String name) { * @hibernate.property column="value" non-null="false" unique="false" */ public String getValue() { - + return this.value; } - + /** * Setter for property value. * * @param value New value of property value. */ public void setValue(String value) { - + this.value = value; } - + //------------------------------------------------------- Good citizenship - + public String toString() { return (this.name + "=" + this.value); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof RuntimeConfigProperty != true) return false; @@ -102,7 +102,7 @@ public boolean equals(Object other) { .append(getName(), o.getName()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/StaticTemplate.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/StaticTemplate.java index 045ffae753..b4f13ef1d7 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/StaticTemplate.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/StaticTemplate.java @@ -30,7 +30,7 @@ * an object. */ public class StaticTemplate implements Template, Serializable { - + private String id = null; private String name = null; private String description = null; @@ -40,10 +40,10 @@ public class StaticTemplate implements Template, Serializable { private String templateLanguage = null; private boolean hidden = false; private boolean navbar = false; - - + + public StaticTemplate() {} - + public StaticTemplate(String id, String contents, String lang) { this.id = id; this.name = id; @@ -53,11 +53,11 @@ public StaticTemplate(String id, String contents, String lang) { this.templateLanguage = lang; } - + public Template getDecorator() { return null; } - + public String getId() { return id; } @@ -125,10 +125,10 @@ public void setHidden(boolean hidden) { public void setNavbar(boolean navbar) { this.navbar = navbar; } - + public boolean isNavbar() { - return navbar; + return navbar; } - - + + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/Subscription.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/Subscription.java index 5a3c82d813..b5f8a062a8 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/Subscription.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/Subscription.java @@ -29,7 +29,7 @@ * Planet Subscription. */ public class Subscription implements Serializable, Comparable { - + // attributes private String id = UUIDGenerator.generateUUID(); private String title; @@ -39,17 +39,17 @@ public class Subscription implements Serializable, Comparable { private Date lastUpdated; private int inboundlinks = 0; private int inboundblogs = 0; - + // associations private Set groups = new HashSet(); private Set entries = new HashSet(); - - + + public Subscription() {} - + /** * Compares subscriptions based on concatenation of title and feed URL. - * This ensures that feeds are sorted by title, but that identical titles + * This ensures that feeds are sorted by title, but that identical titles * don't make feeds equal. */ public int compareTo(Object o) { @@ -58,24 +58,24 @@ public int compareTo(Object o) { String thisString = getTitle() + getFeedURL(); return thisString.compareTo(otherString); } - + /** * Determines if subscriotions are equal by comparing feed URLs. */ - public boolean equals(Object other) { + public boolean equals(Object other) { if(this == other) return true; - if(!(other instanceof Subscription)) return false; + if(!(other instanceof Subscription)) return false; final Subscription that = (Subscription) other; return this.feedUrl.equals(that.getFeedURL()); } - + public int hashCode() { return this.feedUrl.hashCode(); } - + public String toString() { StringBuffer buf = new StringBuffer(); - + buf.append("{"); buf.append(feedUrl).append(", "); buf.append(siteUrl).append(", "); @@ -83,104 +83,104 @@ public String toString() { buf.append(author).append(", "); buf.append(lastUpdated); buf.append("}"); - + return buf.toString(); - + } - - + + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - - + + public String getTitle() { return title; } - + public void setTitle(String title) { this.title = title; } - - + + public String getAuthor() { return author; } - + public void setAuthor(String author) { this.author = author; } - - + + public String getFeedURL() { return feedUrl; } - + public void setFeedURL(String feedUrl) { this.feedUrl = feedUrl; } - - + + public String getSiteURL() { return siteUrl; } - + public void setSiteURL(String siteUrl) { this.siteUrl = siteUrl; } - - + + public Date getLastUpdated() { return lastUpdated; } - + public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } - - + + public int getInboundlinks() { return inboundlinks; } - + public void setInboundlinks(int inboundlinks) { this.inboundlinks = inboundlinks; } - - + + public int getInboundblogs() { return inboundblogs; } - + public void setInboundblogs(int inboundblogs) { this.inboundblogs = inboundblogs; } - - + + public Set getGroups() { return groups; } - + // private because there is no need for people to do this private void setGroups(Set groups) { this.groups = groups; } - - + + public Set getEntries() { return entries; } - + // private because there is no need for people to do this private void setEntries(Set entries) { this.entries = entries; } - - + + /** * Add a SubscriptionEntry to this Subscription. */ @@ -189,7 +189,7 @@ public void addEntry(SubscriptionEntry entry) { entry.setSubscription(this); this.getEntries().add(entry); } - + /** * Add a collection of SubscriptionEntry to this Subscription. */ @@ -201,16 +201,16 @@ public void addEntries(Collection newEntries) { } this.getEntries().addAll(newEntries); } - - + + // for backwards compatability? public String getName() { return title; } - + // for backwards compatability? public String getURL() { return siteUrl; } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/SubscriptionEntry.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/SubscriptionEntry.java index 888ae9c9a4..54f9d7717c 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/SubscriptionEntry.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/SubscriptionEntry.java @@ -28,15 +28,15 @@ /** - * Represents a planet entry, i.e. an entry that was parsed out of an RSS or - * Atom newsfeed by Roller's built-in planet aggregator. + * Represents a planet entry, i.e. an entry that was parsed out of an RSS or + * Atom newsfeed by Roller's built-in planet aggregator. *

- * The model coded in this class simple, perhaps too simple, and in the future - * it should be replaced by more complete model that can fully represent all + * The model coded in this class simple, perhaps too simple, and in the future + * it should be replaced by more complete model that can fully represent all * forms of RSS and Atom. */ public class SubscriptionEntry implements Serializable, Comparable { - + // attributes private String id = UUIDGenerator.generateUUID(); private String handle; @@ -48,14 +48,14 @@ public class SubscriptionEntry implements Serializable, Comparable { private Timestamp published; private Timestamp updated; private String categoriesString; - + // associations private Subscription subscription = null; - - + + public SubscriptionEntry() {} - - + + /** * Compare planet entries by comparing permalinks. */ @@ -63,126 +63,126 @@ public int compareTo(Object o) { SubscriptionEntry other = (SubscriptionEntry)o; return getPermalink().compareTo(other.getPermalink()); } - + /** * Compare planet entries by comparing permalinks. */ - public boolean equals(Object other) { + public boolean equals(Object other) { if(this == other) return true; - if(!(other instanceof SubscriptionEntry)) return false; + if(!(other instanceof SubscriptionEntry)) return false; final SubscriptionEntry that = (SubscriptionEntry) other; return this.permalink.equals(that.getPermalink()); } - + /** * Generate hash code based on permalink. */ public int hashCode() { return this.permalink.hashCode(); } - - + + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - - + + public String getHandle() { return handle; } - + public void setHandle(String handle) { this.handle = handle; } - - + + public String getTitle() { return title; } - + public void setTitle(String title) { this.title = title; } - - + + public String getGuid() { return guid; } - + public void setGuid(String guid) { this.guid = guid; } - - + + public String getPermalink() { return permalink; } - + public void setPermalink(String permalink) { this.permalink = permalink; } - - + + public String getAuthor() { return author; } - + public void setAuthor(String author) { this.author = author; } - - + + public String getText() { return text; } - + public void setText(String content) { this.text = content; } - - + + public Timestamp getPubTime() { return published; } - + public void setPubTime(Timestamp published) { this.published = published; } - - + + public Timestamp getUpdateTime() { return updated; } - + public void setUpdateTime(Timestamp updated) { this.updated = updated; } - - + + public String getCategoriesString() { return categoriesString; } - + public void setCategoriesString(String categoriesString) { this.categoriesString = categoriesString; } - - + + public Subscription getSubscription() { return subscription; } - + public void setSubscription(Subscription subscription) { this.subscription = subscription; } - - + + //----------------------------------------------------------------- convenience - + /** * Returns true if any of entry's categories contain a specific string * (case-insensitive comparison). @@ -197,9 +197,9 @@ public boolean inCategory(String category) { } return false; } - + //------------------------------------------------------------- implementation - + /** * Returns categories as list of WeblogCategoryData objects. */ @@ -216,7 +216,7 @@ public List getCategories() { } return list; } - + /** * Return first entry in category collection. * @roller.wrapPojoMethod type="pojo" @@ -240,8 +240,8 @@ public void setCategoriesString(List categories) { } categoriesString = sb.toString(); } - - /** + + /** * Returns creator as a UserData object. * @roller.wrapPojoMethod type="pojo" * TODO: make planet model entry author name, email, and uri @@ -254,23 +254,23 @@ public Author getCreator() { user.setUserName(author); } return user; - } - + } + /** * Returns summary (always null for planet entry) * @roller.wrapPojoMethod type="simple" */ public String getSummary() { return null; - } - + } + /** * Read-only synomym for getSubscription() * @roller.wrapPojoMethod type="pojo" */ public Subscription getWebsite() { - return this.subscription; + return this.subscription; } public void setWebsite() { // noop diff --git a/planet-business/src/main/java/org/apache/roller/planet/pojos/Template.java b/planet-business/src/main/java/org/apache/roller/planet/pojos/Template.java index 2dcb2b4612..e6949481b9 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/pojos/Template.java +++ b/planet-business/src/main/java/org/apache/roller/planet/pojos/Template.java @@ -13,9 +13,9 @@ * */ public interface Template { - + public String getId(); - + public String getTemplateLanguage(); - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/tasks/GeneratePlanetTask.java b/planet-business/src/main/java/org/apache/roller/planet/tasks/GeneratePlanetTask.java index 3bda4fe653..daf5b9eef8 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/tasks/GeneratePlanetTask.java +++ b/planet-business/src/main/java/org/apache/roller/planet/tasks/GeneratePlanetTask.java @@ -37,7 +37,7 @@ /** - * Generates Planet files based on those entries and the Planet configuration. + * Generates Planet files based on those entries and the Planet configuration. *

  * - Uses PlanetConfig properties for templateDir, outputDir and template name
  * - Creates outputdir and a subdirectory for each group
@@ -45,31 +45,31 @@
  * 
*/ public class GeneratePlanetTask extends PlanetTask { - + private static Log log = LogFactory.getLog(GeneratePlanetTask.class); - - + + public void run() { - try { + try { Planet planet = PlanetFactory.getPlanet(); PlanetManager planetManager = planet.getPlanetManager(); - + // Ignore values from database //String mainPage = planetManager.getConfiguration().getMainPage(); //String templateDir = planetManager.getConfiguration().getTemplateDir(); //String outputDir = planetManager.getConfiguration().getMainPage(); - + // Use values from PlanetConfig instead - String mainPage = + String mainPage = PlanetConfig.getProperty("planet.aggregator.mainPage"); - String templateDir = - PlanetConfig.getProperty("planet.aggregator.template.dir"); - String outputDir = + String templateDir = + PlanetConfig.getProperty("planet.aggregator.template.dir"); + String outputDir = PlanetConfig.getProperty("planet.aggregator.output.dir"); - + log.info("Calling Velocity Texen to generate Planet files"); log.info(" Control file ["+mainPage+"]"); - log.info(" Template directory ["+templateDir+"]"); + log.info(" Template directory ["+templateDir+"]"); log.info(" Output directory ["+outputDir+"]"); // Fire up Velocity engine, point it at templates and init @@ -79,19 +79,19 @@ public void run() { "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); engine.setProperty("file.resource.loader.path", templateDir); engine.init(); - - // Build context with current date + + // Build context with current date VelocityContext context = new VelocityContext(); context.put("date", new Date()); // TODO fix: Use one utilities model and not one of the below //context.put("utils", new UtilitiesModel()); context.put("utilities", new Utilities()); context.put("planet", new StaticPlanetModel()); - + // Ensure that output directories exists, one for each group File outputDirObj = new File(outputDir); if (!outputDirObj.exists()) outputDirObj.mkdirs(); - + List groups = Collections.EMPTY_LIST; // groups must be part of a planet now, so getGroupHandles() was removed //List groups = planetManager.getGroupHandles(); @@ -101,7 +101,7 @@ public void run() { File groupDir = new File(groupDirName); if (!groupDir.exists()) groupDir.mkdirs(); } - + // Generate files: execute control template Generator generator = Generator.getInstance(); generator.setVelocityEngine(engine); @@ -111,16 +111,16 @@ public void run() { generator.setTemplatePath(templateDir); generator.parse(mainPage, context); generator.shutdown(); - + } catch (Exception e) { log.error("ERROR generating planet", e); } } - + public static void main(String[] args) throws Exception{ GeneratePlanetTask task = new GeneratePlanetTask(); task.initialize(); task.run(); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/tasks/PlanetTask.java b/planet-business/src/main/java/org/apache/roller/planet/tasks/PlanetTask.java index ca53d2f1f5..636bf5723b 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/tasks/PlanetTask.java +++ b/planet-business/src/main/java/org/apache/roller/planet/tasks/PlanetTask.java @@ -28,10 +28,10 @@ * An abstract class representing a scheduled task in Roller Planet. */ public abstract class PlanetTask implements Runnable { - + /** * Initialize the task basically the same way the webapp would initialize. */ public void initialize() throws Exception { - } + } } diff --git a/planet-business/src/main/java/org/apache/roller/planet/tasks/RefreshPlanetTask.java b/planet-business/src/main/java/org/apache/roller/planet/tasks/RefreshPlanetTask.java index fe94926926..eefce7bbf6 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/tasks/RefreshPlanetTask.java +++ b/planet-business/src/main/java/org/apache/roller/planet/tasks/RefreshPlanetTask.java @@ -34,34 +34,34 @@ * */ public class RefreshPlanetTask extends PlanetTask { - + private static Log log = LogFactory.getLog(RefreshPlanetTask.class); - - + + public void run() { - try { + try { // Update all feeds in planet log.info("Refreshing Planet entries"); FeedUpdater updater = new SingleThreadedFeedUpdater(); updater.updateSubscriptions(); PlanetFactory.getPlanet().release(); - + } catch (Exception e) { log.error("ERROR refreshing planet", e); } } - - + + public static void main(String[] args) throws Exception { - + RefreshPlanetTask task = new RefreshPlanetTask(); task.initialize(); - + // need to prepare and bootstrap Planet as well PlanetStartup.prepare(); PlanetFactory.bootstrap(); - + task.run(); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/tasks/StaticPlanetModel.java b/planet-business/src/main/java/org/apache/roller/planet/tasks/StaticPlanetModel.java index e9e79d6d4f..760b2099db 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/tasks/StaticPlanetModel.java +++ b/planet-business/src/main/java/org/apache/roller/planet/tasks/StaticPlanetModel.java @@ -36,24 +36,24 @@ public class StaticPlanetModel { private static Log logger = LogFactory.getFactory().getInstance(StaticPlanetModel.class); PlanetManager planetManager = null; - - + + public StaticPlanetModel() throws PlanetException { Planet planet = PlanetFactory.getPlanet(); planetManager = planet.getPlanetManager(); } - + // TODO: replace this with something equivalent // public PlanetConfigData getConfiguration() throws PlanetException { // return planetManager.getConfiguration(); // } - - + + public Subscription getSubscription(String feedUrl) throws Exception { - return planetManager.getSubscription(feedUrl); + return planetManager.getSubscription(feedUrl); } - - + + public List getFeedEntries(String feedUrl, int maxEntries) throws Exception { try { Subscription sub = planetManager.getSubscription(feedUrl); @@ -67,31 +67,31 @@ public List getFeedEntries(String feedUrl, int maxEntries) throws Exception { throw e; } } - + // removed now that groups must be part of a planet, this method no longer makes sense // public List getGroups() throws PlanetException { // return planetManager.getGroups(); // } - + // removed now that groups must be part of a planet, this method no longer makes sense // public PlanetGroup getGroup(String handle) throws PlanetException { // return planetManager.getGroup(handle); // } - - + + public List getAggregation( PlanetGroup group, int maxEntries) throws PlanetException { return planetManager.getEntries(group, 0, maxEntries); } - - + + public Iterator getAllSubscriptions() throws PlanetException { return planetManager.getSubscriptions().iterator(); } - - + + public int getSubscriptionCount() throws PlanetException { return planetManager.getSubscriptionCount(); - } + } } diff --git a/planet-business/src/main/java/org/apache/roller/planet/tasks/TechnoratiRankingsTask.java b/planet-business/src/main/java/org/apache/roller/planet/tasks/TechnoratiRankingsTask.java index 80e31082cb..037e584dab 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/tasks/TechnoratiRankingsTask.java +++ b/planet-business/src/main/java/org/apache/roller/planet/tasks/TechnoratiRankingsTask.java @@ -36,15 +36,15 @@ * Rank each subscription by populating Technorati inbound blog and link counts. */ public class TechnoratiRankingsTask extends PlanetTask { - + private static Log log = LogFactory.getLog(TechnoratiRankingsTask.class); - - + + /** * Loop through all subscriptions get get Technorati rankings for each */ public void run() { - + int count = 0; int errorCount = 0; try { @@ -67,22 +67,22 @@ public void run() { +"For example, in the /WEB-INF/classes directory."); return; } - + try { int limit = PlanetConfig.getIntProperty( "planet.aggregator.technorati.limit", 500); int userCount = planet.getSubscriptionCount(); int mod = (userCount / limit) + 1; - + Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int day = cal.get(Calendar.DAY_OF_YEAR); - + int start = (day % mod) * limit; int end = start + limit; end = end > userCount ? userCount : end; log.info("Updating subscriptions ["+start+":"+end+"]"); - + Iterator subs = planet.getSubscriptions().iterator(); while (subs.hasNext()) { Subscription sub = @@ -120,24 +120,24 @@ public void run() { } count++; } - + // all done, flush results to db PlanetFactory.getPlanet().flush(); - + } finally { PlanetFactory.getPlanet().release(); } - + } catch (Exception e) { log.error("ERROR ranking subscriptions", e); } } - - + + public static void main(String[] args) throws Exception{ TechnoratiRankingsTask task = new TechnoratiRankingsTask(); task.initialize(); task.run(); } - + } diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/MailUtil.java b/planet-business/src/main/java/org/apache/roller/planet/util/MailUtil.java index f4d88687af..e7591acbbc 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/MailUtil.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/MailUtil.java @@ -31,8 +31,8 @@ import org.apache.commons.lang.StringUtils; public class MailUtil extends Object { - - private static Log mLogger = + + private static Log mLogger = LogFactory.getFactory().getInstance(MailUtil.class); // agangolli: Incorporated suggested changes from Ken Blackler. @@ -40,7 +40,7 @@ public class MailUtil extends Object { /** * This method is used to send a Message with a pre-defined * mime-type. - * + * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail @@ -58,7 +58,7 @@ public class MailUtil extends Object { String subject, String content, String mimeType - ) + ) throws MessagingException { Message message = new MimeMessage(session); @@ -73,8 +73,8 @@ public class MailUtil extends Object { if (to!=null) { InternetAddress[] sendTo = new InternetAddress[to.length]; - - for (int i = 0; i < to.length; i++) + + for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (mLogger.isDebugEnabled()) mLogger.debug("sending e-mail to: " + to[i]); @@ -82,40 +82,40 @@ public class MailUtil extends Object { message.setRecipients(Message.RecipientType.TO, sendTo); } - if (cc != null) + if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; - for (int i = 0; i < cc.length; i++) + for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); - } + } - if (bcc != null) + if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; - for (int i = 0; i < bcc.length; i++) + for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("blind copying e-mail to: " + bcc[i]); } message.setRecipients(Message.RecipientType.BCC, copyTo); - } + } message.setSubject((subject == null) ? "(no subject)" : subject); message.setContent(content, mimeType); - message.setSentDate(new java.util.Date()); + message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; - + SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); - + // Try to send while there remain some potentially good addresses do { @@ -131,18 +131,18 @@ public class MailUtil extends Object { { bFailedToSome=true; sendex.setNextException(ex); - + // Extract the remaining potentially good addresses remainingAddresses=ex.getValidUnsentAddresses(); } } while (remainingAddresses!=null && remainingAddresses.length>0 && remainingAddresses.length!=nAddresses); - + if (bFailedToSome) throw sendex; } /** * This method is used to send a Text Message. - * + * * @param from e-mail address of sender * @param to e-mail addresses of recipients * @param subject subject of e-mail @@ -158,16 +158,16 @@ public class MailUtil extends Object { String[] bcc, String subject, String content - ) + ) throws MessagingException { sendMessage(session, from, to, cc, bcc, subject, content, "text/plain; charset=utf-8"); } - + /** * This method overrides the sendTextMessage to specify * one receiver and mulitple cc recipients. - * + * * @param from e-mail address of sender * @param to e-mail addresses of recipients * @param subject subject of e-mail @@ -183,7 +183,7 @@ public class MailUtil extends Object { String[] bcc, String subject, String content - ) + ) throws MessagingException { String[] recipient = null; @@ -191,12 +191,12 @@ public class MailUtil extends Object { sendMessage(session, from, recipient, cc, bcc, subject, content, "text/plain; charset=utf-8"); } - + /** * This method overrides the sendTextMessage to specify - * only one receiver and cc recipients, rather than + * only one receiver and cc recipients, rather than * an array of recipients. - * + * * @param from e-mail address of sender * @param to e-mail address of recipient * @param cc e-mail address of cc recipient @@ -213,7 +213,7 @@ public class MailUtil extends Object { String bcc, String subject, String content - ) + ) throws MessagingException { String[] recipient = null; @@ -226,10 +226,10 @@ public class MailUtil extends Object { sendMessage(session, from, recipient, copy, bcopy, subject, content, "text/plain; charset=utf-8"); } - + /** * This method is used to send a HTML Message - * + * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail @@ -245,16 +245,16 @@ public class MailUtil extends Object { String[] bcc, String subject, String content - ) + ) throws MessagingException { sendMessage(session, from, to, cc, bcc, subject, content, "text/html; charset=utf-8"); } - + /** * This method overrides the sendHTMLMessage to specify * only one sender, rather than an array of senders. - * + * * @param from e-mail address of sender * @param to e-mail address of recipients * @param subject subject of e-mail @@ -270,7 +270,7 @@ public class MailUtil extends Object { String bcc, String subject, String content - ) + ) throws MessagingException { String[] recipient = null; @@ -283,11 +283,11 @@ public class MailUtil extends Object { sendMessage(session, from, recipient, copy, bcopy, subject, content, "text/html; charset=utf-8"); } - + /** * This method overrides the sendHTMLMessage to specify * one receiver and mulitple cc recipients. - * + * * @param from e-mail address of sender * @param to e-mail address of recipient * @param cc e-mail addresses of recipients @@ -304,7 +304,7 @@ public class MailUtil extends Object { String[] bcc, String subject, String content - ) + ) throws MessagingException { String[] recipient = null; diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/URLUtilities.java b/planet-business/src/main/java/org/apache/roller/planet/util/URLUtilities.java index 3e6c633f68..c8373ebc6a 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/URLUtilities.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/URLUtilities.java @@ -36,100 +36,100 @@ * code. */ public final class URLUtilities { - + // non-intantiable private URLUtilities() {} - - + + /** * Get root url for a given weblog. Optionally for a certain locale. */ public static final String getPlanetURL(String planet) { - + if(planet == null) { return null; } - + StringBuffer url = new StringBuffer(); - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + url.append(PlanetRuntimeConfig.getProperty("site.absoluteurl")); url.append("/").append(planet).append("/"); - + return url.toString(); } - - + + /** * Get url for a single weblog entry on a given weblog. */ public static final String getPlanetGroupURL(String planet, String group) { - + if(planet == null || group == null) { return null; } - + StringBuffer url = new StringBuffer(); - + url.append(getPlanetURL(planet)); url.append("group/").append(group).append("/"); - + return url.toString(); } - - + + /** * Get url for a feed on a given weblog. */ public static final String getPlanetGroupFeedURL(String planet, String group, String format) { - + if(planet == null || group == null) { return null; } - + StringBuffer url = new StringBuffer(); - + url.append(getPlanetGroupURL(planet, group)); url.append("feed/").append(format); - + return url.toString(); } - - + + /** * Compose a map of key=value params into a query string. */ public static final String getQueryString(Map params) { - + if(params == null) { return null; } - + StringBuffer queryString = new StringBuffer(); - + for(Iterator keys = params.keySet().iterator(); keys.hasNext();) { String key = (String) keys.next(); String value = (String) params.get(key); - + if (queryString.length() == 0) { queryString.append("?"); } else { queryString.append("&"); } - + queryString.append(key); queryString.append("="); queryString.append(value); } - + return queryString.toString(); } - - + + /** * URL encode a string using UTF-8. */ @@ -142,8 +142,8 @@ public static final String encode(String str) { } return encodedStr; } - - + + /** * URL decode a string using UTF-8. */ @@ -156,18 +156,18 @@ public static final String decode(String str) { } return decodedStr; } - - + + public static final String getEncodedTagsString(List tags) { StringBuffer tagsString = new StringBuffer(); if(tags != null && tags.size() > 0) { String tag = null; Iterator tagsIT = tags.iterator(); - + // do first tag tag = (String) tagsIT.next(); tagsString.append(encode(tag)); - + // do rest of tags, joining them with a '+' while(tagsIT.hasNext()) { tag = (String) tagsIT.next(); diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/Utilities.java b/planet-business/src/main/java/org/apache/roller/planet/util/Utilities.java index d1e0098cff..1a1ef400df 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/Utilities.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/Utilities.java @@ -32,9 +32,9 @@ public class Utilities { /** The Log instance for this class. */ private static Log mLogger = LogFactory.getLog(Utilities.class); - + public final static String TAG_SPLIT_CHARS = " ,\n\r\f\t"; - + //------------------------------------------------------------------------ /** Strip jsessionid off of a URL */ public static String stripJsessionId( String url ) { @@ -51,7 +51,7 @@ public static String stripJsessionId( String url ) { } return url; } - + //------------------------------------------------------------------------ /** * Escape, but do not replace HTML. @@ -60,7 +60,7 @@ public static String stripJsessionId( String url ) { public static String escapeHTML(String s) { return escapeHTML(s, true); } - + //------------------------------------------------------------------------ /** * Escape, but do not replace HTML. @@ -78,11 +78,11 @@ public static String escapeHTML(String s, boolean escapeAmpersand) { s = StringUtils.replace(s, ">", ">"); return s; } - + public static String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + //------------------------------------------------------------------------ /** * Remove occurences of html, defined as any text @@ -92,7 +92,7 @@ public static String unescapeHTML(String str) { public static String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -110,16 +110,16 @@ public static String removeHTML(String str, boolean addSpace) { int endTag = 0; if (beginTag == -1) return str; - + while (beginTag >= start) { if (beginTag > 0) { ret.append(str.substring(start, beginTag)); - + // replace each tag with a space (looks better) if (addSpace) ret.append(" "); } endTag = str.indexOf(">", beginTag); - + // if endTag found move "cursor" forward if (endTag > -1) { start = endTag + 1; @@ -137,7 +137,7 @@ public static String removeHTML(String str, boolean addSpace) { } return ret.toString().trim(); } - + //------------------------------------------------------------------------ /** Run both removeHTML and escapeHTML on a string. * @param s String to be run through removeHTML and escapeHTML. @@ -147,7 +147,7 @@ public static String removeAndEscapeHTML( String s ) { if ( s==null ) return ""; else return Utilities.escapeHTML( Utilities.removeHTML(s) ); } - + //------------------------------------------------------------------------ /** * Autoformat. @@ -156,7 +156,7 @@ public static String autoformat(String s) { String ret = StringUtils.replace(s, "\n", "
"); return ret; } - + //------------------------------------------------------------------------ /** * Replaces occurences of non-alphanumeric characters with an underscore. @@ -164,7 +164,7 @@ public static String autoformat(String s) { public static String replaceNonAlphanumeric(String str) { return replaceNonAlphanumeric(str, '_'); } - + //------------------------------------------------------------------------ /** * Replaces occurences of non-alphanumeric characters with a @@ -182,7 +182,7 @@ public static String replaceNonAlphanumeric(String str, char subst) { } return ret.toString(); } - + //------------------------------------------------------------------------ /** * Remove occurences of non-alphanumeric characters. @@ -199,7 +199,7 @@ public static String removeNonAlphanumeric(String str) { } return ret.toString(); } - + //------------------------------------------------------------------------ /** * @param stringArray @@ -216,7 +216,7 @@ public static String stringArrayToString(String[] stringArray, String delim) { } return ret; } - + //-------------------------------------------------------------------------- /** Convert string to string array. */ public static String[] stringToStringArray(String instr, String delim) @@ -224,13 +224,13 @@ public static String[] stringToStringArray(String instr, String delim) StringTokenizer toker = new StringTokenizer(instr, delim); String stringArray[] = new String[toker.countTokens()]; int i = 0; - + while (toker.hasMoreTokens()) { stringArray[i++] = toker.nextToken(); } return stringArray; } - + //-------------------------------------------------------------------------- /** Convert string to integer array. */ public static int[] stringToIntArray(String instr, String delim) @@ -238,7 +238,7 @@ public static int[] stringToIntArray(String instr, String delim) StringTokenizer toker = new StringTokenizer(instr, delim); int intArray[] = new int[toker.countTokens()]; int i = 0; - + while (toker.hasMoreTokens()) { String sInt = toker.nextToken(); int nInt = Integer.parseInt(sInt); @@ -246,7 +246,7 @@ public static int[] stringToIntArray(String instr, String delim) } return intArray; } - + //------------------------------------------------------------------- /** Convert integer array to a string. */ public static String intArrayToString(int[] intArray) { @@ -259,12 +259,12 @@ public static String intArrayToString(int[] intArray) { } return ret; } - + //------------------------------------------------------------------------ public static void copyFile(File from, File to) throws IOException { InputStream in = null; OutputStream out = null; - + try { in = new FileInputStream(from); } catch (IOException ex) { @@ -274,7 +274,7 @@ public static void copyFile(File from, File to) throws IOException { + "', " + ex.getMessage()); } - + try { out = new FileOutputStream(to); } catch (Exception ex) { @@ -288,10 +288,10 @@ public static void copyFile(File from, File to) throws IOException { + "', " + ex.getMessage()); } - + copyInputToOutput(in, out, from.length()); } - + //------------------------------------------------------------------------ /** * Utility method to copy an input stream to an output stream. @@ -304,16 +304,16 @@ public static void copyInputToOutput( throws IOException { int bytes; long length; - + BufferedInputStream in = new BufferedInputStream(input); BufferedOutputStream out = new BufferedOutputStream(output); - + byte[] buffer; buffer = new byte[8192]; - + for (length = byteCount; length > 0;) { bytes = (int) (length > 8192 ? 8192 : length); - + try { bytes = in.read(buffer, 0, bytes); } catch (IOException ex) { @@ -325,12 +325,12 @@ public static void copyInputToOutput( throw new IOException( "Reading input stream, " + ex.getMessage()); } - + if (bytes < 0) break; - + length -= bytes; - + try { out.write(buffer, 0, bytes); } catch (IOException ex) { @@ -343,7 +343,7 @@ public static void copyInputToOutput( "Writing output stream, " + ex.getMessage()); } } - + try { in.close(); out.close(); @@ -351,7 +351,7 @@ public static void copyInputToOutput( throw new IOException("Closing file streams, " + ex.getMessage()); } } - + //------------------------------------------------------------------------ public static void copyInputToOutput( InputStream input, @@ -365,7 +365,7 @@ public static void copyInputToOutput( if (count != -1) out.write(buffer, 0, count); } - + try { in.close(); out.close(); @@ -373,7 +373,7 @@ public static void copyInputToOutput( throw new IOException("Closing file streams, " + ex.getMessage()); } } - + /** * Encode a string using algorithm specified in web.xml and return the * resulting encrypted password. If exception, the plain credentials @@ -387,9 +387,9 @@ public static void copyInputToOutput( */ public static String encodePassword(String password, String algorithm) { byte[] unencodedPassword = password.getBytes(); - + MessageDigest md = null; - + try { // first create an instance, given the provider md = MessageDigest.getInstance(algorithm); @@ -397,29 +397,29 @@ public static String encodePassword(String password, String algorithm) { mLogger.error("Exception: " + e); return password; } - + md.reset(); - + // call the update method one or more times // (useful when you don't know the size of your data, eg. stream) md.update(unencodedPassword); - + // now calculate the hash byte[] encodedPassword = md.digest(); - + StringBuffer buf = new StringBuffer(); - + for (int i = 0; i < encodedPassword.length; i++) { if ((encodedPassword[i] & 0xff) < 0x10) { buf.append("0"); } - + buf.append(Long.toString(encodedPassword[i] & 0xff, 16)); } - + return buf.toString(); } - + /** * Encode a string using Base64 encoding. Used when storing passwords * as cookies. @@ -432,10 +432,10 @@ public static String encodePassword(String password, String algorithm) { * @throws IOException */ public static String encodeString(String str) throws IOException { - String encodedStr = new String(Base64.encodeBase64(str.getBytes())); + String encodedStr = new String(Base64.encodeBase64(str.getBytes())); return (encodedStr.trim()); } - + /** * Decode a string using Base64 encoding. * @@ -444,10 +444,10 @@ public static String encodeString(String str) throws IOException { * @throws IOException */ public static String decodeString(String str) throws IOException { - String value = new String(Base64.decodeBase64(str.getBytes())); - return (value); + String value = new String(Base64.decodeBase64(str.getBytes())); + return (value); } - + /** * Strips HTML and truncates. */ @@ -455,21 +455,21 @@ public static String truncate( String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); - + // quickly adjust the upper if it is set lower than 'lower' if (upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -479,14 +479,14 @@ public static String truncate( str2 = str2.substring(0, upper); loc = upper; } - + // the string was truncated, so we append the appendToEnd String str2 = str2 + appendToEnd; } - + return str2; } - + /** * This method based on code from the String taglib at Apache Jakarta: * http://cvs.apache.org/viewcvs/jakarta-taglibs/string/src/org/apache/taglibs/string/util/StringW.java?rev=1.16&content-type=text/vnd.viewcvs-markup @@ -503,21 +503,21 @@ public static String truncateNicely(String str, int lower, int upper, String app // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -527,29 +527,29 @@ public static String truncateNicely(String str, int lower, int upper, String app str2 = str2.substring(0, upper); loc = upper; } - + // HTML was removed from original str if (diff) { - + // location of last space in truncated string loc = str2.lastIndexOf(' ', loc); - + // get last "word" in truncated string (add 1 to loc to eliminate space String str3 = str2.substring(loc+1); - + // find this fragment in original str, from 'loc' position loc = str.indexOf(str3, loc) + str3.length(); - + // get truncated string from original str, given new 'loc' str2 = str.substring(0, loc); - + // get all the HTML from original str after loc str3 = extractHTML(str.substring(loc)); - + // remove any tags which generate visible HTML // This call is unecessary, all HTML has already been stripped //str3 = removeVisibleHTMLTags(str3); - + // append the appendToEnd String and // add extracted HTML back onto truncated string str = str2 + appendToEnd + str3; @@ -557,31 +557,31 @@ public static String truncateNicely(String str, int lower, int upper, String app // the string was truncated, so we append the appendToEnd String str = str2 + appendToEnd; } - + } - + return str; } - + public static String truncateText(String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -596,7 +596,7 @@ public static String truncateText(String str, int lower, int upper, String appen } return str; } - + /** * @param str * @return @@ -611,7 +611,7 @@ private static String stripLineBreaks(String str) { str = str.replaceAll("

",""); return str; } - + /** * Need need to get rid of any user-visible HTML tags once all text has been * removed such as <BR>. This sounds like a better approach than removing @@ -628,7 +628,7 @@ private static String removeVisibleHTMLTags(String str) { str = stripLineBreaks(str); StringBuffer result = new StringBuffer(str); StringBuffer lcresult = new StringBuffer(str.toLowerCase()); - + // = start) { endTag = str.indexOf(">", beginTag); - + // if endTag found, keep tag if (endTag > -1) { ret.append( str.substring(beginTag, endTag+1) ); - + // move start forward and find another tag start = endTag + 1; beginTag = str.indexOf("<", start); @@ -714,14 +714,14 @@ public static String extractHTML(String str) { } return ret.toString(); } - - + + public static String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public static String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } @@ -772,37 +772,37 @@ public static int stringToInt(String string) { } return 0; } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public static String toBase64(byte[] aValue) { - + final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - + int byte1; int byte2; int byte3; int iByteLen = aValue.length; StringBuffer tt = new StringBuffer(); - + for (int i = 0; i < iByteLen; i += 3) { boolean bByte2 = (i + 1) < iByteLen; boolean bByte3 = (i + 2) < iByteLen; byte1 = aValue[i] & 0xFF; byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0; byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0; - + tt.append(m_strBase64Chars.charAt(byte1 / 4)); tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16))); tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '=')); tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '=')); } - + return tt.toString(); } - + /** * @param tag * @return @@ -830,12 +830,12 @@ public static String stripInvalidTagCharacters(String tag) { } return sb.toString(); } - + public static String normalizeTag(String tag, Locale locale) { tag = Utilities.stripInvalidTagCharacters(tag); - return locale == null ? tag.toLowerCase() : tag.toLowerCase(locale); + return locale == null ? tag.toLowerCase() : tag.toLowerCase(locale); } - + /** * @param tags * @return diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/rome/ContentModuleGenerator.java b/planet-business/src/main/java/org/apache/roller/planet/util/rome/ContentModuleGenerator.java index 13ebc86ee8..d7261e87ff 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/rome/ContentModuleGenerator.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/rome/ContentModuleGenerator.java @@ -27,7 +27,7 @@ import com.sun.syndication.io.ModuleGenerator; public class ContentModuleGenerator implements ModuleGenerator { - private static final Namespace CONTENT_NS = + private static final Namespace CONTENT_NS = Namespace.getNamespace(ContentModule.URI); public String getNamespaceUri() { diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091N.java b/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091N.java index 64fc09676e..084eb69643 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091N.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091N.java @@ -32,7 +32,7 @@ protected PlanetConverterForRSS091N(String type) { } protected SyndEntry createSyndEntry(Item item) { SyndEntry entry = super.createSyndEntry(item, true); - entry.setPublishedDate(item.getPubDate()); + entry.setPublishedDate(item.getPubDate()); return entry; } } diff --git a/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091U.java b/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091U.java index 3adae2639b..6e090fd05f 100644 --- a/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091U.java +++ b/planet-business/src/main/java/org/apache/roller/planet/util/rome/PlanetConverterForRSS091U.java @@ -33,7 +33,7 @@ protected PlanetConverterForRSS091U(String type) { } protected SyndEntry createSyndEntry(Item item) { SyndEntry entry = super.createSyndEntry(item, true); - entry.setPublishedDate(item.getPubDate()); + entry.setPublishedDate(item.getPubDate()); return entry; } } diff --git a/planet-business/src/main/resources/META-INF/persistence.xml b/planet-business/src/main/resources/META-INF/persistence.xml index d7e9b5df74..7c822cd839 100644 --- a/planet-business/src/main/resources/META-INF/persistence.xml +++ b/planet-business/src/main/resources/META-INF/persistence.xml @@ -1,10 +1,10 @@ - + ${datasourceName} org/apache/roller/planet/pojos/RuntimeConfigProperty.orm.xml org/apache/roller/planet/pojos/Planet.orm.xml org/apache/roller/planet/pojos/PlanetGroup.orm.xml org/apache/roller/planet/pojos/Subscription.orm.xml - org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml + org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml \ No newline at end of file diff --git a/planet-business/src/main/resources/org/apache/roller/planet/config/planetRuntimeConfigDefs.xml b/planet-business/src/main/resources/org/apache/roller/planet/config/planetRuntimeConfigDefs.xml index 8e442b22b3..4d72e007af 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/config/planetRuntimeConfigDefs.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/config/planetRuntimeConfigDefs.xml @@ -21,21 +21,21 @@ STOP!!!! This is NOT a Roller configuration file!! Users of Roller should never need to edit this file. The properties listed here are changed on the Roller Admin Settings page. - + This file defines what properties are made available to get/set during the running of the Roller application. These properties are stored in the database and the code *must* be able to make use of changed values during runtime. - + Also included in this file is meta-data which defines what class of property we are dealing with, it's default value, and information on how to populate the display that allows for changing the value. - + NOTE: order does matter!! the display is populated in a linear fashion starting from the first display-group and moving down. --> - + - + string Roller Planet @@ -76,9 +76,9 @@ string 0 - + - + - + diff --git a/planet-business/src/main/resources/org/apache/roller/planet/pojos/Planet.orm.xml b/planet-business/src/main/resources/org/apache/roller/planet/pojos/Planet.orm.xml index 8dc6f7dfc6..fecf175caa 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/pojos/Planet.orm.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/pojos/Planet.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/planet-business/src/main/resources/org/apache/roller/planet/pojos/PlanetGroup.orm.xml b/planet-business/src/main/resources/org/apache/roller/planet/pojos/PlanetGroup.orm.xml index 6a95729cc6..6893985018 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/pojos/PlanetGroup.orm.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/pojos/PlanetGroup.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/planet-business/src/main/resources/org/apache/roller/planet/pojos/RuntimeConfigProperty.orm.xml b/planet-business/src/main/resources/org/apache/roller/planet/pojos/RuntimeConfigProperty.orm.xml index da43c2d80b..af5432b392 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/pojos/RuntimeConfigProperty.orm.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/pojos/RuntimeConfigProperty.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/planet-business/src/main/resources/org/apache/roller/planet/pojos/Subscription.orm.xml b/planet-business/src/main/resources/org/apache/roller/planet/pojos/Subscription.orm.xml index 7eaab33a94..9c7b4ebee7 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/pojos/Subscription.orm.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/pojos/Subscription.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/planet-business/src/main/resources/org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml b/planet-business/src/main/resources/org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml index 49962263da..6c7b805868 100644 --- a/planet-business/src/main/resources/org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml +++ b/planet-business/src/main/resources/org/apache/roller/planet/pojos/SubscriptionEntry.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -70,7 +70,7 @@ - + diff --git a/planet-business/src/test/java/org/apache/roller/planet/TestUtils.java b/planet-business/src/test/java/org/apache/roller/planet/TestUtils.java index e9d63ed839..e27a95a2a1 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/TestUtils.java +++ b/planet-business/src/test/java/org/apache/roller/planet/TestUtils.java @@ -31,32 +31,32 @@ * Utility class for unit test classes. */ public final class TestUtils { - - + + public static void setupPlanet() throws Exception { - + if(!PlanetFactory.isBootstrapped()) { - + // do core services preparation PlanetStartup.prepare(); - + // do application bootstrapping and init PlanetFactory.bootstrap(); - + // always initialize the properties manager and flush PlanetFactory.getPlanet().getPropertiesManager().initialize(); PlanetFactory.getPlanet().flush(); } } - - + + public static void shutdownPlanet() throws Exception { - + // trigger shutdown PlanetFactory.getPlanet().shutdown(); } - - + + /** * Convenience method that simulates the end of a typical session. * @@ -66,158 +66,158 @@ public static void shutdownPlanet() throws Exception { * @param flush true if you want to flush changes to db before releasing */ public static void endSession(boolean flush) throws Exception { - + if(flush) { PlanetFactory.getPlanet().flush(); } - + PlanetFactory.getPlanet().release(); } - - + + /** * Convenience method that creates a planet and stores it. */ public static Planet setupPlanet(String handle) throws Exception { - + Planet testPlanet = new Planet(handle, handle, handle); - + // store PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); mgr.savePlanet(testPlanet); - + // flush PlanetFactory.getPlanet().flush(); - + // query to make sure we return the persisted object Planet planet = mgr.getPlanet(handle); - + if(planet == null) throw new PlanetException("error inserting new planet"); - + return planet; } - - + + /** * Convenience method for removing a planet. */ public static void teardownPlanet(String id) throws Exception { - + // lookup PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Planet planet = mgr.getPlanetById(id); - + // remove mgr.deletePlanet(planet); - + // flush PlanetFactory.getPlanet().flush(); } - - + + /** * Convenience method that creates a group and stores it. */ - public static PlanetGroup setupGroup(Planet planet, String handle) + public static PlanetGroup setupGroup(Planet planet, String handle) throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // make sure we are using a persistent object Planet testPlanet = mgr.getPlanetById(planet.getId()); - + // store PlanetGroup testGroup = new PlanetGroup(testPlanet, handle, handle, handle); testPlanet.getGroups().add(testGroup); mgr.saveGroup(testGroup); - + // flush PlanetFactory.getPlanet().flush(); - + // query to make sure we return the persisted object PlanetGroup group = mgr.getGroupById(testGroup.getId()); - + if(group == null) throw new PlanetException("error inserting new group"); - + return group; } - - + + /** * Convenience method for removing a group. */ public static void teardownGroup(String id) throws Exception { - + // lookup PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); PlanetGroup group = mgr.getGroupById(id); - + // remove mgr.deleteGroup(group); group.getPlanet().getGroups().remove(group); - + // flush PlanetFactory.getPlanet().flush(); } - - + + /** * Convenience method that creates a sub and stores it. */ - public static Subscription setupSubscription(String feedUrl) + public static Subscription setupSubscription(String feedUrl) throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // store Subscription testSub = new Subscription(); testSub.setFeedURL(feedUrl); testSub.setTitle(feedUrl); mgr.saveSubscription(testSub); - + // flush PlanetFactory.getPlanet().flush(); - + // query to make sure we return the persisted object Subscription sub = mgr.getSubscriptionById(testSub.getId()); - + if(sub == null) throw new PlanetException("error inserting new subscription"); - + return sub; } - - + + /** * Convenience method for removing a sub. */ public static void teardownSubscription(String id) throws Exception { - + // lookup PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Subscription sub = mgr.getSubscriptionById(id); - + // remove mgr.deleteSubscription(sub); - + // flush PlanetFactory.getPlanet().flush(); } - - + + /** * Convenience method that creates an entry and stores it. */ - public static SubscriptionEntry setupEntry(Subscription sub, String title) + public static SubscriptionEntry setupEntry(Subscription sub, String title) throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // make sure we are using a persistent object Subscription testSub = mgr.getSubscriptionById(sub.getId()); - + // store SubscriptionEntry testEntry = new SubscriptionEntry(); testEntry.setPermalink(title); @@ -226,39 +226,39 @@ public static SubscriptionEntry setupEntry(Subscription sub, String title) testEntry.setSubscription(testSub); testSub.getEntries().add(testEntry); mgr.saveEntry(testEntry); - + // flush PlanetFactory.getPlanet().flush(); - + // query to make sure we return the persisted object SubscriptionEntry entry = mgr.getEntryById(testEntry.getId()); - + if(entry == null) throw new PlanetException("error inserting new entry"); - + return entry; } - - + + /** * Convenience method for removing an entry. */ public static void teardownEntry(String id) throws Exception { - + // lookup PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); SubscriptionEntry entry = mgr.getEntryById(id); - + // remove mgr.deleteEntry(entry); entry.getSubscription().getEntries().remove(entry); - + // flush PlanetFactory.getPlanet().flush(); } - + public void testNothing() { // TODO: remove this method } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/EntryBasicTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/EntryBasicTests.java index 63f3feee1a..968b97bd9e 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/EntryBasicTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/EntryBasicTests.java @@ -27,63 +27,63 @@ * Test Entry CRUD. */ public class EntryBasicTests extends TestCase { - + private Subscription testSub = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); - + testSub = TestUtils.setupSubscription("entryBasicTest"); } - - + + protected void tearDown() throws Exception { TestUtils.teardownSubscription(testSub.getId()); } - - + + public void testEntryCRUD() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Subscription sub = mgr.getSubscriptionById(testSub.getId()); - + SubscriptionEntry testEntry = new SubscriptionEntry(); testEntry.setPermalink("entryBasics"); testEntry.setTitle("entryBasics"); testEntry.setPubTime(new java.sql.Timestamp(System.currentTimeMillis())); testEntry.setSubscription(sub); - + // add mgr.saveEntry(testEntry); TestUtils.endSession(true); - + // verify SubscriptionEntry entry = null; entry = mgr.getEntryById(testEntry.getId()); assertNotNull(entry); assertEquals("entryBasics", entry.getPermalink()); - + // modify entry.setTitle("foo"); mgr.saveEntry(entry); TestUtils.endSession(true); - + // verify entry = null; entry = mgr.getEntryById(testEntry.getId()); assertNotNull(entry); assertEquals("foo", entry.getTitle()); - + // remove mgr.deleteEntry(entry); TestUtils.endSession(true); - + // verify entry = null; entry = mgr.getEntryById(testEntry.getId()); assertNull(entry); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/EntryFunctionalTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/EntryFunctionalTests.java index 67a633d7b7..f796f8c9c5 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/EntryFunctionalTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/EntryFunctionalTests.java @@ -31,9 +31,9 @@ * Test planet Entry functionality. */ public class EntryFunctionalTests extends TestCase { - + public static Log log = LogFactory.getLog(EntryFunctionalTests.class); - + private Planet testPlanet = null; private PlanetGroup testGroup1 = null; private Subscription testSub1 = null; @@ -41,14 +41,14 @@ public class EntryFunctionalTests extends TestCase { private SubscriptionEntry testEntry1 = null; private SubscriptionEntry testEntry2 = null; private SubscriptionEntry testEntry3 = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); log.info("ENTERED"); - + testPlanet = TestUtils.setupPlanet("entryFuncTestPlanet"); testGroup1 = TestUtils.setupGroup(testPlanet, "entryFuncTestGroup"); testSub1 = TestUtils.setupSubscription("entryFuncTestSub1"); @@ -56,73 +56,73 @@ protected void setUp() throws Exception { testEntry1 = TestUtils.setupEntry(testSub1, "entryFuncTestEntry1"); testEntry2 = TestUtils.setupEntry(testSub2, "entryFuncTestEntry2"); testEntry3 = TestUtils.setupEntry(testSub2, "entryFuncTestEntry3"); - + // now associate both subscriptions with the test group testGroup1.getSubscriptions().add(testSub1); testSub1.getGroups().add(testGroup1); - + testGroup1.getSubscriptions().add(testSub2); testSub2.getGroups().add(testGroup1); - + PlanetFactory.getPlanet().getPlanetManager().saveGroup(testGroup1); PlanetFactory.getPlanet().flush(); - + log.info("EXITED"); } - - + + protected void tearDown() throws Exception { log.info("ENTERED"); - + TestUtils.teardownSubscription(testSub1.getId()); TestUtils.teardownSubscription(testSub2.getId()); TestUtils.teardownGroup(testGroup1.getId()); TestUtils.teardownPlanet(testPlanet.getId()); - + log.info("EXITED"); } - - + + public void testEntryLookups() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // by id SubscriptionEntry entry = mgr.getEntryById(testEntry1.getId()); assertNotNull(entry); assertEquals("entryFuncTestEntry1", entry.getPermalink()); - + // by subscription Subscription sub = mgr.getSubscriptionById(testSub2.getId()); assertEquals(2, sub.getEntries().size()); - + // by subscription through manager assertEquals(2, mgr.getEntries(sub, 0, 10).size()); - + // by group PlanetGroup group = mgr.getGroupById(testGroup1.getId()); assertEquals(3, mgr.getEntries(group, 0, 10).size()); - + // by group with timeframe constraint assertEquals(0, mgr.getEntries(group, new Date(), null, 0, 10).size()); } - - + + public void testDeleteEntries() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Subscription sub = mgr.getSubscriptionById(testSub2.getId()); - + // make sure entries are there assertEquals(2, sub.getEntries().size()); - + // purge entries mgr.deleteEntries(sub); TestUtils.endSession(true); - + // verify sub = mgr.getSubscriptionById(testSub2.getId()); assertEquals(0, sub.getEntries().size()); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/GroupBasicTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/GroupBasicTests.java index 8494904c08..98d9a487c2 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/GroupBasicTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/GroupBasicTests.java @@ -27,67 +27,67 @@ * Test Group CRUD. */ public class GroupBasicTests extends TestCase { - + private Planet testPlanet = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); testPlanet = TestUtils.setupPlanet("groupBasicTest"); } - - + + protected void tearDown() throws Exception { TestUtils.teardownPlanet(testPlanet.getId()); } - - + + public void testGroupCRUD() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + PlanetGroup testGroup = new PlanetGroup(); testGroup.setDescription("test_group_desc"); testGroup.setHandle("test_handle"); testGroup.setTitle("test_title"); testGroup.setPlanet(testPlanet); PlanetGroup group = null; - + group = mgr.getGroup(testPlanet, "test_handle"); assertNull(group); - + // add mgr.saveGroup(testGroup); TestUtils.endSession(true); - + // verify group = null; group = mgr.getGroupById(testGroup.getId()); assertNotNull(group); assertEquals("test_handle", group.getHandle()); assertEquals(testPlanet.getId(), group.getPlanet().getId()); - + // modify group.setTitle("foo"); mgr.saveGroup(group); TestUtils.endSession(true); - + // verify group = null; group = mgr.getGroupById(testGroup.getId()); assertNotNull(group); assertEquals("foo", group.getTitle()); - + // remove mgr.deleteGroup(group); TestUtils.endSession(true); - + // verify group = null; group = mgr.getGroupById(testGroup.getId()); assertNull(group); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/GroupFunctionalTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/GroupFunctionalTests.java index 6d826d9b5b..29638a8767 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/GroupFunctionalTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/GroupFunctionalTests.java @@ -27,12 +27,12 @@ * Test planet Group functionality. */ public class GroupFunctionalTests extends TestCase { - + private Planet testPlanet = null; private PlanetGroup testGroup1 = null; private PlanetGroup testGroup2 = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); @@ -41,35 +41,35 @@ protected void setUp() throws Exception { testGroup1 = TestUtils.setupGroup(testPlanet, "groupFuncTest1"); testGroup2 = TestUtils.setupGroup(testPlanet, "groupFuncTest2"); } - - + + protected void tearDown() throws Exception { TestUtils.teardownGroup(testGroup1.getId()); TestUtils.teardownGroup(testGroup2.getId()); TestUtils.teardownPlanet(testPlanet.getId()); } - - + + public void testGroupLookups() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // lookup group by id PlanetGroup group = mgr.getGroupById(testGroup1.getId()); assertNotNull(group); assertEquals("groupFuncTest1", group.getHandle()); - + // lookup group by planet & handle group = null; group = mgr.getGroup(testPlanet, testGroup1.getHandle()); assertNotNull(group); assertEquals("groupFuncTest1", group.getHandle()); - + // lookup all groups in planet Planet planet = mgr.getPlanetById(testPlanet.getId()); Set groups = planet.getGroups(); assertNotNull(groups); assertEquals(2, groups.size()); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetBasicTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetBasicTests.java index 174536a9c1..2052c5fb34 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetBasicTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetBasicTests.java @@ -28,52 +28,52 @@ * Test Planet CRUD. */ public class PlanetBasicTests extends TestCase { - + public static Log log = LogFactory.getLog(PlanetBasicTests.class); - - + + public void testPlanetCRUD() throws Exception { - + // setup planet TestUtils.setupPlanet(); PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + Planet testPlanet = new Planet("testPlanet", "testPlanet", "testPlanet"); Planet planet = null; - + planet = mgr.getPlanet("testPlanet"); assertNull(planet); - + // add mgr.savePlanet(testPlanet); TestUtils.endSession(true); - + // verify planet = null; planet = mgr.getPlanetById(testPlanet.getId()); assertNotNull(planet); assertEquals("testPlanet", planet.getHandle()); - + // modify planet.setTitle("foo"); mgr.savePlanet(planet); TestUtils.endSession(true); - + // verify planet = null; planet = mgr.getPlanetById(testPlanet.getId()); assertNotNull(planet); assertEquals("foo", planet.getTitle()); - + // remove mgr.deletePlanet(planet); TestUtils.endSession(true); - + // verify planet = null; planet = mgr.getPlanet(testPlanet.getId()); assertNull(planet); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetFunctionalTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetFunctionalTests.java index 0ef5cfc303..033037c479 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetFunctionalTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetFunctionalTests.java @@ -28,49 +28,49 @@ * Test Planet functionality. */ public class PlanetFunctionalTests extends TestCase { - + public static Log log = LogFactory.getLog(PlanetFunctionalTests.class); - + private Planet testPlanet = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); testPlanet = TestUtils.setupPlanet("planetFuncTest"); } - - + + protected void tearDown() throws Exception { TestUtils.teardownPlanet(testPlanet.getId()); } - - + + /** * Test lookup mechanisms. */ public void testPlanetLookups() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + Planet planet = null; - + // by id planet = mgr.getPlanetById(testPlanet.getId()); assertNotNull(planet); assertEquals("planetFuncTest", planet.getHandle()); - + // by handle planet = null; planet = mgr.getPlanet("planetFuncTest"); assertNotNull(planet); assertEquals("planetFuncTest", planet.getHandle()); - + // all planets List planets = mgr.getPlanets(); assertNotNull(planets); assertEquals(1, planets.size()); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetTestSuite.java b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetTestSuite.java index 3f20eebf42..fca7754850 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/PlanetTestSuite.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/PlanetTestSuite.java @@ -34,38 +34,38 @@ * weblog to do them. */ public class PlanetTestSuite { - + public static Test suite() { TestSuite suite = new TestSuite(); - + // TODO: add a test for PlanetConfig - + suite.addTestSuite(PropertiesTest.class); - + // planets suite.addTestSuite(PlanetBasicTests.class); suite.addTestSuite(PlanetFunctionalTests.class); - + // groups suite.addTestSuite(GroupBasicTests.class); suite.addTestSuite(GroupFunctionalTests.class); - + // subscriptions suite.addTestSuite(SubscriptionBasicTests.class); suite.addTestSuite(SubscriptionFunctionalTests.class); - + // entries suite.addTestSuite(EntryBasicTests.class); suite.addTestSuite(EntryFunctionalTests.class); - + // fetching suite.addTestSuite(RomeFeedFetcherTest.class); - + // updating suite.addTestSuite(SingleThreadedFeedUpdaterTest.class); - + return suite; } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/PropertiesTest.java b/planet-business/src/test/java/org/apache/roller/planet/business/PropertiesTest.java index 75f7591182..355c3068e5 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/PropertiesTest.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/PropertiesTest.java @@ -34,47 +34,47 @@ * Test Properties related business operations. */ public class PropertiesTest extends TestCase { - + public static Log log = LogFactory.getLog(PropertiesTest.class); - - + + public void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); } - + public void tearDown() throws Exception {} - - + + public void testProperiesCRUD() throws Exception { - + // remember, the properties table is initialized during Roller startup PropertiesManager mgr = PlanetFactory.getPlanet().getPropertiesManager(); TestUtils.endSession(true); - + RuntimeConfigProperty prop = null; - + // get a property by name prop = mgr.getProperty("site.name"); assertNotNull(prop); - + // update a property prop.setValue("testtest"); mgr.saveProperty(prop); TestUtils.endSession(true); - + // make sure property was updated prop = null; prop = mgr.getProperty("site.name"); assertNotNull(prop); assertEquals("testtest", prop.getValue()); - + // get all properties Map props = mgr.getProperties(); assertNotNull(props); assertTrue(props.containsKey("site.name")); - + // update multiple properties prop = (RuntimeConfigProperty) props.get("site.name"); prop.setValue("foofoo"); @@ -82,12 +82,12 @@ public void testProperiesCRUD() throws Exception { prop.setValue("blahblah"); mgr.saveProperties(props); TestUtils.endSession(true); - + // make sure all properties were updated props = mgr.getProperties(); assertNotNull(props); assertEquals("foofoo", ((RuntimeConfigProperty)props.get("site.name")).getValue()); assertEquals("blahblah", ((RuntimeConfigProperty)props.get("site.description")).getValue()); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/RomeFeedFetcherTest.java b/planet-business/src/test/java/org/apache/roller/planet/business/RomeFeedFetcherTest.java index 5a05378f96..8b5d26bda7 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/RomeFeedFetcherTest.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/RomeFeedFetcherTest.java @@ -28,24 +28,24 @@ * Test database implementation of PlanetManager. */ public class RomeFeedFetcherTest extends TestCase { - + public static Log log = LogFactory.getLog(RomeFeedFetcherTest.class); - + String feed_url = "http://rollerweblogger.org/roller/feed/entries/atom"; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); } - - + + protected void tearDown() throws Exception { } - - + + public void testFetchFeed() throws Exception { - + FeedFetcher feedFetcher = PlanetFactory.getPlanet().getFeedFetcher(); // fetch feed @@ -57,10 +57,10 @@ public void testFetchFeed() throws Exception { assertNotNull(sub.getLastUpdated()); assertTrue(sub.getEntries().size() > 0); } - - + + public void testFetchFeedConditionally() throws Exception { - + FeedFetcher feedFetcher = PlanetFactory.getPlanet().getFeedFetcher(); // fetch feed @@ -71,10 +71,10 @@ public void testFetchFeedConditionally() throws Exception { assertEquals("Blogging Roller", sub.getTitle()); assertNotNull(sub.getLastUpdated()); assertTrue(sub.getEntries().size() > 0); - + // now do a conditional fetch and we should get back null Subscription updatedSub = feedFetcher.fetchSubscription(feed_url, sub.getLastUpdated()); assertNull(updatedSub); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/SingleThreadedFeedUpdaterTest.java b/planet-business/src/test/java/org/apache/roller/planet/business/SingleThreadedFeedUpdaterTest.java index 60cde94cd8..16951c3930 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/SingleThreadedFeedUpdaterTest.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/SingleThreadedFeedUpdaterTest.java @@ -30,18 +30,18 @@ * Test feed updater. */ public class SingleThreadedFeedUpdaterTest extends TestCase { - + public static Log log = LogFactory.getLog(SingleThreadedFeedUpdaterTest.class); - + private Subscription testSub = null; - + private String feed_url = "http://rollerweblogger.org/roller/feed/entries/atom"; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); - + // add test subscription PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); testSub = new Subscription(); @@ -50,23 +50,23 @@ protected void setUp() throws Exception { mgr.saveSubscription(testSub); PlanetFactory.getPlanet().flush(); } - - + + protected void tearDown() throws Exception { TestUtils.teardownSubscription(testSub.getId()); } - - + + public void testUpdateSubscription() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Subscription sub = mgr.getSubscriptionById(testSub.getId()); - + // update the subscription FeedUpdater updater = new SingleThreadedFeedUpdater(); updater.updateSubscription(sub); TestUtils.endSession(true); - + // verify the results sub = mgr.getSubscription(feed_url); assertNotNull(sub); @@ -76,5 +76,5 @@ public void testUpdateSubscription() throws Exception { assertNotNull(sub.getLastUpdated()); assertTrue(sub.getEntries().size() > 0); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionBasicTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionBasicTests.java index 0ba26789bb..50735be60d 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionBasicTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionBasicTests.java @@ -25,52 +25,52 @@ * Test Subscription CRUD. */ public class SubscriptionBasicTests extends TestCase { - - + + public void testSubscriptionCRUD() throws Exception { - + // setup planet TestUtils.setupPlanet(); PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + Subscription testSub = new Subscription(); testSub.setFeedURL("test_title"); testSub.setTitle("test_title"); - + Subscription sub = mgr.getSubscription(testSub.getFeedURL()); assertNull(sub); - + // add mgr.saveSubscription(testSub); TestUtils.endSession(true); - + // verify sub = null; sub = mgr.getSubscriptionById(testSub.getId()); assertNotNull(sub); assertEquals("test_title", sub.getFeedURL()); - + // modify sub.setTitle("foo"); mgr.saveSubscription(sub); TestUtils.endSession(true); - + // verify sub = null; sub = mgr.getSubscriptionById(testSub.getId()); assertNotNull(sub); assertEquals("foo", sub.getTitle()); - + // remove mgr.deleteSubscription(sub); TestUtils.endSession(true); - + // verify sub = null; sub = mgr.getSubscriptionById(testSub.getId()); assertNull(sub); - + } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionFunctionalTests.java b/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionFunctionalTests.java index afebba52a9..0b76f0743c 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionFunctionalTests.java +++ b/planet-business/src/test/java/org/apache/roller/planet/business/SubscriptionFunctionalTests.java @@ -28,14 +28,14 @@ * Test Subscription functionality. */ public class SubscriptionFunctionalTests extends TestCase { - + private Planet testPlanet = null; private PlanetGroup testGroup1 = null; private PlanetGroup testGroup2 = null; private Subscription testSub1 = null; private Subscription testSub2 = null; - - + + protected void setUp() throws Exception { // setup planet TestUtils.setupPlanet(); @@ -46,8 +46,8 @@ protected void setUp() throws Exception { testSub1 = TestUtils.setupSubscription("subFuncTest1"); testSub2 = TestUtils.setupSubscription("subFuncTest2"); } - - + + protected void tearDown() throws Exception { TestUtils.teardownSubscription(testSub1.getId()); TestUtils.teardownSubscription(testSub2.getId()); @@ -55,71 +55,71 @@ protected void tearDown() throws Exception { TestUtils.teardownGroup(testGroup2.getId()); TestUtils.teardownPlanet(testPlanet.getId()); } - - + + public void testSubscriptionLookups() throws Exception { - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + // by id Subscription sub = mgr.getSubscriptionById(testSub1.getId()); assertNotNull(sub); assertEquals("subFuncTest1", sub.getFeedURL()); - + // by feed url sub = null; sub = mgr.getSubscription(testSub2.getFeedURL()); assertNotNull(sub); assertEquals("subFuncTest2", sub.getFeedURL()); - + // count assertEquals(2, mgr.getSubscriptionCount()); } - - + + public void testSubscriptionGroupCRUD() throws Exception { - + PlanetManager planet = PlanetFactory.getPlanet().getPlanetManager(); - + // retrieve subscriptions and add to group Subscription sub1 = planet.getSubscriptionById(testSub1.getId()); Subscription sub2 = planet.getSubscriptionById(testSub2.getId()); PlanetGroup group = planet.getGroupById(testGroup1.getId()); - + // make sure no subs in group yet assertEquals(0, group.getSubscriptions().size()); - + // add group.getSubscriptions().add(sub1); sub1.getGroups().add(group); group.getSubscriptions().add(sub2); sub2.getGroups().add(group); - + planet.saveGroup(group); TestUtils.endSession(true); - + // verify group = null; group = planet.getGroupById(testGroup1.getId()); sub1 = planet.getSubscriptionById(testSub1.getId()); sub2 = planet.getSubscriptionById(testSub2.getId()); assertEquals(2, group.getSubscriptions().size()); - + // remove group.getSubscriptions().remove(sub1); sub1.getGroups().remove(group); - + group.getSubscriptions().remove(sub2); sub2.getGroups().remove(group); planet.saveGroup(group); TestUtils.endSession(true); - + // verify group = null; group = planet.getGroupById(testGroup1.getId()); assertEquals(0, group.getSubscriptions().size()); } - + } diff --git a/planet-business/src/test/java/org/apache/roller/planet/util/rome/DiskFeedInfoCacheTest.java b/planet-business/src/test/java/org/apache/roller/planet/util/rome/DiskFeedInfoCacheTest.java index f9e3d2728e..084dca433f 100644 --- a/planet-business/src/test/java/org/apache/roller/planet/util/rome/DiskFeedInfoCacheTest.java +++ b/planet-business/src/test/java/org/apache/roller/planet/util/rome/DiskFeedInfoCacheTest.java @@ -30,35 +30,35 @@ * @author David M Johnson */ public class DiskFeedInfoCacheTest extends TestCase { - + public static void main(String[] args) { junit.textui.TestRunner.run(DiskFeedInfoCacheTest.class); } - + public void testCache() throws Exception { URL url = new URL("http://cnn.com"); SyndFeedInfo info = new SyndFeedInfo(); info.setUrl(url); - + String testPlanetCache = PlanetConfig.getProperty("cache.dir"); assertNotNull("testPlanetCache not null", testPlanetCache); assertTrue("testPlanetCache not zero length", testPlanetCache.trim().length() > 0); - + File cacheDir = new File(testPlanetCache); if (!cacheDir.exists()) cacheDir.mkdirs(); - + DiskFeedInfoCache cache = new DiskFeedInfoCache(PlanetConfig.getProperty("cache.dir")); cache.setFeedInfo(info.getUrl(), info); - + SyndFeedInfo info2 = cache.getFeedInfo(url); assertNotNull(info2); assertEquals(url, info2.getUrl()); } - + public static Test suite() { return new TestSuite(DiskFeedInfoCacheTest.class); - + } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/ConfigForm.java b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/ConfigForm.java index d5058b84af..847735e342 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/ConfigForm.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/ConfigForm.java @@ -39,34 +39,34 @@ * * TODO: validation and security. */ -public class ConfigForm extends PlanetActionSupport +public class ConfigForm extends PlanetActionSupport implements Preparable, ParameterAware { - + private static Log log = LogFactory.getLog(ConfigForm.class); - + // original request parameters private Map parameters = Collections.EMPTY_MAP; - + // runtime properties data private Map properties = Collections.EMPTY_MAP; - - + + public void prepare() throws Exception { // just grab our properties map and put it in the request PropertiesManager pMgr = PlanetFactory.getPlanet().getPropertiesManager(); this.properties = pMgr.getProperties(); } - + public String execute() { return INPUT; } - - + + public String save() { - + log.debug("Handling update request"); - + try { // only set values for properties that are already defined String propName = null; @@ -75,52 +75,52 @@ public String save() { Iterator propsIT = this.properties.keySet().iterator(); while(propsIT.hasNext()) { propName = (String) propsIT.next(); - + log.debug("Checking property ["+propName+"]"); - + updProp = (RuntimeConfigProperty) this.properties.get(propName); String[] propValues = (String[]) this.parameters.get(updProp.getName()); if(propValues != null && propValues.length > 0) { // we don't deal with multi-valued props incomingProp = propValues[0]; } - + // some special treatment for booleans // this is a bit hacky since we are assuming that any prop // with a value of "true" or "false" is meant to be a boolean // it may not always be the case, but we should be okay for now if( updProp.getValue() != null // null check needed w/Oracle && (updProp.getValue().equals("true") || updProp.getValue().equals("false"))) { - + if(incomingProp == null || !incomingProp.equals("on")) incomingProp = "false"; else incomingProp = "true"; } - + // only work on props that were submitted with the request if(incomingProp != null) { log.debug("Setting new value for ["+propName+"]"); - + updProp.setValue(incomingProp.trim()); } } - + // save it PropertiesManager pMgr = PlanetFactory.getPlanet().getPropertiesManager(); pMgr.saveProperties(this.properties); PlanetFactory.getPlanet().flush(); - + } catch (PlanetException e) { log.error(e); setError("ConfigForm.error.saveFailed"); } - + setSuccess("ConfigForm.message.saveSucceeded"); return INPUT; } - + public Map getParameters() { return parameters; } @@ -136,5 +136,5 @@ public Map getProperties() { public void setProperties(Map properties) { this.properties = properties; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm-PlanetForm!save-validation.xml b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm-PlanetForm!save-validation.xml index ed7f6f578e..74b1374a76 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm-PlanetForm!save-validation.xml +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm-PlanetForm!save-validation.xml @@ -1,16 +1,16 @@ - + - + true handle is required - + 32 @@ -18,16 +18,16 @@ handle must be less than 32 characters - + - + true title is required - + 255 @@ -35,10 +35,10 @@ title must be less than 255 characters - + - + 255 diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm.java b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm.java index 08769e77e5..1adde647f1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetForm.java @@ -37,25 +37,25 @@ * TODO: validation and security. */ public class PlanetForm extends PlanetActionSupport implements Preparable { - + private static Log log = LogFactory.getLog(PlanetForm.class); - + // the objects to work on private Planet planet = null; private PlanetGroup group = null; - + // form fields private String planetid = null; private String groupid = null; - - + + /** * Load relevant form data if possible. */ public void prepare() throws Exception { - + PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); - + // load existing planet if(getPlanetid() != null && !"".equals(getPlanetid())) { log.debug("Loading Planet ... "+getPlanetid()); @@ -66,26 +66,26 @@ public void prepare() throws Exception { this.planet = new Planet(); } } - - + + public String execute() { return INPUT; } - - + + // TODO: Validation - check that planet handle is unique // TODO: Validation - make sure html is not allowed in handle or title public String save() { - + if(this.planet != null) { // save planet log.debug("Saving Planet ..."); - + try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); pmgr.savePlanet(this.planet); PlanetFactory.getPlanet().flush(); - + // need to set planetid attribute setPlanetid(this.planet.getId()); } catch (PlanetException ex) { @@ -93,7 +93,7 @@ public String save() { setError("PlanetForm.error.saveFailed"); return INPUT; } - + setSuccess("PlanetForm.message.saveSucceeded"); return INPUT; } else { @@ -102,14 +102,14 @@ public String save() { } } - - + + public String deleteGroup() { - + if(getGroupid() != null && !"".equals(getGroupid())) { // delete a planet group log.debug("Deleting Planet Group ... "+getGroupid()); - + PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); try { PlanetGroup group = pmgr.getGroupById(getGroupid()); @@ -118,7 +118,7 @@ public String deleteGroup() { pmgr.savePlanet(this.planet); pmgr.deleteGroup(group); PlanetFactory.getPlanet().flush(); - + setSuccess("PlanetForm.message.groupDeleteSucceeded", group.getHandle()); return INPUT; } catch (PlanetException ex) { @@ -126,7 +126,7 @@ public String deleteGroup() { setError("PlanetForm.error.groupDeleteFailed", getGroupid()); return INPUT; } - + } else { setError("PlanetForm.error.groupNull"); return INPUT; @@ -148,7 +148,7 @@ public String getGroupid() { public void setGroupid(String groupid) { this.groupid = groupid; } - + public Planet getPlanet() { return planet; } @@ -156,5 +156,5 @@ public Planet getPlanet() { public void setPlanet(Planet planet) { this.planet = planet; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm-PlanetGroupForm!save-validation.xml b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm-PlanetGroupForm!save-validation.xml index c4e6412b17..89d11a205e 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm-PlanetGroupForm!save-validation.xml +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm-PlanetGroupForm!save-validation.xml @@ -1,16 +1,16 @@ - + - + true handle is required - + 32 @@ -18,16 +18,16 @@ handle must be less than 32 characters - + - + true title is required - + 255 @@ -35,10 +35,10 @@ title must be less than 255 characters - + - + 255 @@ -46,15 +46,15 @@ description must be less than 255 characters - + - + maxPageEntries is required - + 1 @@ -62,15 +62,15 @@ maxPageEntries must be a number between 1 and 100 - + - + maxFeedEntries is required - + 1 @@ -78,5 +78,5 @@ maxFeedEntries must be a number between 1 and 100 - + \ No newline at end of file diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm.java b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm.java index 70b0625617..9b1c5cf3e4 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetGroupForm.java @@ -40,19 +40,19 @@ * TODO: validation and security. */ public class PlanetGroupForm extends PlanetActionSupport implements Preparable { - + private static Log log = LogFactory.getLog(PlanetGroupForm.class); - + // the PlanetGroup to work on private PlanetGroup group = null; - + // form fields private String planetid = null; private String groupid = null; private String subid = null; private String addSubUrl = null; - - + + /** * Load relevant Planet if possible. */ @@ -61,7 +61,7 @@ public void prepare() throws Exception { if(getGroupid() != null && !"".equals(getGroupid())) { // load a planet group log.debug("Loading Planet Group ..."); - + group = pMgr.getGroupById(getGroupid()); } else { // new group, must have a planet to add it to @@ -74,24 +74,24 @@ public void prepare() throws Exception { } } } - + public String execute() { return INPUT; } - - + + // TODO: Validation - check that group handle is unique within planet // TODO: Validation - make sure that html is not allowed in handle or title // TODO: Validation - make sure maxXXXEntries have a proper value range public String save() { // save a group group log.debug("Saving Planet Group ..."); - + try { PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); pMgr.saveGroup(this.group); PlanetFactory.getPlanet().flush(); - + // call setGroupid() just in case this was a new group with no id yet setGroupid(this.group.getId()); } catch (PlanetException ex) { @@ -99,17 +99,17 @@ public String save() { setError("PlanetGroupForm.error.saveFailed"); return INPUT; } - + setSuccess("PlanetGroupForm.message.saveSucceeded"); return INPUT; } - - + + // Validation - sub url cannot be null, must be valid url public String addSub() { // add a planet subscription log.debug("Adding Planet Subscription ..."); - + PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); try { PlanetGroup group = getGroup(); @@ -117,44 +117,44 @@ public String addSub() { setError("PlanetSubscriptionForm.error.groupNull"); return INPUT; } - + // check if this subscription already exists before adding it Subscription sub = pMgr.getSubscription(getAddSubUrl()); if(sub == null) { // sub doesn't exist yet, so we need to fetch it FeedFetcher fetcher = PlanetFactory.getPlanet().getFeedFetcher(); sub = fetcher.fetchSubscription(getAddSubUrl()); - + // save new sub pMgr.saveSubscription(sub); } - + // add the sub to the group group.getSubscriptions().add(sub); sub.getGroups().add(group); pMgr.saveGroup(group); - + // flush changes PlanetFactory.getPlanet().flush(); - + // clear field after success setAddSubUrl(null); - + } catch (PlanetException ex) { log.error("Error adding subscription", ex); setError("PlanetSubscriptionForm.error.saveFailed"); return INPUT; } - + setSuccess("PlanetSubscriptionForm.message.saveSucceeded"); return INPUT; } - - + + public String deleteSub() { // delete a planet subscription log.debug("Deleting Planet Subscription ..."); - + PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); try { if(!StringUtils.isEmpty(getSubid())) { @@ -169,21 +169,21 @@ public String deleteSub() { pmgr.saveGroup(group); PlanetFactory.getPlanet().flush(); } - + setSuccess("PlanetGroupForm.message.subscriptionDeleteSucceeded", sub.getTitle()); } else { setError("PlanetGroupForm.error.subscriptionNull"); } - + return INPUT; - + } catch (PlanetException ex) { log.error("Unable to lookup planet group", ex); setError("PlanetGroupForm.error.subscriptionDeleteFailed", getSubid()); return INPUT; } } - + public String getPlanetid() { return planetid; @@ -208,7 +208,7 @@ public String getSubid() { public void setSubid(String subid) { this.subid = subid; } - + public PlanetGroup getGroup() { return group; } @@ -224,5 +224,5 @@ public String getAddSubUrl() { public void setAddSubUrl(String addSubUrl) { this.addSubUrl = addSubUrl; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm-PlanetSubscriptionForm!save-validation.xml b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm-PlanetSubscriptionForm!save-validation.xml index f8bac395d8..150ff354c7 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm-PlanetSubscriptionForm!save-validation.xml +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm-PlanetSubscriptionForm!save-validation.xml @@ -1,16 +1,16 @@ - + - + true title is required - + 255 @@ -18,21 +18,21 @@ title must be less than 255 characters - + - + true feedURL is required - + feedURL must be a valid url - + 255 @@ -40,15 +40,15 @@ feedURL must be less than 255 characters - + - + siteURL must be a valid url - + 255 @@ -56,7 +56,7 @@ siteURL must be less than 255 characters - - - + + + \ No newline at end of file diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm.java b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm.java index 5b86579605..4d7d6d82e1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetSubscriptionForm.java @@ -31,23 +31,23 @@ /** * Planet Sub Form Action. - * + * * Handles adding/modifying subscriptions for a group. * * TODO: validation and security. */ public class PlanetSubscriptionForm extends PlanetActionSupport implements Preparable { - + private static Log log = LogFactory.getLog(PlanetSubscriptionForm.class); - + // the Subscription to work on private Subscription subscription = null; - + // form fields private String groupid = null; private String subid = null; - - + + /** * Load relevant Subscription if possible. */ @@ -56,23 +56,23 @@ public void prepare() throws Exception { if(getSubid() != null && !"".equals(getSubid())) { // load a planet subscription log.debug("Loading Planet Subscription ..."); - + subscription = pMgr.getSubscriptionById(getSubid()); } else { subscription = new Subscription(); } } - + public String execute() { return INPUT; } - - + + // TODO: Validation - make sure that html is not allowed in title public String save() { // save a subscription log.debug("Saving Planet Subscription ..."); - + PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); try { if(this.subscription.getId() == null) { @@ -82,28 +82,28 @@ public String save() { setError("PlanetSubscriptionForm.error.groupNull"); return INPUT; } - + // check if this subscription already exists before adding it Subscription sub = pMgr.getSubscription(this.subscription.getFeedURL()); if(sub != null) { this.subscription = sub; } else { pMgr.saveSubscription(this.subscription); - + // set subid now that we have one setSubid(this.subscription.getId()); } - + // add the sub to the group group.getSubscriptions().add(this.subscription); this.subscription.getGroups().add(group); pMgr.saveGroup(group); - + } else { // updating and existing subscription, so just save it pMgr.saveSubscription(this.subscription); } - + // flush changes PlanetFactory.getPlanet().flush(); } catch (PlanetException ex) { @@ -111,7 +111,7 @@ public String save() { setError("PlanetSubscriptionForm.error.saveFailed"); return INPUT; } - + setSuccess("PlanetSubscriptionForm.message.saveSucceeded"); return INPUT; } @@ -139,5 +139,5 @@ public Subscription getSubscription() { public void setSubscription(Subscription subscription) { this.subscription = subscription; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetsList.java b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetsList.java index 256749e234..17b440b5d5 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetsList.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/admin/struts2/PlanetsList.java @@ -37,16 +37,16 @@ * TODO: validation and security. */ public class PlanetsList extends PlanetActionSupport { - + private static Log log = LogFactory.getLog(PlanetsList.class); - + private static final String LIST = "list"; - + // action properties private String planetid = null; private Collection planets = Collections.EMPTY_LIST; - - + + public String execute() { try { PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); @@ -57,20 +57,20 @@ public String execute() { log.error("PlanetsList.error.general", e); return LIST; } - + return LIST; } - - + + /** * Delete a planet. */ public String deletePlanet() { - + if(getPlanetid() != null && getPlanetid().length() > 0) { // delete a planet log.debug("Deleting Planet ... "+getPlanetid()); - + try { PlanetManager pMgr = PlanetFactory.getPlanet().getPlanetManager(); Planet planet = pMgr.getPlanetById(getPlanetid()); @@ -78,7 +78,7 @@ public String deletePlanet() { pMgr.deletePlanet(planet); PlanetFactory.getPlanet().flush(); } - + // delete succeeded, handle rest of request as usual setSuccess("PlanetsList.message.planetDeleteSucceeded", planet.getHandle()); return execute(); @@ -87,19 +87,19 @@ public String deletePlanet() { setError("PlanetsList.error.planetDeleteFailed", getPlanetid()); return LIST; } - + } else { setError("PlanetsList.error.planetNull"); return execute(); } - + } - - + + public Collection getPlanets() { return this.planets; } - + private void setPlanets(Collection planets) { this.planets = planets; } @@ -111,5 +111,5 @@ public String getPlanetid() { public void setPlanetid(String planetid) { this.planetid = planetid; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/PlanetContext.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/PlanetContext.java index 9dc4eceea0..dabc2f6d42 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/PlanetContext.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/PlanetContext.java @@ -34,20 +34,20 @@ /** * Responds to app init/destroy events and holds Roller instance. */ -public class PlanetContext extends ContextLoaderListener +public class PlanetContext extends ContextLoaderListener implements ServletContextListener { - + private static Log log = LogFactory.getLog(PlanetContext.class); - + // reference to ServletContext object private static ServletContext context = null; - - + + public PlanetContext() { super(); } - - + + /** * Get the ServletContext. * @@ -56,33 +56,33 @@ public PlanetContext() { public static ServletContext getServletContext() { return context; } - + /** * Responds to context initialization event by processing context * paramters for easy access by the rest of the application. */ public void contextInitialized(ServletContextEvent sce) { - + log.info("Roller Planet Initializing ... "); - + // keep a reverence to ServletContext object this.context = sce.getServletContext(); - + // call Spring's context ContextLoaderListener to initialize // all the context files specified in web.xml. This is necessary // because listeners don't initialize in the order specified in // 2.3 containers super.contextInitialized(sce); - + // Now prepare the core services of the app so we can bootstrap try { PlanetStartup.prepare(); } catch (StartupException ex) { log.fatal("Roller Planet startup failed during app preparation", ex); return; - } - + } + // if preparation failed or is incomplete then we are done, // otherwise try to bootstrap the business tier if (!PlanetStartup.isPrepared()) { @@ -91,23 +91,23 @@ public void contextInitialized(ServletContextEvent sce) { try { // trigger bootstrapping process PlanetFactory.bootstrap(); - + // trigger initialization process PlanetFactory.getPlanet().initialize(); - + } catch (BootstrapException ex) { log.fatal("Roller PlanetFactory bootstrap failed", ex); } catch (PlanetException ex) { log.fatal("Roller PlanetFactory initialization failed", ex); } } - + log.info("Roller Planet Initialization Complete"); } - - - /** - * Responds to app-destroy. + + + /** + * Responds to app-destroy. */ public void contextDestroyed(ServletContextEvent sce) { PlanetFactory.getPlanet().shutdown(); diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/DebugFilter.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/DebugFilter.java index 243d7250c1..41983ed1f6 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/DebugFilter.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/DebugFilter.java @@ -37,26 +37,26 @@ * Used for debugging, not mapped by default. */ public class DebugFilter implements Filter { - + private static Log log = LogFactory.getLog(DebugFilter.class); - - + + public void init(FilterConfig filterConfig) { - + } - - + + /** * Inspect incoming urls and see if they should be routed. */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.info("entering"); - + // print out session details HttpSession session = request.getSession(false); if(session != null) { @@ -67,10 +67,10 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) log.info(attr+" = "+session.getAttribute("attr")); } } - + // keep going chain.doFilter(request, response); - + // print out session details session = request.getSession(false); if(session != null) { @@ -81,11 +81,11 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) log.info(attr+" = "+session.getAttribute("attr")); } } - + log.info("exiting"); } - - + + public void destroy() {} - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/PersistenceSessionFilter.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/PersistenceSessionFilter.java index df337edd31..da9c6f7ae1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/PersistenceSessionFilter.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/filters/PersistenceSessionFilter.java @@ -38,21 +38,21 @@ * persistence session is released at end of the request. */ public class PersistenceSessionFilter implements Filter { - + private static Log log = LogFactory.getLog(PersistenceSessionFilter.class); - - + + /** * Release Roller persistence session at end of request processing. */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.debug("Entered PersistenceSessionFilter"); - + Planet planet = PlanetFactory.getPlanet(); try { chain.doFilter(request, response); @@ -62,14 +62,14 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) PlanetFactory.getPlanet().release(); } } - + log.debug("Exiting PersistenceSessionFilter"); } - - + + public void init(FilterConfig filterConfig) throws ServletException {} - + public void destroy() {} - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Login.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Login.java index c8b78c244c..14426c45c2 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Login.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Login.java @@ -25,10 +25,10 @@ * Login Action. */ public class Login extends PlanetActionSupport { - + private boolean failed = false; - - + + public String execute() { // nothing to do right now return SUCCESS; @@ -41,5 +41,5 @@ public boolean isFailed() { public void setFailed(boolean failed) { this.failed = failed; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Logout.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Logout.java index d4b830cc82..f32445a5c7 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Logout.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/Logout.java @@ -25,10 +25,10 @@ * Logout Action. */ public class Logout extends ActionSupport { - + public String execute() { // nothing to do right now return SUCCESS; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/MainMenu.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/MainMenu.java index 3bd46cccf3..66da8dbf1d 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/MainMenu.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/MainMenu.java @@ -25,10 +25,10 @@ * Menu Action. */ public class MainMenu extends ActionSupport { - + public String execute() { // nothing to do right now return SUCCESS; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/PlanetActionSupport.java b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/PlanetActionSupport.java index b74a837eb2..e3998973ac 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/PlanetActionSupport.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/core/struts2/PlanetActionSupport.java @@ -26,19 +26,19 @@ * Extends the Struts2 ActionSupport class to add in support for handling an * error and status success. Other actions extending this one only need to * calle setError() and setSuccess() accordingly. - * + * * NOTE: as a small convenience, all errors and messages are assumed to be keys * which point to a success in a resource bundle, so we automatically call * getText(key) on the param passed into setError() and setSuccess(). */ public abstract class PlanetActionSupport extends ActionSupport { - + // status params private String error = null; private String warning = null; private String success = null; - - + + public String getError() { return error; } @@ -46,11 +46,11 @@ public String getError() { public void setError(String error) { this.error = getText(error); } - + public void setError(String error, String param) { this.error = getText(error, error, param); } - + public String getWarning() { return warning; } @@ -58,11 +58,11 @@ public String getWarning() { public void setWarning(String warning) { this.warning = getText(warning); } - + public void setWarning(String warning, String param) { this.warning = getText(warning, warning, param); } - + public String getSuccess() { return success; } @@ -70,9 +70,9 @@ public String getSuccess() { public void setSuccess(String message) { this.success = getText(message); } - + public void setSuccess(String message, String param) { this.success = getText(message, message, param); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/MultiPlanetRequestMapper.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/MultiPlanetRequestMapper.java index 24a32079de..c5c4969720 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/MultiPlanetRequestMapper.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/MultiPlanetRequestMapper.java @@ -42,23 +42,23 @@ * request. */ public class MultiPlanetRequestMapper implements RequestMapper { - + private static Log log = LogFactory.getLog(MultiPlanetRequestMapper.class); - + private static final String PAGE_SERVLET = "/planet-ui/rendering/page"; private static final String FEED_SERVLET = "/planet-ui/rendering/feed"; private static final String OPML_SERVLET = "/planet-ui/rendering/opml"; - + // url patterns that are not allowed to be considered planet handles Set restricted = null; - - + + public MultiPlanetRequestMapper() { - + this.restricted = new HashSet(); - + // build roller restricted list - String restrictList = + String restrictList = PlanetConfig.getProperty("rendering.multiPlanetMapper.rollerProtectedUrls"); if(restrictList != null && restrictList.trim().length() > 0) { String[] restrict = restrictList.split(","); @@ -66,9 +66,9 @@ public MultiPlanetRequestMapper() { this.restricted.add(restrict[i]); } } - + // add user restricted list - restrictList = + restrictList = PlanetConfig.getProperty("rendering.multiPlanetMapper.userProtectedUrls"); if(restrictList != null && restrictList.trim().length() > 0) { String[] restrict = restrictList.split(","); @@ -77,41 +77,41 @@ public MultiPlanetRequestMapper() { } } } - - + + public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + // kinda silly, but we need to keep track of whether or not the url had // a trailing slash so that we can act accordingly boolean trailingSlash = false; - + String planetHandle = null; String planetContext = null; String groupHandle = null; String groupContext = null; String extraRequestData = null; - + log.debug("evaluating ["+request.getRequestURI()+"]"); - + // figure out potential planet handle String uri = request.getRequestURI(); String pathInfo = null; - + if(uri != null && uri.trim().length() > 1) { - + if(request.getContextPath() != null) uri = uri.substring(request.getContextPath().length()); - + // strip off the leading slash uri = uri.substring(1); - + // strip off trailing slash if needed if(uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); trailingSlash = true; } - + if(uri.indexOf("/") != -1) { planetHandle = uri.substring(0, uri.indexOf("/")); pathInfo = uri.substring(uri.indexOf("/")+1); @@ -119,25 +119,25 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res planetHandle = uri; } } - + log.debug("potential planet handle = "+planetHandle); - + // check if it's a valid planet handle if(restricted.contains(planetHandle) || !this.isPlanet(planetHandle)) { log.debug("SKIPPED "+planetHandle); return false; } - + log.debug("PLANET_URL "+request.getServletPath()); - + // parse the rest of the url if(pathInfo != null) { - + // parse the next portion of the url // we expect //// String[] urlPath = pathInfo.split("/", 4); planetContext = urlPath[0]; - + if(urlPath.length == 2) { groupHandle = urlPath[1]; } else if(urlPath.length == 3) { @@ -149,51 +149,51 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res extraRequestData = urlPath[3]; } } - + // special handling for trailing slash issue // we need this because by http standards the urls /foo and /foo/ are // supposed to be considered different, so we must enforce that if( (planetContext == null && !trailingSlash) || (groupHandle != null && groupContext == null && !trailingSlash) ) { - - // this means someone referred to a planet or group index page + + // this means someone referred to a planet or group index page // with the shortest form of url / or //group/ // and we need to add a slash to the url and redirect String redirectUrl = request.getRequestURI() + "/"; if(request.getQueryString() != null) { redirectUrl += "?"+request.getQueryString(); } - + response.sendRedirect(redirectUrl); return true; - + } else if(groupContext != null && trailingSlash) { - // this means that someone has accessed a url and included a + // this means that someone has accessed a url and included a // trailing slash, like //group//feed/atom/ which is // not supported, so we need to offer up a 404 Not Found response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } - + // calculate forward url - String forwardUrl = calculateForwardUrl(request, planetHandle, + String forwardUrl = calculateForwardUrl(request, planetHandle, planetContext, groupHandle, groupContext, extraRequestData); - + // if we don't have a forward url then the request was invalid somehow if(forwardUrl == null) { return false; } - + // dispatch to forward url log.debug("forwarding to "+forwardUrl); RequestDispatcher dispatch = request.getRequestDispatcher(forwardUrl); dispatch.forward(request, response); - + // we dealt with this request ourselves, so return "true" return true; } - + /** * Convenience method for caculating the servlet forward url given a set * of information to make the decision with. @@ -201,24 +201,24 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res * handle is always assumed valid, all other params may be null. */ private String calculateForwardUrl(HttpServletRequest request, - String planetHandle, - String planetContext, - String groupHandle, - String groupContext, + String planetHandle, + String planetContext, + String groupHandle, + String groupContext, String data) { - + log.debug(planetHandle+","+planetContext+","+groupHandle+","+groupContext+","+data); - + StringBuffer forwardUrl = new StringBuffer(); - + // no context means planet homepage if(planetContext == null) { forwardUrl.append(PAGE_SERVLET); forwardUrl.append("/").append(planetHandle); - + // requests for a specific planet group } else if(planetContext.equals("group") && groupHandle != null) { - + // no group context means group homepage if(groupContext == null) { forwardUrl.append(PAGE_SERVLET); @@ -233,7 +233,7 @@ private String calculateForwardUrl(HttpServletRequest request, if(data != null) { forwardUrl.append("/").append(data); } - + // request for planet group opml descriptor } else if("opml".equals(groupContext)) { forwardUrl.append(OPML_SERVLET); @@ -242,45 +242,45 @@ private String calculateForwardUrl(HttpServletRequest request, if(data != null) { forwardUrl.append("/").append(data); } - + // unsupported planet group url } else { return null; } - + // unsupported planet url } else { return null; } - + log.debug("FORWARD_URL "+forwardUrl.toString()); - + return forwardUrl.toString(); } - - + + /** * convenience method which determines if the given string is a valid * planet handle. */ private boolean isPlanet(String planetHandle) { - + log.debug("checking planet handle "+planetHandle); - + boolean isPlanet = false; - + try { PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); Planet planet = mgr.getPlanet(planetHandle); - + if(planet != null) { isPlanet = true; } } catch(Exception ex) { // doesn't really matter to us why it's not a valid planet } - + return isPlanet; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/Renderer.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/Renderer.java index 7d0d4766e3..514905d12a 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/Renderer.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/Renderer.java @@ -26,8 +26,8 @@ * Interface representing a content renderer in Roller. */ public interface Renderer { - - + + /** * Render the content for this Renderer to the given Writer using * the given set of model objects. @@ -35,5 +35,5 @@ public interface Renderer { * Throws an exception if there is a problem during rendering. */ public void render(Map model, Writer writer) throws RenderingException; - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererFactory.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererFactory.java index adb4f55e12..81ff5f982b 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererFactory.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererFactory.java @@ -28,8 +28,8 @@ * what Renderer object should be used to render a given resource. */ public interface RendererFactory { - - + + /** * Get a Renderer that will handle the given Template. * If a RendererFactory does not have a Renderer which can handle the @@ -41,5 +41,5 @@ public interface RendererFactory { * report any relevant exceptions itself. */ public Renderer getRenderer(Template template); - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererManager.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererManager.java index 5f684cc818..25d6f74894 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererManager.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RendererManager.java @@ -32,28 +32,28 @@ /** * A governing class for Rollers rendering system. - * - * The purpose of the RendererManager is to provide a level of abstraction + * + * The purpose of the RendererManager is to provide a level of abstraction * between classes that are rendering content and the implementations of the * rendering technology. This allows us to provide easily pluggable rendering * implementations. */ public class RendererManager { - + private static Log log = LogFactory.getLog(RendererManager.class); - + // a set of all renderer factories we are consulting private static Set rendererFactories = new HashSet(); - - + + static { // lookup set of renderer factories we are going to use String rollerFactories = PlanetConfig.getProperty("rendering.rollerRendererFactories"); String userFactories = PlanetConfig.getProperty("rendering.userRendererFactories"); - + // instantiate user defined renderer factory classes if(userFactories != null && userFactories.trim().length() > 0) { - + RendererFactory rendererFactory = null; String[] uFactories = userFactories.split(","); for(int i=0; i < uFactories.length; i++) { @@ -69,10 +69,10 @@ public class RendererManager { } } } - + // instantiate roller standard renderer factory classes if(rollerFactories != null && rollerFactories.trim().length() > 0) { - + RendererFactory rendererFactory = null; String[] rFactories = rollerFactories.split(","); for(int i=0; i < rFactories.length; i++) { @@ -88,21 +88,21 @@ public class RendererManager { } } } - + if(rendererFactories.size() < 1) { // hmm ... failed to load any renderer factories? log.warn("Failed to load any renderer factories. "+ "Rendering probably won't function as you expect."); } - + log.info("Renderer Manager Initialized."); } - - + + // this class is non-instantiable private RendererManager() {} - - + + /** * Find the appropriate Renderer for the given content. * @@ -110,24 +110,24 @@ private RendererManager() {} * instance and tries to find a Renderer for the content. If no Renderer * can be found then we throw an exception. */ - public static Renderer getRenderer(Template template) + public static Renderer getRenderer(Template template) throws RenderingException { - + Renderer renderer = null; - + // iterate over our renderer factories and see if one of them // wants to handle this content Iterator factories = rendererFactories.iterator(); while(factories.hasNext()) { renderer = ((RendererFactory)factories.next()).getRenderer(template); - + if(renderer != null) { return renderer; } } - + throw new RenderingException("No renderer found for template "+ template.getId()+"!"); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RenderingException.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RenderingException.java index 6a1c2b615d..085257239c 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RenderingException.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RenderingException.java @@ -25,17 +25,17 @@ * A generic Roller rendering exception. */ public class RenderingException extends PlanetException { - + public RenderingException(String s) { super(s); } - + public RenderingException(String s, Throwable t) { super(s, t); } - + public RenderingException(Throwable t) { super(t); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RequestMapper.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RequestMapper.java index db9c93cf52..150892e677 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RequestMapper.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/RequestMapper.java @@ -11,16 +11,16 @@ * Interface representing an object that maps requests. */ public interface RequestMapper { - + /** * Handle an incoming request. * * RequestMappers are not required to handle all requests and are instead * encouraged to inspect the request and only take action when it - * wants to. If action is taken then the RequestMapper should return a + * wants to. If action is taken then the RequestMapper should return a * boolean "true" value indicating that no further action is required. */ public boolean handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException; - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/filters/RequestMappingFilter.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/filters/RequestMappingFilter.java index 30676542ba..b2829324c3 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/filters/RequestMappingFilter.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/filters/RequestMappingFilter.java @@ -43,22 +43,22 @@ * potentially be re-routed to different places within the application. */ public class RequestMappingFilter implements Filter { - + private static Log log = LogFactory.getLog(RequestMappingFilter.class); - + // list of RequestMappers that want to inspect the request private final List requestMappers = new ArrayList(); - - + + public void init(FilterConfig filterConfig) { - + // lookup set of request mappers we are going to use String rollerMappers = PlanetConfig.getProperty("rendering.rollerRequestMappers"); String userMappers = PlanetConfig.getProperty("rendering.userRequestMappers"); - + // instantiate user defined request mapper classes if(userMappers != null && userMappers.trim().length() > 0) { - + RequestMapper requestMapper = null; String[] uMappers = userMappers.split(","); for(int i=0; i < uMappers.length; i++) { @@ -74,10 +74,10 @@ public void init(FilterConfig filterConfig) { } } } - + // instantiate roller standard request mapper classes if(rollerMappers != null && rollerMappers.trim().length() > 0) { - + RequestMapper requestMapper = null; String[] rMappers = rollerMappers.split(","); for(int i=0; i < rMappers.length; i++) { @@ -93,37 +93,37 @@ public void init(FilterConfig filterConfig) { } } } - + if(requestMappers.size() < 1) { // hmm ... failed to load any request mappers? log.warn("Failed to load any request mappers. "+ "Weblog urls probably won't function as you expect."); } - + log.info("Request mapping filter initialized, "+requestMappers.size()+ " mappers configured."); } - - + + /** * Inspect incoming urls and see if they should be routed. */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.debug("entering"); - + // give each mapper a chance to handle the request RequestMapper mapper = null; Iterator mappersIT = this.requestMappers.iterator(); while(mappersIT.hasNext()) { mapper = (RequestMapper) mappersIT.next(); - + log.debug("trying mapper "+mapper.getClass().getName()); - + boolean wasHandled = mapper.handleRequest(request, response); if(wasHandled) { // if mapper has handled the request then we are done @@ -132,16 +132,16 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) return; } } - + log.debug("request not mapped"); - + // nobody handled the request, so let it continue as usual chain.doFilter(request, response); - + log.debug("exiting"); } - - + + public void destroy() {} - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/FeedModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/FeedModel.java index 82b36a3c38..3abc8f7abc 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/FeedModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/FeedModel.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.planet.ui.rendering.model; +package org.apache.roller.planet.ui.rendering.model; import java.util.Map; import org.apache.commons.logging.Log; @@ -35,43 +35,43 @@ * Model which provides information needed to render a planet feed. */ public class FeedModel extends PlanetGroupModel { - + private static Log log = LogFactory.getLog(FeedModel.class); - + private PlanetGroupFeedRequest feedRequest = null; - - - /** + + + /** * Creates an un-initialized new instance, Roller calls init() to complete - * construction. + * construction. */ public FeedModel() { super(); } - - - /** + + + /** * Template context name to be used for model. */ public String getModelName() { return "model"; } - - - /** - * Init page model based on request. + + + /** + * Init page model based on request. */ public void init(Map initData) throws PlanetException { - + // parent gets to go first super.init(initData); - + // we expect the init data to contain a weblogRequest object PlanetRequest planetRequest = (PlanetRequest) initData.get("planetRequest"); if(planetRequest == null) { throw new PlanetException("expected planetRequest from init data"); } - + // PageModel only works on page requests, so cast planetRequest // into a PlanetRequest and if it fails then throw exception if(planetRequest instanceof PlanetGroupFeedRequest) { @@ -81,12 +81,12 @@ public void init(Map initData) throws PlanetException { " PageModel only supports page requests."); } } - - + + public Pager getPager() { - + String pagerUrl = URLUtilities.getPlanetGroupURL(getPlanet().getHandle(), feedRequest.getGroupHandle()); - + return new PlanetEntriesPager( null, feedRequest.getGroup(), @@ -95,5 +95,5 @@ public Pager getPager() { 0, 30); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/Model.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/Model.java index 170baae2f4..8b62b86a8e 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/Model.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/Model.java @@ -26,16 +26,16 @@ * Represents a set of functionality to be used at rendering. */ public interface Model { - + /** * Name to be used when referring to this model. */ public String getModelName(); - - + + /** * Initialize. */ public void init(Map params) throws PlanetException; - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/ModelLoader.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/ModelLoader.java index 649cca0bbc..e88a85782c 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/ModelLoader.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/ModelLoader.java @@ -29,20 +29,20 @@ * Helps with model loading process. */ public class ModelLoader { - + private static Log log = LogFactory.getLog(ModelLoader.class); - - + + /** * Convenience method to load a comma-separated list of page models. * * Optionally fails if any exceptions are thrown when initializing * the Model instances. */ - public static void loadModels(String modelsString, Map model, - Map initData, boolean fail) + public static void loadModels(String modelsString, Map model, + Map initData, boolean fail) throws PlanetException { - + String[] models = Utilities.stringToStringArray(modelsString, ","); for(int i=0; i < models.length; i++) { try { @@ -77,5 +77,5 @@ public static void loadModels(String modelsString, Map model, } } } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PageModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PageModel.java index 33e67aa4cd..c8bd0d1286 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PageModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PageModel.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.planet.ui.rendering.model; +package org.apache.roller.planet.ui.rendering.model; import java.util.Map; import org.apache.commons.logging.Log; @@ -35,42 +35,42 @@ * Model which provides information needed to render a planet page. */ public class PageModel extends PlanetGroupModel { - + private static Log log = LogFactory.getLog(PageModel.class); - + private PlanetGroupPageRequest pageRequest = null; - - - /** + + + /** * Creates an un-initialized new instance. */ public PageModel() { super(); } - - - /** + + + /** * Template context name to be used for model. */ public String getModelName() { return "model"; } - - - /** - * Init page model based on request. + + + /** + * Init page model based on request. */ public void init(Map initData) throws PlanetException { - + // parent gets to go first super.init(initData); - + // we expect the init data to contain a weblogRequest object PlanetRequest planetRequest = (PlanetRequest) initData.get("planetRequest"); if(planetRequest == null) { throw new PlanetException("expected planetRequest from init data"); } - + // PageModel only works on page requests, so cast planetRequest // into a PlanetRequest and if it fails then throw exception if(planetRequest instanceof PlanetGroupPageRequest) { @@ -80,12 +80,12 @@ public void init(Map initData) throws PlanetException { " PageModel only supports page requests."); } } - - + + public Pager getPager() { - + String pagerUrl = URLUtilities.getPlanetGroupURL(getPlanet().getHandle(), pageRequest.getGroupHandle()); - + return new PlanetEntriesPager( null, pageRequest.getGroup(), @@ -94,5 +94,5 @@ public Pager getPager() { pageRequest.getPageNum(), getGroup().getMaxPageEntries()); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetGroupModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetGroupModel.java index d4026f805d..815091bd70 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetGroupModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetGroupModel.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.planet.ui.rendering.model; +package org.apache.roller.planet.ui.rendering.model; import java.util.Map; import org.apache.commons.logging.Log; @@ -32,40 +32,40 @@ * Model which provides information common to a planet group request */ public class PlanetGroupModel implements Model { - + private static Log log = LogFactory.getLog(PlanetGroupModel.class); - + private PlanetGroupRequest planetGroupRequest = null; private Planet planet = null; private PlanetGroup group = null; - - - /** + + + /** * Creates an un-initialized new instance, Roller calls init() to complete - * construction. + * construction. */ public PlanetGroupModel() {} - - - /** + + + /** * Template context name to be used for model. */ public String getModelName() { return "model"; } - - - /** - * Init page model based on request. + + + /** + * Init page model based on request. */ public void init(Map initData) throws PlanetException { - + // we expect the init data to contain a planetRequest object PlanetRequest planetRequest = (PlanetRequest) initData.get("planetRequest"); if(planetRequest == null) { throw new PlanetException("expected planetRequest from init data"); } - + // only works on planet group requests, so cast planetRequest // into a PlanetGroupRequest and if it fails then throw exception if(planetRequest instanceof PlanetGroupRequest) { @@ -74,28 +74,28 @@ public void init(Map initData) throws PlanetException { throw new PlanetException("planetRequest is not a PlanetGroupRequest."+ " PlanetGroupModel only supports planet group requests."); } - + // extract planet object planet = planetGroupRequest.getPlanet(); - + // extract group object group = planetGroupRequest.getGroup(); } - - + + /** * Get planet being displayed. */ public Planet getPlanet() { return planet; } - - + + /** * Get group being displayed. */ public PlanetGroup getGroup() { return group; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetURLModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetURLModel.java index 1adc428398..02f009641b 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetURLModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/PlanetURLModel.java @@ -43,75 +43,75 @@ * $url.getCategory("foo") */ public class PlanetURLModel implements Model { - + private static Log log = LogFactory.getLog(PlanetURLModel.class); - + private URLStrategy urlStrategy = null; private Planet planet = null; - - + + public PlanetURLModel() {} - + public String getModelName() { return "url"; } - + public void init(Map initData) throws PlanetException { - + // grab a reference to the url strategy this.urlStrategy = PlanetFactory.getPlanet().getURLStrategy(); - + // need a weblog request so that we can know the weblog and locale PlanetRequest planetRequest = (PlanetRequest) initData.get("planetRequest"); if(planetRequest == null) { throw new PlanetException("Expected 'planetRequest' init param!"); } - + this.planet = planetRequest.getPlanet(); } - - + + public String getSite() { return PlanetRuntimeConfig.getProperty("site.absoluteurl"); } - - + + public String getHome() { return urlStrategy.getPlanetURL(planet.getHandle()); } - - + + public String group(String groupHandle) { return urlStrategy.getPlanetGroupURL(planet.getHandle(), groupHandle, -1); } - - + + public String group(String groupHandle, int pageNum) { return urlStrategy.getPlanetGroupURL(planet.getHandle(), groupHandle, pageNum); } - - + + public FeedURLS getFeed() { return new FeedURLS(); } - - + + public String opml(String groupHandle) { return urlStrategy.getPlanetGroupOpmlURL(planet.getHandle(), groupHandle); } - - + + /////// Inner Classes /////// - + public class FeedURLS { - + public String rss(String groupHandle) { return urlStrategy.getPlanetGroupFeedURL(planet.getHandle(), groupHandle, "rss"); } - + public String atom(String groupHandle) { return urlStrategy.getPlanetGroupFeedURL(planet.getHandle(), groupHandle, "atom"); } } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteModel.java index a6bb65f425..51e095b51b 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteModel.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.planet.ui.rendering.model; +package org.apache.roller.planet.ui.rendering.model; import java.util.List; import java.util.Map; @@ -32,42 +32,42 @@ * Model which provides information on an application wide scope. */ public class SiteModel implements Model { - + private static Log log = LogFactory.getLog(SiteModel.class); - - - /** + + + /** * Creates an un-initialized new instance. */ public SiteModel() {} - - - /** + + + /** * Template context name to be used for model. */ public String getModelName() { return "site"; } - - - /** - * Init page model based on request. + + + /** + * Init page model based on request. */ public void init(Map initData) throws PlanetException { // no-op } - - + + public String getTitle() { return PlanetRuntimeConfig.getProperty("site.name"); } - - + + public String getDescription() { return PlanetRuntimeConfig.getProperty("site.description"); } - - + + /** * Get the list of all planets. */ @@ -78,8 +78,8 @@ public List getPlanets() { } catch(Exception e) { log.error("Error getting planets list", e); } - + return null; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteURLModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteURLModel.java index c3cdbb7d46..a29eb01688 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteURLModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/SiteURLModel.java @@ -43,32 +43,32 @@ * $url.getCategory("foo") */ public class SiteURLModel implements Model { - + private static Log log = LogFactory.getLog(SiteURLModel.class); - + private URLStrategy urlStrategy = null; - - + + public SiteURLModel() {} - + public String getModelName() { return "url"; } - + public void init(Map initData) throws PlanetException { - + // grab a reference to the url strategy this.urlStrategy = PlanetFactory.getPlanet().getURLStrategy(); } - - + + public String getSite() { return PlanetRuntimeConfig.getProperty("site.absoluteurl"); } - - + + public String planet(String planetHandle) { return this.urlStrategy.getPlanetURL(planetHandle); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/UtilitiesModel.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/UtilitiesModel.java index 0787f82180..996da90abc 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/UtilitiesModel.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/model/UtilitiesModel.java @@ -42,66 +42,66 @@ * Model which provides access to a set of general utilities. */ public class UtilitiesModel implements Model { - - private static Log log = LogFactory.getLog(UtilitiesModel.class); - + + private static Log log = LogFactory.getLog(UtilitiesModel.class); + private static Pattern mLinkPattern = - Pattern.compile("", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_B_TAG_PATTERN = + Pattern.compile("", Pattern.CASE_INSENSITIVE); + private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("<b>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_B_TAG_PATTERN = + private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("</b>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_I_TAG_PATTERN = + private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("<i>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_I_TAG_PATTERN = + private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("</i>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern BR_TAG_PATTERN = + private static final Pattern BR_TAG_PATTERN = Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_P_TAG_PATTERN = + private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("<p>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_P_TAG_PATTERN = + private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("</p>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_PRE_TAG_PATTERN = + private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_PRE_TAG_PATTERN = + private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_UL_TAG_PATTERN = + private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_UL_TAG_PATTERN = + private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_OL_TAG_PATTERN = + private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_OL_TAG_PATTERN = + private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_LI_TAG_PATTERN = + private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("<li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_LI_TAG_PATTERN = + private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("</li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_A_TAG_PATTERN = + private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("</a>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_A_TAG_PATTERN = + private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE); - private static final Pattern QUOTE_PATTERN = + private static final Pattern QUOTE_PATTERN = Pattern.compile(""", Pattern.CASE_INSENSITIVE); - + private TimeZone tz = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "utils"; } - - + + /** Init page model based on request */ public void init(Map initData) throws PlanetException { } - - + + //-------------------------------------------------------------- Date utils /** * Return date for current time. @@ -109,54 +109,54 @@ public void init(Map initData) throws PlanetException { public static Date getNow() { return new Date(); } - + /** * Format date using SimpleDateFormat format string. */ public String formatDate(Date d, String fmt) { if(d == null || fmt == null) return fmt; - + SimpleDateFormat format = new SimpleDateFormat(fmt); if (tz != null) { format.setTimeZone(tz); } return format.format(d); } - + /** * Format date using SimpleDateFormat format string. */ public static String formatDate(Date d, String fmt, TimeZone tzOverride) { if(d == null || fmt == null) return fmt; - + SimpleDateFormat format = new SimpleDateFormat(fmt); format.setTimeZone(tzOverride); return format.format(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Date(Date d) { return DateUtil.formatIso8601(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Day(Date d) { return DateUtil.formatIso8601Day(d); } - + /** * Return a date in RFC-822 format. */ public static String formatRfc822Date(Date date) { return DateUtil.formatRfc822(date); } - + /** * Return a date in RFC-822 format. */ @@ -165,66 +165,66 @@ public static String format8charsDate(Date date) { } //------------------------------------------------------------ String utils - + public static boolean isEmpty(String str) { if (str == null) return true; return "".equals(str.trim()); } - + public static boolean isNotEmpty(String str) { return !isEmpty(str); } - + public static String[] split(String str1, String str2) { return StringUtils.split(str1, str2); } - - + + public static boolean equals(String str1, String str2) { return StringUtils.equals(str1, str2); } - + public static boolean isAlphanumeric(String str) { return StringUtils.isAlphanumeric(str); } - + public static String[] stripAll(String[] strs) { return StringUtils.stripAll(strs); } - + public static String left(String str, int length) { return StringUtils.left(str, length); } - + public static String escapeHTML(String str) { return StringEscapeUtils.escapeHtml(str); } - + public static String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + public static String escapeXML(String str) { return StringEscapeUtils.escapeXml(str); } - + public static String unescapeXML(String str) { return StringEscapeUtils.unescapeXml(str); } - + public static String replace(String src, String target, String rWith) { return StringUtils.replace(src, target, rWith); } - + public static String replace(String src, String target, String rWith, int maxCount) { return StringUtils.replace(src, target, rWith, maxCount); } - + private static String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". Replace @@ -233,7 +233,7 @@ private static String replace(String string, Pattern pattern, String replacement public static String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -242,7 +242,7 @@ public static String removeHTML(String str) { public static String removeHTML(String str, boolean addSpace) { return Utilities.removeHTML(str, addSpace); } - + /** * Autoformat. */ @@ -257,21 +257,21 @@ public static String truncate( String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); - + // quickly adjust the upper if it is set lower than 'lower' if (upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -281,37 +281,37 @@ public static String truncate( str2 = str2.substring(0, upper); loc = upper; } - + // the string was truncated, so we append the appendToEnd String str2 = str2 + appendToEnd; } - + return str2; } - + public static String truncateNicely(String str, int lower, int upper, String appendToEnd) { return Utilities.truncateNicely(str, lower, upper, appendToEnd); } - + public static String truncateText(String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -325,18 +325,18 @@ public static String truncateText(String str, int lower, int upper, String appen str = str2 + appendToEnd; } return str; - } - + } + public static String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public static String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } - + /** * URL encoding. * @param s a string to be URL-encoded @@ -353,7 +353,7 @@ public static final String encode(String s) { return s; } } - + /** * URL decoding. * @param s a URL-encoded string to be URL-decoded @@ -370,7 +370,7 @@ public static final String decode(String s) { return s; } } - + /** * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML. */ @@ -397,7 +397,7 @@ public static String addNofollow(String html) { buf.append(html); return buf.toString(); } - + /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes <b>, <i>, <p>, <br>, @@ -407,11 +407,11 @@ public static String addNofollow(String html) { * @return the transformed String */ public static String transformToHTMLSubset(String s) { - + if (s == null) { return null; } - + s = replace(s, OPENING_B_TAG_PATTERN, ""); s = replace(s, CLOSING_B_TAG_PATTERN, ""); s = replace(s, OPENING_I_TAG_PATTERN, ""); @@ -430,7 +430,7 @@ public static String transformToHTMLSubset(String s) { s = replace(s, OPENING_LI_TAG_PATTERN, "

  • "); s = replace(s, CLOSING_LI_TAG_PATTERN, "
  • "); s = replace(s, QUOTE_PATTERN, "\""); - + // HTTP links s = replace(s, CLOSING_A_TAG_PATTERN, ""); Matcher m = OPENING_A_TAG_PATTERN.matcher(s); @@ -442,43 +442,43 @@ public static String transformToHTMLSubset(String s) { s = s.substring(0, start) + link + s.substring(end, s.length()); m = OPENING_A_TAG_PATTERN.matcher(s); } - + // escaped angle brackets s = s.replaceAll("&lt;", "<"); s = s.replaceAll("&gt;", ">"); s = s.replaceAll("&#", "&#"); - + return s; } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public static String toBase64(byte[] aValue) { - + final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - + int byte1; int byte2; int byte3; int iByteLen = aValue.length; StringBuffer tt = new StringBuffer(); - + for (int i = 0; i < iByteLen; i += 3) { boolean bByte2 = (i + 1) < iByteLen; boolean bByte3 = (i + 2) < iByteLen; byte1 = aValue[i] & 0xFF; byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0; byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0; - + tt.append(m_strBase64Chars.charAt(byte1 / 4)); tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16))); tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '=')); tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '=')); } - + return tt.toString(); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/AbstractPager.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/AbstractPager.java index 78e1d619a2..4e6a0be79d 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/AbstractPager.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/AbstractPager.java @@ -27,30 +27,30 @@ * Abstract base for simple pagers. */ public abstract class AbstractPager implements Pager { - + private String url = null; private int page = 0; - - + + public AbstractPager(String baseUrl, int pageNum) { - + this.url = baseUrl; if(pageNum > 0) { this.page = pageNum; } } - - + + public String getHomeLink() { return url; } - - + + public String getHomeName() { return "Home"; } - - + + public String getNextLink() { if(hasMoreItems()) { int nextPage = page + 1; @@ -60,16 +60,16 @@ public String getNextLink() { } return null; } - - + + public String getNextName() { if(hasMoreItems()) { return "Next"; } return null; } - - + + public String getPrevLink() { if (page > 1) { int prevPage = page - 1; @@ -81,27 +81,27 @@ public String getPrevLink() { } return null; } - - + + public String getPrevName() { if (page > 0) { return "Previous"; } return null; } - - + + public boolean hasMoreItems() { return false; } - - + + protected String createURL(String url, Map params) { - + return url + URLUtilities.getQueryString(params); } - + public String getUrl() { return url; } @@ -117,5 +117,5 @@ public int getPage() { public void setPage(int page) { this.page = page; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/Pager.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/Pager.java index fc069ed030..0efd6041e5 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/Pager.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/Pager.java @@ -53,10 +53,10 @@ public interface Pager { * Link value for prev page in current collection view */ public String getPrevName(); - + /** * Get current list of items available from the pager. */ public List getItems(); - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/PlanetEntriesPager.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/PlanetEntriesPager.java index e1df2b9daf..8db92f40fe 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/PlanetEntriesPager.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/pagers/PlanetEntriesPager.java @@ -37,21 +37,21 @@ * Paging through a collection of planet entries. */ public class PlanetEntriesPager extends AbstractPager { - + private static Log log = LogFactory.getLog(PlanetEntriesPager.class); - + private String feedURL = null; private PlanetGroup group = null; private int sinceDays = -1; private int length = 0; - + // the collection for the pager private List entries = null; - + // are there more items? private boolean more = false; - - + + public PlanetEntriesPager( String feedURL, PlanetGroup group, @@ -59,25 +59,25 @@ public PlanetEntriesPager( int sinceDays, int page, int length) { - + super(baseUrl, page); - + this.feedURL = feedURL; this.group = group; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public List getItems() { - + if (entries == null) { // calculate offset int offset = getPage() * length; - + Date startDate = null; if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); @@ -85,11 +85,11 @@ public List getItems() { cal.add(Calendar.DATE, -1 * sinceDays); startDate = cal.getTime(); } - + List results = new ArrayList(); try { PlanetManager planetManager = PlanetFactory.getPlanet().getPlanetManager(); - + List rawEntries = null; if (feedURL != null) { Subscription sub = planetManager.getSubscription(feedURL); @@ -102,33 +102,33 @@ public List getItems() { //rawEntries = planetManager.getEntries(startDate, null, offset, length+1); rawEntries = Collections.EMPTY_LIST; } - + // check if there are more results for paging if(rawEntries.size() > length) { more = true; rawEntries.remove(rawEntries.size() - 1); } - + // wrap 'em for (Iterator it = rawEntries.iterator(); it.hasNext();) { SubscriptionEntry entry = (SubscriptionEntry) it.next(); // TODO needs pojo wrapping from planet results.add(entry); } - + } catch (Exception e) { log.error("ERROR: get aggregation", e); } - + entries = results; } - + return entries; } - - + + public boolean hasMoreItems() { return more; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/FeedServlet.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/FeedServlet.java index 9ce2c4d2fe..590cc499f6 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/FeedServlet.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/FeedServlet.java @@ -74,13 +74,13 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) try { // parse the incoming request and extract the relevant data feedRequest = new PlanetGroupFeedRequest(request); - + planet = feedRequest.getPlanet(); if(planet == null) { throw new PlanetException("unable to lookup planet: "+ feedRequest.getPlanetHandle()); } - + group = feedRequest.getGroup(); if(group == null) { throw new PlanetException("unable to lookup group: "+ @@ -99,8 +99,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) String userAgent = request.getHeader("User-Agent"); if (accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null && userAgent.startsWith("Mozilla")) { - // client is a browser and feed style is enabled so we want - // browsers to load the page rather than popping up the download + // client is a browser and feed style is enabled so we want + // browsers to load the page rather than popping up the download // dialog, so we provide a content-type that browsers will display response.setContentType("text/xml"); } else if("rss".equals(feedRequest.getFormat())) { @@ -108,15 +108,15 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } else if("atom".equals(feedRequest.getFormat())) { response.setContentType("application/atom+xml; charset=utf-8"); } - - + + // looks like we need to render content HashMap model = new HashMap(); try { // populate the rendering model Map initData = new HashMap(); initData.put("planetRequest", feedRequest); - + // Load models for feeds String feedModels = PlanetConfig.getProperty("rendering.feedModels"); ModelLoader.loadModels(feedModels, model, initData, true); @@ -134,14 +134,14 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) Renderer renderer = null; try { log.debug("Looking up renderer"); - + String templateFile = null; if("rss".equals(feedRequest.getFormat())) { templateFile = "group-rss.vm"; } else if("atom".equals(feedRequest.getFormat())) { templateFile = "group-atom.vm"; } - + Template template = new StaticTemplate(templateFile, null, "velocity"); renderer = RendererManager.getRenderer(template); } catch(Exception e) { diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/HomepageServlet.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/HomepageServlet.java index 20bc69d18c..3dd1b26c6d 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/HomepageServlet.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/HomepageServlet.java @@ -69,14 +69,14 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set content type response.setContentType("text/html; charset=utf-8"); - - + + // initialize model HashMap model = new HashMap(); try { // populate the rendering model Map initData = new HashMap(); - + // Load models for pages String models = PlanetConfig.getProperty("rendering.homepageModels"); ModelLoader.loadModels(models, model, initData, true); @@ -94,13 +94,13 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) Renderer renderer = null; try { log.debug("Looking up renderer"); - + // what template are we going to render? Template template = new StaticTemplate("home.vm", null, "velocity"); - + // get the Renderer renderer = RendererManager.getRenderer(template); - + } catch(Exception e) { // nobody wants to render my content :( @@ -108,8 +108,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // render content try { log.debug("Doing rendering"); diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/OpmlServlet.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/OpmlServlet.java index 9b44587c92..8a52edc3cf 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/OpmlServlet.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/OpmlServlet.java @@ -66,7 +66,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); - + Planet planet = null; PlanetGroup group = null; @@ -80,7 +80,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) throw new PlanetException("unable to lookup planet: "+ opmlRequest.getPlanetHandle()); } - + group = opmlRequest.getGroup(); if(group == null) { throw new PlanetException("unable to lookup group: "+ @@ -96,15 +96,15 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set content type response.setContentType("application/xml; charset=utf-8"); - - + + // looks like we need to render content HashMap model = new HashMap(); try { // populate the rendering model Map initData = new HashMap(); initData.put("planetRequest", opmlRequest); - + // Load models for feeds String opmlModels = PlanetConfig.getProperty("rendering.opmlModels"); ModelLoader.loadModels(opmlModels, model, initData, true); diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/PageServlet.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/PageServlet.java index 429fa74d67..037ade91f1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/PageServlet.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/servlets/PageServlet.java @@ -66,7 +66,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); - + Planet planet = null; PlanetGroup group = null; @@ -80,7 +80,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) throw new PlanetException("unable to lookup planet: "+ pageRequest.getPlanetHandle()); } - + group = pageRequest.getGroup(); } catch(Exception e) { @@ -92,15 +92,15 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set content type response.setContentType("text/html; charset=utf-8"); - - + + // looks like we need to render content HashMap model = new HashMap(); try { // populate the rendering model Map initData = new HashMap(); initData.put("planetRequest", pageRequest); - + // Load models for pages String pageModels = PlanetConfig.getProperty("rendering.pageModels"); ModelLoader.loadModels(pageModels, model, initData, true); @@ -118,7 +118,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) Renderer renderer = null; try { log.debug("Looking up renderer"); - + // what template are we going to render? Template template = null; if(group == null) { @@ -128,10 +128,10 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // group homepage template = new StaticTemplate("group.vm", null, "velocity"); } - + // get the Renderer renderer = RendererManager.getRenderer(template); - + } catch(Exception e) { // nobody wants to render my content :( @@ -139,8 +139,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // render content try { log.debug("Doing rendering"); diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/InvalidRequestException.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/InvalidRequestException.java index 56ac4bd0fe..46fea39943 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/InvalidRequestException.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/InvalidRequestException.java @@ -26,13 +26,13 @@ * its subclasses when the request being parsed is invalid in any way. */ public class InvalidRequestException extends PlanetException { - + public InvalidRequestException(String msg) { super(msg); } - + public InvalidRequestException(String msg, Exception e) { super(msg, e); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/ParsedRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/ParsedRequest.java index bbccd336e0..2104223a18 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/ParsedRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/ParsedRequest.java @@ -34,15 +34,15 @@ * needed. */ public abstract class ParsedRequest { - + HttpServletRequest request = null; - + private String authenticUser = null; - - + + ParsedRequest() {} - - + + /** * Parse the given http request and extract any information we can. * @@ -50,31 +50,31 @@ public abstract class ParsedRequest { * relevant to all requests to Roller. */ public ParsedRequest(HttpServletRequest request) throws InvalidRequestException { - + // keep a reference to the original request this.request = request; - + // login status java.security.Principal prince = request.getUserPrincipal(); if(prince != null) { this.authenticUser = prince.getName(); } - + } - - + + public String getAuthenticUser() { return this.authenticUser; } - - + + public void setAuthenticUser(String authenticUser) { this.authenticUser = authenticUser; } - - + + public boolean isLoggedIn() { return (this.authenticUser != null); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupFeedRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupFeedRequest.java index 1e5002e054..b428c106b1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupFeedRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupFeedRequest.java @@ -27,54 +27,54 @@ /** * Represents a request for a Roller planet group feed. - * + * * /planet-ui/rendering/feeds/* * * We use this class as a helper to parse an incoming url and sort out the * information embedded in the url for later use. */ public class PlanetGroupFeedRequest extends PlanetGroupRequest { - + private static Log log = LogFactory.getLog(PlanetGroupFeedRequest.class); - + // lightweight attributes private String format = null; - - + + public PlanetGroupFeedRequest() {} - - + + /** * Construct the WeblogFeedRequest by parsing the incoming url */ - public PlanetGroupFeedRequest(HttpServletRequest request) + public PlanetGroupFeedRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - - - /* + + + /* * parse the path info. must look like this ... * * */ if(pathInfo != null && pathInfo.trim().length() > 1) { - + this.format = pathInfo; - + } else { throw new InvalidRequestException("not a valid planet group feed, "+ request.getRequestURL()); } - + if(log.isDebugEnabled()) { log.debug("format = "+this.format); } @@ -87,5 +87,5 @@ public String getFormat() { public void setFormat(String format) { this.format = format; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupOpmlRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupOpmlRequest.java index 53f655d7e8..f906e8cd0c 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupOpmlRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupOpmlRequest.java @@ -27,42 +27,42 @@ /** * Represents a request for a Roller planet group page. - * + * * /planet-ui/rendering/opml/* * * We use this class as a helper to parse an incoming url and sort out the * information embedded in the url for later use. */ public class PlanetGroupOpmlRequest extends PlanetGroupRequest { - + private static Log log = LogFactory.getLog(PlanetGroupOpmlRequest.class); - + // lightweight attributes - - + + public PlanetGroupOpmlRequest() {} - - + + /** * Construct the WeblogFeedRequest by parsing the incoming url */ - public PlanetGroupOpmlRequest(HttpServletRequest request) + public PlanetGroupOpmlRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - + if(pathInfo != null) { throw new InvalidRequestException("not a valid planet opml page, "+ request.getRequestURL()); } } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupPageRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupPageRequest.java index 026adb0aa7..cce1f5837b 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupPageRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupPageRequest.java @@ -25,44 +25,44 @@ /** * Represents a request for a Roller planet group page. - * + * * /planet-ui/rendering/pages/* * * We use this class as a helper to parse an incoming url and sort out the * information embedded in the url for later use. */ public class PlanetGroupPageRequest extends PlanetGroupRequest { - + private static Log log = LogFactory.getLog(PlanetGroupPageRequest.class); - + // lightweight attributes private int pageNum = 0; - - + + public PlanetGroupPageRequest() {} - - + + /** * Construct the WeblogFeedRequest by parsing the incoming url */ - public PlanetGroupPageRequest(HttpServletRequest request) + public PlanetGroupPageRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines planet handle super(request); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - + if(pathInfo != null) { throw new InvalidRequestException("not a valid planet group page, "+ request.getRequestURL()); } - + // parse request parameters, right now we only allow for a "page" param if(request.getParameter("page") != null) { String pageInt = request.getParameter("page"); @@ -81,5 +81,5 @@ public int getPageNum() { public void setPageNum(int pageNum) { this.pageNum = pageNum; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupRequest.java index f60ff4c237..38c660eb75 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetGroupRequest.java @@ -29,58 +29,58 @@ /** * Represents a request to a planet group. - * + * * //group/[/extra/path/info] * */ public class PlanetGroupRequest extends PlanetRequest { - + private static Log log = LogFactory.getLog(PlanetGroupRequest.class); - + // lightweight attributes private String groupHandle = null; - + // heavyweight attributes private PlanetGroup group = null; - - + + public PlanetGroupRequest() {} - - - public PlanetGroupRequest(HttpServletRequest request) + + + public PlanetGroupRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first super(request); - + String myPathInfo = this.getPathInfo(); - + log.debug("parsing path "+myPathInfo); - - /* + + /* * parse the path info. must look like this ... * * [/extra/info] */ if(myPathInfo != null && myPathInfo.trim().length() > 1) { - + String[] urlPath = myPathInfo.split("/", 2); this.groupHandle = urlPath[0]; this.pathInfo = null; - + if(urlPath.length == 2) { this.pathInfo = urlPath[1]; } - + } - + if(log.isDebugEnabled()) { log.debug("groupHandle = "+this.groupHandle); log.debug("pathInfo = "+this.pathInfo); } } - - + + public String getGroupHandle() { return groupHandle; } @@ -90,7 +90,7 @@ public void setGroupHandle(String groupHandle) { } public PlanetGroup getGroup() { - + if(group == null && groupHandle != null) { try { PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); @@ -99,12 +99,12 @@ public PlanetGroup getGroup() { log.error("Error looking up group "+groupHandle, ex); } } - + return group; } public void setGroup(PlanetGroup group) { this.group = group; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetRequest.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetRequest.java index 58341fdb7f..7da0242d40 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetRequest.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/util/PlanetRequest.java @@ -29,14 +29,14 @@ /** * Represents a request to a weblog. - * + * * This is a fairly generic parsed request which is only trying to figure out - * the elements of a weblog request which apply to all weblogs. We try to - * determine the weblogHandle, if a locale was specified, and then what extra + * the elements of a weblog request which apply to all weblogs. We try to + * determine the weblogHandle, if a locale was specified, and then what extra * path info remains. The basic format is like this ... - * + * * /[/extra/path/info] - * + * * All weblog urls require a weblogHandle, so we ensure that part of the url is * properly specified. locale is always optional, so we do our best to see * if a locale is specified. and path info is always optional. @@ -47,41 +47,41 @@ * this class and simply pick up where it left off in the parsing process. */ public class PlanetRequest extends ParsedRequest { - + private static Log log = LogFactory.getLog(PlanetRequest.class); - + // lightweight attributes private String planetHandle = null; protected String pathInfo = null; - + // heavyweight attributes private Planet planet = null; - - + + public PlanetRequest() {} - - - public PlanetRequest(HttpServletRequest request) + + + public PlanetRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first super(request); - + String path = request.getPathInfo(); - + log.debug("parsing path "+path); - + // first, cleanup extra slashes and extract the planet handle if(path != null && path.trim().length() > 1) { - + // strip off the leading slash path = path.substring(1); - + // strip off trailing slash if needed if(path.endsWith("/")) { path = path.substring(0, path.length() - 1); } - + String[] pathElements = path.split("/", 2); if(pathElements[0].trim().length() > 0) { this.planetHandle = pathElements[0]; @@ -90,7 +90,7 @@ public PlanetRequest(HttpServletRequest request) throw new InvalidRequestException("not a planet request, "+ request.getRequestURL()); } - + // if there is more left of the path info then hold onto it if(pathElements.length == 2) { pathInfo = pathElements[1]; @@ -98,14 +98,14 @@ public PlanetRequest(HttpServletRequest request) pathInfo = null; } } - + if(log.isDebugEnabled()) { log.debug("planetHandle = "+this.planetHandle); log.debug("pathInfo = "+this.pathInfo); } } - - + + public String getPlanetHandle() { return planetHandle; } @@ -115,7 +115,7 @@ public void setPlanetHandle(String planetHandle) { } public Planet getPlanet() { - + if(planet == null && planetHandle != null) { try { PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); @@ -124,14 +124,14 @@ public Planet getPlanet() { log.error("Error looking up planet "+planetHandle, ex); } } - + return planet; } public void setPlanet(Planet planet) { this.planet = planet; } - + public String getPathInfo() { return pathInfo; } @@ -139,5 +139,5 @@ public String getPathInfo() { public void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/PlanetVelocity.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/PlanetVelocity.java index d12cf2d6ef..2c22c9d424 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/PlanetVelocity.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/PlanetVelocity.java @@ -36,40 +36,40 @@ * access to the instance via the Singleton getInstance() method. */ public class PlanetVelocity { - + public static final String VELOCITY_CONFIG = "/WEB-INF/velocity.properties"; - + private static Log log = LogFactory.getLog(PlanetVelocity.class); - + private static VelocityEngine velocityEngine = null; - - + + static { log.info("Initializing Velocity Rendering Engine"); - + // initialize the Velocity engine Properties velocityProps = new Properties(); - + try { InputStream instream = PlanetContext.getServletContext().getResourceAsStream(VELOCITY_CONFIG); - + velocityProps.load(instream); - + log.debug("Velocity engine props = "+velocityProps); - + // construct the VelocityEngine velocityEngine = new VelocityEngine(); - + // init velocity with our properties velocityEngine.init(velocityProps); - + } catch (Exception e) { throw new RuntimeException(e); } } - - + + /** * Access to the VelocityEngine. * @@ -79,8 +79,8 @@ public class PlanetVelocity { public static VelocityEngine getEngine() { return velocityEngine; } - - + + /** * Convenience static method for looking up a template. */ @@ -88,8 +88,8 @@ public static Template getTemplate(String name) throws ResourceNotFoundException, ParseErrorException, Exception { return velocityEngine.getTemplate(name); } - - + + /** * Convenience static method for looking up a template. */ @@ -97,5 +97,5 @@ public static Template getTemplate(String name, String encoding) throws ResourceNotFoundException, ParseErrorException, Exception { return velocityEngine.getTemplate(name, encoding); } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/TemplateResourceLoader.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/TemplateResourceLoader.java index fcffac2a6c..fff6ff2ecf 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/TemplateResourceLoader.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/TemplateResourceLoader.java @@ -33,65 +33,65 @@ * Loads Velocity resources from the planet "templates.dir" folder. */ public class TemplateResourceLoader extends ResourceLoader { - + private static Log log = LogFactory.getLog(TemplateResourceLoader.class); - + private String templateDir = null; - - + + /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#init(org.apache.commons.collections.ExtendedProperties) */ public void init(ExtendedProperties config) { - + log.debug("TemplateResourceLoader : initialization starting."); - + if (templateDir == null) { templateDir = PlanetConfig.getProperty("template.dir"); log.debug("Templates dir = "+templateDir); } - + log.debug(config); - + log.debug("TemplateResourceLoader : initialization complete."); } - - + + /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String) */ - public InputStream getResourceStream(String name) + public InputStream getResourceStream(String name) throws ResourceNotFoundException { - + log.debug("Looking up resource named ... "+name); - + if (name == null || name.length() == 0) { throw new ResourceNotFoundException("No template name provided"); } - + InputStream result = null; - + try { if(!name.startsWith("/")) name = templateDir + "/" + name; else { name = templateDir + name; } - + result = new FileInputStream(name); - + } catch(Exception e) { throw new ResourceNotFoundException(e.getMessage()); } - + if(result == null) { throw new ResourceNotFoundException("Couldn't find "+name); } - + return result; } - - + + /** * Files loaded by this resource loader are considered static, so they are * never reloaded by velocity. @@ -101,8 +101,8 @@ public InputStream getResourceStream(String name) public boolean isSourceModified(Resource arg0) { return false; } - - + + /** * Defaults to return 0. * @@ -111,5 +111,5 @@ public boolean isSourceModified(Resource arg0) { public long getLastModified(Resource arg0) { return 0; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRenderer.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRenderer.java index a56a184215..bcfc4344f3 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRenderer.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRenderer.java @@ -37,84 +37,84 @@ * Renderer for Velocity templates. */ public class VelocityRenderer implements Renderer { - + private static Log log = LogFactory.getLog(VelocityRenderer.class); - + // the original template we are supposed to render private Template renderTemplate = null; - + // the velocity templates private org.apache.velocity.Template velocityTemplate = null; - + // a possible exception private Exception parseException = null; - - + + public VelocityRenderer(Template template) throws Exception { - + // the Template we are supposed to render this.renderTemplate = template; - + try { // make sure that we can locate the template // if we can't then this will throw an exception velocityTemplate = PlanetVelocity.getTemplate(template.getId(), "UTF-8"); - + } catch(ResourceNotFoundException ex) { // velocity couldn't find the resource so lets log a warning log.warn("Error creating renderer for "+template.getId()+ " due to ["+ex.getMessage()+"]"); - + // then just rethrow so that the caller knows this instantiation failed throw ex; - + } catch(ParseErrorException ex) { // in the case of a parsing error we want to render an // error page instead so the user knows what was wrong parseException = ex; - + // need to lookup error page template velocityTemplate = PlanetVelocity.getTemplate("error-page.vm"); - + } catch(Exception ex) { // some kind of generic/unknown exception, dump it to the logs log.error("Unknown exception creatting renderer for "+template.getId(), ex); - + // throw if back to the caller throw ex; } } - - + + public void render(Map model, Writer out) throws RenderingException { - + try { if(parseException != null) { - + Context ctx = new VelocityContext(model); ctx.put("exception", parseException); ctx.put("exceptionSource", renderTemplate.getId()); - + // render output to Writer velocityTemplate.merge(ctx, out); - + // and we're done return; } - + long startTime = System.currentTimeMillis(); - + // convert model to Velocity Context Context ctx = new VelocityContext(model); - + // no decorator, so just merge template to our output writer velocityTemplate.merge(ctx, out); long endTime = System.currentTimeMillis(); long renderTime = (endTime - startTime)/1000; - + log.debug("Rendered ["+renderTemplate.getId()+"] in "+renderTime+" secs"); - + } catch (Exception ex) { // wrap and rethrow so caller can deal with it throw new RenderingException("Error during rendering", ex); diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRendererFactory.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRendererFactory.java index 65ea2617eb..6bb57cfb08 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRendererFactory.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/VelocityRendererFactory.java @@ -29,21 +29,21 @@ * Velocity RendererFactory for Roller. */ public class VelocityRendererFactory implements RendererFactory { - + private static Log log = LogFactory.getLog(VelocityRendererFactory.class); - - + + public Renderer getRenderer(Template template) { - + Renderer renderer = null; - + // nothing we can do with null values if(template.getTemplateLanguage() == null || template.getId() == null) { return null; } - - if("velocity".equals(template.getTemplateLanguage())) { - + + if("velocity".equals(template.getTemplateLanguage())) { + // standard velocity template try { renderer = new VelocityRenderer(template); @@ -51,11 +51,11 @@ public Renderer getRenderer(Template template) { // some kind of exception so we don't have a renderer // we do catching/logging in VelocityRenderer constructor return null; - } - + } + } - + return renderer; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/WebappResourceLoader.java b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/WebappResourceLoader.java index 5740e1eaa3..3c6ee51ea1 100644 --- a/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/WebappResourceLoader.java +++ b/planet-web/src/main/java/org/apache/roller/planet/ui/rendering/velocity/WebappResourceLoader.java @@ -37,62 +37,62 @@ * /WEB-INF/velocity/, which is where we keep velocity files. */ public class WebappResourceLoader extends ResourceLoader { - + private static Log log = LogFactory.getLog(WebappResourceLoader.class); - + private ServletContext mContext = null; - - + + /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#init(org.apache.commons.collections.ExtendedProperties) */ public void init(ExtendedProperties config) { - + log.debug("WebappResourceLoader : initialization starting."); - + if (mContext == null) { mContext = PlanetContext.getServletContext(); log.debug("Servlet Context = "+mContext.getRealPath("/WEB-INF/velocity/")); } - + log.debug(config); - + log.debug("WebappResourceLoader : initialization complete."); } - - + + /** * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String) */ - public InputStream getResourceStream(String name) + public InputStream getResourceStream(String name) throws ResourceNotFoundException { - + log.debug("Looking up resource named ... "+name); - + if (name == null || name.length() == 0) { throw new ResourceNotFoundException("No template name provided"); } - + InputStream result = null; - + try { if(!name.startsWith("/")) name = "/WEB-INF/velocity/" + name; - + result = this.mContext.getResourceAsStream(name); - + } catch(Exception e) { throw new ResourceNotFoundException(e.getMessage()); } - + if(result == null) { throw new ResourceNotFoundException("Couldn't find "+name); } - + return result; } - - + + /** * Files loaded by this resource loader are considered static, so they are * never reloaded by velocity. @@ -102,8 +102,8 @@ public InputStream getResourceStream(String name) public boolean isSourceModified(Resource arg0) { return false; } - - + + /** * Defaults to return 0. * @@ -112,5 +112,5 @@ public boolean isSourceModified(Resource arg0) { public long getLastModified(Resource arg0) { return 0; } - + } diff --git a/planet-web/src/main/java/org/apache/roller/util/OldUtilities.java b/planet-web/src/main/java/org/apache/roller/util/OldUtilities.java index 2002bded52..6359427da0 100644 --- a/planet-web/src/main/java/org/apache/roller/util/OldUtilities.java +++ b/planet-web/src/main/java/org/apache/roller/util/OldUtilities.java @@ -38,99 +38,99 @@ * Utility methods needed by old Roller 2.X macros/templates. * Deprecated because they are either redundant or unnecesary. */ -public class OldUtilities { - +public class OldUtilities { + /** The Log instance for this class. */ private static Log mLogger = LogFactory.getLog(OldUtilities.class); - + private static Pattern mLinkPattern = - Pattern.compile("", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_B_TAG_PATTERN = + Pattern.compile("", Pattern.CASE_INSENSITIVE); + private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("<b>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_B_TAG_PATTERN = + private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("</b>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_I_TAG_PATTERN = + private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("<i>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_I_TAG_PATTERN = + private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("</i>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern BR_TAG_PATTERN = + private static final Pattern BR_TAG_PATTERN = Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_P_TAG_PATTERN = + private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("<p>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_P_TAG_PATTERN = + private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("</p>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_PRE_TAG_PATTERN = + private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_PRE_TAG_PATTERN = + private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_UL_TAG_PATTERN = + private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_UL_TAG_PATTERN = + private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_OL_TAG_PATTERN = + private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_OL_TAG_PATTERN = + private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_LI_TAG_PATTERN = + private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("<li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_LI_TAG_PATTERN = + private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("</li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_A_TAG_PATTERN = + private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("</a>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_A_TAG_PATTERN = + private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE); - private static final Pattern QUOTE_PATTERN = + private static final Pattern QUOTE_PATTERN = Pattern.compile(""", Pattern.CASE_INSENSITIVE); - + public static boolean isEmpty(String str) { if (str == null) return true; return "".equals(str.trim()); } - + public static boolean isNotEmpty(String str) { return !isEmpty(str); } - + public static String[] split(String str1, String str2) { return StringUtils.split(str1, str2); } - + public static String replace(String src, String target, String rWith) { return StringUtils.replace(src, target, rWith); } - + public static String replace(String src, String target, String rWith, int maxCount) { return StringUtils.replace(src, target, rWith, maxCount); } - + public static boolean equals(String str1, String str2) { return StringUtils.equals(str1, str2); } - + public static boolean isAlphanumeric(String str) { return StringUtils.isAlphanumeric(str); } - + public static String[] stripAll(String[] strs) { return StringUtils.stripAll(strs); } - + public static String left(String str, int length) { return StringUtils.left(str, length); } - + public static String escapeHTML(String str) { return StringEscapeUtils.escapeHtml(str); } - + public static String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". Replace @@ -139,7 +139,7 @@ public static String unescapeHTML(String str) { public static String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -148,7 +148,7 @@ public static String removeHTML(String str) { public static String removeHTML(String str, boolean addSpace) { return Utilities.removeHTML(str, addSpace); } - + /** * Autoformat. */ @@ -156,14 +156,14 @@ public static String autoformat(String s) { String ret = StringUtils.replace(s, "\n", "
    "); return ret; } - + /** * Return date for current time. */ public static Date getNow() { return new Date(); } - + /** * Format date using SimpleDateFormat format string. */ @@ -171,35 +171,35 @@ public static String formatDate(Date d, String fmt) { SimpleDateFormat format = new SimpleDateFormat(fmt); return format.format(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Date(Date d) { return DateUtil.formatIso8601(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Day(Date d) { return DateUtil.formatIso8601Day(d); } - + /** * Return a date in RFC-822 format. */ public static String formatRfc822Date(Date date) { return DateUtil.formatRfc822(date); } - + /** * Return a date in RFC-822 format. */ public static String format8charsDate(Date date) { return DateUtil.format8chars(date); } - + /** * Strips HTML and truncates. */ @@ -207,21 +207,21 @@ public static String truncate( String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); - + // quickly adjust the upper if it is set lower than 'lower' if (upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -231,37 +231,37 @@ public static String truncate( str2 = str2.substring(0, upper); loc = upper; } - + // the string was truncated, so we append the appendToEnd String str2 = str2 + appendToEnd; } - + return str2; } - + public static String truncateNicely(String str, int lower, int upper, String appendToEnd) { return Utilities.truncateNicely(str, lower, upper, appendToEnd); } - + public static String truncateText(String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -275,18 +275,18 @@ public static String truncateText(String str, int lower, int upper, String appen str = str2 + appendToEnd; } return str; - } - + } + public static String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public static String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } - + /** * URL encoding. * @param s a string to be URL-encoded @@ -303,7 +303,7 @@ public static final String encode(String s) { return s; } } - + /** * URL decoding. * @param s a URL-encoded string to be URL-decoded @@ -320,7 +320,7 @@ public static final String decode(String s) { return s; } } - + /** * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML. */ @@ -347,7 +347,7 @@ public static String addNofollow(String html) { buf.append(html); return buf.toString(); } - + /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes <b>, <i>, <p>, <br>, @@ -357,11 +357,11 @@ public static String addNofollow(String html) { * @return the transformed String */ public static String transformToHTMLSubset(String s) { - + if (s == null) { return null; } - + s = replace(s, OPENING_B_TAG_PATTERN, ""); s = replace(s, CLOSING_B_TAG_PATTERN, ""); s = replace(s, OPENING_I_TAG_PATTERN, ""); @@ -380,7 +380,7 @@ public static String transformToHTMLSubset(String s) { s = replace(s, OPENING_LI_TAG_PATTERN, "
  • "); s = replace(s, CLOSING_LI_TAG_PATTERN, "
  • "); s = replace(s, QUOTE_PATTERN, "\""); - + // HTTP links s = replace(s, CLOSING_A_TAG_PATTERN, "
    "); Matcher m = OPENING_A_TAG_PATTERN.matcher(s); @@ -392,51 +392,51 @@ public static String transformToHTMLSubset(String s) { s = s.substring(0, start) + link + s.substring(end, s.length()); m = OPENING_A_TAG_PATTERN.matcher(s); } - + // escaped angle brackets s = s.replaceAll("&lt;", "<"); s = s.replaceAll("&gt;", ">"); s = s.replaceAll("&#", "&#"); - + return s; } - + private static String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public static String toBase64(byte[] aValue) { - + final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - + int byte1; int byte2; int byte3; int iByteLen = aValue.length; StringBuffer tt = new StringBuffer(); - + for (int i = 0; i < iByteLen; i += 3) { boolean bByte2 = (i + 1) < iByteLen; boolean bByte3 = (i + 2) < iByteLen; byte1 = aValue[i] & 0xFF; byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0; byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0; - + tt.append(m_strBase64Chars.charAt(byte1 / 4)); tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16))); tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '=')); tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '=')); } - + return tt.toString(); } - - + + //------------------------------------------------------------------------ /** * Escape, but do not replace HTML. @@ -446,7 +446,7 @@ public static String toBase64(byte[] aValue) { public static String escapeHTML(String s, boolean escapeAmpersand) { return Utilities.escapeHTML(s, escapeAmpersand); } - + //------------------------------------------------------------------------ /** * Replace occurrences of str1 in string str with str2 @@ -455,7 +455,7 @@ public static String stringReplace(String str, String str1, String str2) { String ret = StringUtils.replace(str,str1,str2); return ret; } - + //------------------------------------------------------------------------ /** * Replace occurrences of str1 in string str with str2 @@ -472,9 +472,9 @@ public static String stringReplace( String ret = StringUtils.replace(str,str1,str2,maxCount); return ret; } - - + + /** * Encode a string using Base64 encoding. Used when storing passwords * as cookies. @@ -487,10 +487,10 @@ public static String stringReplace( * @throws IOException */ public static String encodeString(String str) throws IOException { - String encodedStr = new String(Base64.encodeBase64(str.getBytes())); + String encodedStr = new String(Base64.encodeBase64(str.getBytes())); return (encodedStr.trim()); } - + /** * Decode a string using Base64 encoding. * @@ -499,10 +499,10 @@ public static String encodeString(String str) throws IOException { * @throws IOException */ public static String decodeString(String str) throws IOException { - String value = new String(Base64.decodeBase64(str.getBytes())); - return (value); + String value = new String(Base64.decodeBase64(str.getBytes())); + return (value); } - + /** * @param str * @return @@ -517,7 +517,7 @@ private static String stripLineBreaks(String str) { str = str.replaceAll("

    ",""); return str; } - + /** * Need need to get rid of any user-visible HTML tags once all text has been * removed such as <BR>. This sounds like a better approach than removing @@ -534,7 +534,7 @@ private static String removeVisibleHTMLTags(String str) { str = stripLineBreaks(str); StringBuffer result = new StringBuffer(str); StringBuffer lcresult = new StringBuffer(str.toLowerCase()); - + // ') { return (">"); } - + // Convert ampersand else if (ch == '&') { return ("&"); } - + // Commented out to eliminate redundant numeric character codes (ROL-507) // High-ASCII character //else if (ch >= 128) @@ -623,24 +623,24 @@ else if (ch == '&') { //c = ch; //return ("&#" + c + ';'); //} - + // Convert double quote else if (xml && (ch == '"')) { return ("""); } - + // Convert single quote else if (xml && (ch == '\'')) { return ("'"); } - + // No conversion else { // Return character as string return (String.valueOf(ch)); } } - + /** * Converts a text string to HTML or XML entities. * @@ -653,17 +653,17 @@ else if (xml && (ch == '\'')) { public static final String textToHTML(String text, boolean xml) { if (text == null) return "null"; final StringBuffer html = new StringBuffer(); - + // Loop thru each characters of the text for (int i = 0; i < text.length(); i++) { // Convert character to HTML/XML html.append(charToHTML(text.charAt(i), xml)); } - + // Return HTML/XML string return html.toString(); } - + /** * Converts a text string to HTML or XML entities. * @@ -674,7 +674,7 @@ public static final String textToHTML(String text, boolean xml) { public static final String textToHTML(String text) { return textToHTML(text, false); } - + /** * Converts a text string to XML entities. * @@ -685,7 +685,7 @@ public static final String textToHTML(String text) { public static final String textToXML(String text) { return textToHTML(text, true); } - + /** * Converts a text string to HTML or XML entities. * @param text The string to convert. @@ -694,17 +694,17 @@ public static final String textToXML(String text) { public static final String textToCDATA(String text) { if (text == null) return "null"; final StringBuffer html = new StringBuffer(); - + // Loop thru each characters of the text for (int i = 0; i < text.length(); i++) { // Convert character to HTML/XML html.append(charToCDATA(text.charAt(i))); } - + // Return HTML/XML string return html.toString(); } - + /** * Converts a character to CDATA character. * @param ch The character to convert. @@ -712,18 +712,18 @@ public static final String textToCDATA(String text) { */ public static final String charToCDATA(char ch) { int c; - + if (ch >= 128) { c = ch; - + return ("&#" + c + ';'); } - + // No conversion else { // Return character as string return (String.valueOf(ch)); } } - + } diff --git a/planet-web/src/main/java/org/apache/roller/util/StandaloneWebappClassLoader.java b/planet-web/src/main/java/org/apache/roller/util/StandaloneWebappClassLoader.java index cf01f8640d..9eaaf3a62e 100644 --- a/planet-web/src/main/java/org/apache/roller/util/StandaloneWebappClassLoader.java +++ b/planet-web/src/main/java/org/apache/roller/util/StandaloneWebappClassLoader.java @@ -29,23 +29,23 @@ import java.util.List; /** - * ClassLoader to enable running webapp classes outside of webapp. - * You provide webappDir and jarsDir paths and the classloader will include + * ClassLoader to enable running webapp classes outside of webapp. + * You provide webappDir and jarsDir paths and the classloader will include * webappDir/WEB-INF/classes, webappDir/WEB-INF/lib/*jar and jarsDir/*.jar. */ public class StandaloneWebappClassLoader extends URLClassLoader { public static String FS = File.separator; - + /** Use calling class's parent classloader */ public StandaloneWebappClassLoader(String webappDir, String jarsDir) throws Exception { super(buildURLsArray(webappDir, jarsDir)); } - + /** Use a specific parent classloader, or null for no parent */ public StandaloneWebappClassLoader(String webappDir, String jarsDir, ClassLoader cl) throws Exception { super(buildURLsArray(webappDir, jarsDir), cl); } - + private static URL[] buildURLsArray(String webappDir, String jarsDir) throws Exception { // Create collection of URLs needed for classloader List urlList = new ArrayList(); @@ -53,17 +53,17 @@ private static URL[] buildURLsArray(String webappDir, String jarsDir) throws Exc // Add WEB-INF/lib jars String libPath = webappDir + FS + "WEB-INF" + FS + "lib"; addURLs(libPath, urlList); - + // Added WEB-INF/classes String classesPath = webappDir + FS + "WEB-INF" + FS + "classes" + FS; urlList.add(new URL("file://" + classesPath)); - + // Add additional jars addURLs(jarsDir, urlList); - - return (URL[])urlList.toArray(new URL[urlList.size()]); + + return (URL[])urlList.toArray(new URL[urlList.size()]); } - + private static void addURLs(String dirPath, List urlList) throws Exception { File libDir = new File(dirPath); String[] libJarNames = libDir.list(new FilenameFilter() { @@ -73,7 +73,7 @@ public boolean accept(File dir, String pathname) { } return false; } - }); + }); for (int i=0; i", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_B_TAG_PATTERN = + Pattern.compile("", Pattern.CASE_INSENSITIVE); + private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("<b>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_B_TAG_PATTERN = + private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("</b>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_I_TAG_PATTERN = + private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("<i>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_I_TAG_PATTERN = + private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("</i>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern BR_TAG_PATTERN = + private static final Pattern BR_TAG_PATTERN = Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_P_TAG_PATTERN = + private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("<p>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_P_TAG_PATTERN = + private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("</p>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_PRE_TAG_PATTERN = + private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_PRE_TAG_PATTERN = + private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_UL_TAG_PATTERN = + private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_UL_TAG_PATTERN = + private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_OL_TAG_PATTERN = + private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_OL_TAG_PATTERN = + private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_LI_TAG_PATTERN = + private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("<li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_LI_TAG_PATTERN = + private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("</li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_A_TAG_PATTERN = + private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("</a>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_A_TAG_PATTERN = + private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE); - private static final Pattern QUOTE_PATTERN = + private static final Pattern QUOTE_PATTERN = Pattern.compile(""", Pattern.CASE_INSENSITIVE); - + private TimeZone tz = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "utils"; } - - + + // /** Init page model based on request */ // public void init(Map initData) throws PlanetException { -// +// // // extract request object -// this.request = (HttpServletRequest) initData.get("request"); +// this.request = (HttpServletRequest) initData.get("request"); // // // extract timezone if available // WeblogRequest weblogRequest = (WeblogRequest)initData.get("weblogRequest"); @@ -111,10 +111,10 @@ public String getModelName() { // tz = weblogRequest.getWeblog().getTimeZoneInstance(); // } // } -// -// -// //---------------------------------------------------- Authentication utils -// +// +// +// //---------------------------------------------------- Authentication utils +// // public boolean isUserAuthorizedToAuthor(WebsiteDataWrapper weblog) { // try { // RollerSession rses = RollerSession.getRollerSession(request); @@ -126,7 +126,7 @@ public String getModelName() { // } // return false; // } -// +// // public boolean isUserAuthorizedToAdmin(WebsiteDataWrapper weblog) { // try { // RollerSession rses = RollerSession.getRollerSession(request); @@ -138,11 +138,11 @@ public String getModelName() { // } // return false; // } -// +// // public boolean isUserAuthenticated() { // return (request.getUserPrincipal() != null); // } - + //-------------------------------------------------------------- Date utils /** * Return date for current time. @@ -150,54 +150,54 @@ public String getModelName() { public static Date getNow() { return new Date(); } - + /** * Format date using SimpleDateFormat format string. */ public String formatDate(Date d, String fmt) { if(d == null || fmt == null) return fmt; - + SimpleDateFormat format = new SimpleDateFormat(fmt); if (tz != null) { format.setTimeZone(tz); } return format.format(d); } - + /** * Format date using SimpleDateFormat format string. */ public static String formatDate(Date d, String fmt, TimeZone tzOverride) { if(d == null || fmt == null) return fmt; - + SimpleDateFormat format = new SimpleDateFormat(fmt); format.setTimeZone(tzOverride); return format.format(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Date(Date d) { return DateUtil.formatIso8601(d); } - + /** * Format date in ISO-8601 format. */ public static String formatIso8601Day(Date d) { return DateUtil.formatIso8601Day(d); } - + /** * Return a date in RFC-822 format. */ public static String formatRfc822Date(Date date) { return DateUtil.formatRfc822(date); } - + /** * Return a date in RFC-822 format. */ @@ -206,66 +206,66 @@ public static String format8charsDate(Date date) { } //------------------------------------------------------------ String utils - + public static boolean isEmpty(String str) { if (str == null) return true; return "".equals(str.trim()); } - + public static boolean isNotEmpty(String str) { return !isEmpty(str); } - + public static String[] split(String str1, String str2) { return StringUtils.split(str1, str2); } - - + + public static boolean equals(String str1, String str2) { return StringUtils.equals(str1, str2); } - + public static boolean isAlphanumeric(String str) { return StringUtils.isAlphanumeric(str); } - + public static String[] stripAll(String[] strs) { return StringUtils.stripAll(strs); } - + public static String left(String str, int length) { return StringUtils.left(str, length); } - + public static String escapeHTML(String str) { return StringEscapeUtils.escapeHtml(str); } - + public static String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + public static String escapeXML(String str) { return StringEscapeUtils.escapeXml(str); } - + public static String unescapeXML(String str) { return StringEscapeUtils.unescapeXml(str); } - + public static String replace(String src, String target, String rWith) { return StringUtils.replace(src, target, rWith); } - + public static String replace(String src, String target, String rWith, int maxCount) { return StringUtils.replace(src, target, rWith, maxCount); } - + private static String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". Replace @@ -274,7 +274,7 @@ private static String replace(String string, Pattern pattern, String replacement public static String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -283,7 +283,7 @@ public static String removeHTML(String str) { public static String removeHTML(String str, boolean addSpace) { return Utilities.removeHTML(str, addSpace); } - + /** * Autoformat. */ @@ -298,21 +298,21 @@ public static String truncate( String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); - + // quickly adjust the upper if it is set lower than 'lower' if (upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -322,37 +322,37 @@ public static String truncate( str2 = str2.substring(0, upper); loc = upper; } - + // the string was truncated, so we append the appendToEnd String str2 = str2 + appendToEnd; } - + return str2; } - + public static String truncateNicely(String str, int lower, int upper, String appendToEnd) { return Utilities.truncateNicely(str, lower, upper, appendToEnd); } - + public static String truncateText(String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -366,18 +366,18 @@ public static String truncateText(String str, int lower, int upper, String appen str = str2 + appendToEnd; } return str; - } - + } + public static String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public static String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } - + /** * URL encoding. * @param s a string to be URL-encoded @@ -394,7 +394,7 @@ public static final String encode(String s) { return s; } } - + /** * URL decoding. * @param s a URL-encoded string to be URL-decoded @@ -411,7 +411,7 @@ public static final String decode(String s) { return s; } } - + /** * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML. */ @@ -438,7 +438,7 @@ public static String addNofollow(String html) { buf.append(html); return buf.toString(); } - + /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes <b>, <i>, <p>, <br>, @@ -448,11 +448,11 @@ public static String addNofollow(String html) { * @return the transformed String */ public static String transformToHTMLSubset(String s) { - + if (s == null) { return null; } - + s = replace(s, OPENING_B_TAG_PATTERN, ""); s = replace(s, CLOSING_B_TAG_PATTERN, ""); s = replace(s, OPENING_I_TAG_PATTERN, ""); @@ -471,7 +471,7 @@ public static String transformToHTMLSubset(String s) { s = replace(s, OPENING_LI_TAG_PATTERN, "

  • "); s = replace(s, CLOSING_LI_TAG_PATTERN, "
  • "); s = replace(s, QUOTE_PATTERN, "\""); - + // HTTP links s = replace(s, CLOSING_A_TAG_PATTERN, ""); Matcher m = OPENING_A_TAG_PATTERN.matcher(s); @@ -483,43 +483,43 @@ public static String transformToHTMLSubset(String s) { s = s.substring(0, start) + link + s.substring(end, s.length()); m = OPENING_A_TAG_PATTERN.matcher(s); } - + // escaped angle brackets s = s.replaceAll("&lt;", "<"); s = s.replaceAll("&gt;", ">"); s = s.replaceAll("&#", "&#"); - + return s; } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public static String toBase64(byte[] aValue) { - + final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - + int byte1; int byte2; int byte3; int iByteLen = aValue.length; StringBuffer tt = new StringBuffer(); - + for (int i = 0; i < iByteLen; i += 3) { boolean bByte2 = (i + 1) < iByteLen; boolean bByte3 = (i + 2) < iByteLen; byte1 = aValue[i] & 0xFF; byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0; byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0; - + tt.append(m_strBase64Chars.charAt(byte1 / 4)); tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16))); tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '=')); tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '=')); } - + return tt.toString(); } - + } diff --git a/planet-web/src/main/resources/ehcache.xml b/planet-web/src/main/resources/ehcache.xml index 10e3a3415b..2d9f0b8ee7 100644 --- a/planet-web/src/main/resources/ehcache.xml +++ b/planet-web/src/main/resources/ehcache.xml @@ -1,7 +1,7 @@ - + - + diff --git a/planet-web/src/main/resources/struts.xml b/planet-web/src/main/resources/struts.xml index 9bbf72df11..f7f7473700 100644 --- a/planet-web/src/main/resources/struts.xml +++ b/planet-web/src/main/resources/struts.xml @@ -14,13 +14,13 @@ /WEB-INF/jsps/MainMenu.jsp - + - + - + /WEB-INF/jsps/admin/ConfigForm.jsp diff --git a/planet-web/src/main/webapp/WEB-INF/sun-web.xml b/planet-web/src/main/webapp/WEB-INF/sun-web.xml index 29b10bf4e5..1da2276693 100644 --- a/planet-web/src/main/webapp/WEB-INF/sun-web.xml +++ b/planet-web/src/main/webapp/WEB-INF/sun-web.xml @@ -3,7 +3,7 @@ - + diff --git a/planet-web/src/main/webapp/WEB-INF/web.xml b/planet-web/src/main/webapp/WEB-INF/web.xml index 11a9787ac5..1bdab21df9 100644 --- a/planet-web/src/main/webapp/WEB-INF/web.xml +++ b/planet-web/src/main/webapp/WEB-INF/web.xml @@ -1,28 +1,28 @@ - + Planet Roller - + struts2 org.apache.struts2.dispatcher.FilterDispatcher - + PersistenceSessionFilter org.apache.roller.planet.ui.core.filters.PersistenceSessionFilter - + RequestMappingFilter org.apache.roller.planet.ui.rendering.filters.RequestMappingFilter - + DebugFilter org.apache.roller.planet.ui.core.filters.DebugFilter - + - + PersistenceSessionFilter /planet-ui/* REQUEST - + RequestMappingFilter /* REQUEST - + struts2 /* REQUEST FORWARD - - + + HomepageServlet org.apache.roller.planet.ui.rendering.servlets.HomepageServlet 5 - + FeedServlet org.apache.roller.planet.ui.rendering.servlets.FeedServlet 5 - + PageServlet org.apache.roller.planet.ui.rendering.servlets.PageServlet 5 - + OpmlServlet org.apache.roller.planet.ui.rendering.servlets.OpmlServlet 5 - + HomepageServlet /planet-ui/rendering/homepage - + FeedServlet /planet-ui/rendering/feed/* - + PageServlet /planet-ui/rendering/page/* - + OpmlServlet /planet-ui/rendering/opml/* - - + + org.apache.roller.planet.ui.core.PlanetContext - + - + index.jsp index.html - + planet-ui @@ -125,13 +125,13 @@ admin - - + + admin - + FORM @@ -139,5 +139,5 @@ /planet-ui/Login.action?failed=true - + diff --git a/pom.xml b/pom.xml index 0483519927..6f7eb6f272 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,3 @@ - @@ -117,7 +116,7 @@ true --> - + - - @@ -84,7 +84,7 @@ limitations under the License. - AnakiaTask is not present! Please check to make sure that + AnakiaTask is not present! Please check to make sure that velocity.jar is in your classpath. @@ -105,11 +105,11 @@ limitations under the License. - diff --git a/site/xdocs/dev/sitemap.xml b/site/xdocs/dev/sitemap.xml index df3a2edec3..76bf7a2757 100644 --- a/site/xdocs/dev/sitemap.xml +++ b/site/xdocs/dev/sitemap.xml @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. --> diff --git a/site/xdocs/download.xml b/site/xdocs/download.xml index bd1406351f..115e6ad8fc 100644 --- a/site/xdocs/download.xml +++ b/site/xdocs/download.xml @@ -23,9 +23,9 @@ limitations under the License.
    Download a Release of Apache Roller

    - Use the links below to download a release of Apache Roller from one of - our mirrors. You can verify the integrity of the - downloaded files using signatures downloaded from our main distribution + Use the links below to download a release of Apache Roller from one of + our mirrors. You can verify the integrity of the + downloaded files using signatures downloaded from our main distribution directory.

    @@ -38,9 +38,9 @@ limitations under the License. logo [end] - The currently selected mirror is [preferred]. If you - encounter a problem with this mirror, please select another mirror. - If all mirrors are failing, there are backup mirrors (at + The currently selected mirror is [preferred]. If you + encounter a problem with this mirror, please select another mirror. + If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

    @@ -73,11 +73,11 @@ limitations under the License.

    Roller 4.0.1 is the "best available" version of Roller. Check the - What's New in Roller 4.0 page to learn more about the features and + What's New in Roller 4.0 page to learn more about the features and changes in this release and the Release Notes to learn what bugs are fixed in 4.0.1 release.

    - +
    • Roller Web Application (what you need to run Roller)
        diff --git a/site/xdocs/downloads.xml b/site/xdocs/downloads.xml index 5ebaab8d69..a8f449da30 100644 --- a/site/xdocs/downloads.xml +++ b/site/xdocs/downloads.xml @@ -23,8 +23,8 @@ limitations under the License.
        Apache Roller Releases

        - Releases of the Apache Roller blog server are made available to the - general public at no charge, under the + Releases of the Apache Roller blog server are made available to the + general public at no charge, under the Apache License, in both binary and source distributions.

        @@ -42,21 +42,21 @@ limitations under the License.

      - Project releases are approved by vote of the Apache Roller Project - Management Committee (PMC). Support for a release is provided by project - volunteers on the project + Project releases are approved by vote of the Apache Roller Project + Management Committee (PMC). Support for a release is provided by project + volunteers on the project mailing lists. - Additional free support is provided by many other volunteer subscribers - to the list. Bugs found in a release may be discussed on the list and + Additional free support is provided by many other volunteer subscribers + to the list. Bugs found in a release may be discussed on the list and reported through the issue tracker.

      - +

      Roller is a Project of the Apache Software Foundation (ASF), formed by a resolution of the - ASF Board of Directors. + ASF Board of Directors. As an ASF Project, Struts is subject to the ASF Bylaws and the direction of the ASF Board. diff --git a/site/xdocs/index.xml b/site/xdocs/index.xml index e9b14471c3..d8a2866565 100644 --- a/site/xdocs/index.xml +++ b/site/xdocs/index.xml @@ -22,26 +22,26 @@ limitations under the License.

      Welcome!

      - Apache Roller is a full-featured, multi-user and group-blog - server suitable for blog sites large and small. This is the project's - homepage, which provides a brief overview of the software and project as - well as links to - project news, - downloads, - user documentation, - install guide, + Apache Roller is a full-featured, multi-user and group-blog + server suitable for blog sites large and small. This is the project's + homepage, which provides a brief overview of the software and project as + well as links to + project news, + downloads, + user documentation, + install guide, mailing-lists, bug tracker, - wiki and the - FAQ. + wiki and the + FAQ.

      Overview

      Roller is a Java web application that should be able to run on any Java EE - server and any relational database. Currently, Roller is best supported on - Tomcat and MySQL -- but users have reported success running Roller on - Glassfish, Websphere, JBoss, Resin, Geronimo, Derby, PostgresSQL, + server and any relational database. Currently, Roller is best supported on + Tomcat and MySQL -- but users have reported success running Roller on + Glassfish, Websphere, JBoss, Resin, Geronimo, Derby, PostgresSQL, Oracle, etc.)

      Here are some of Roller's key features:

      diff --git a/site/xdocs/stylesheets/project.xml b/site/xdocs/stylesheets/project.xml index 0adf2c16af..4e58dea498 100644 --- a/site/xdocs/stylesheets/project.xml +++ b/site/xdocs/stylesheets/project.xml @@ -18,7 +18,7 @@ limitations under the License. Apache Roller - + Project information
    • Project HOME
    • Project Blog
    • diff --git a/test-utils/src/main/java/org/apache/roller/weblogger/ant/StartDerbyTask.java b/test-utils/src/main/java/org/apache/roller/weblogger/ant/StartDerbyTask.java index 8cec37ab5f..6058b902ff 100644 --- a/test-utils/src/main/java/org/apache/roller/weblogger/ant/StartDerbyTask.java +++ b/test-utils/src/main/java/org/apache/roller/weblogger/ant/StartDerbyTask.java @@ -36,7 +36,7 @@ public class StartDerbyTask extends Task { private String databaseScriptsDir = null; private String port = null; private boolean skip = false; - + public void execute() throws BuildException { try { if (!isSkip()) { @@ -83,9 +83,9 @@ public void execute() throws BuildException { System.out.println(message); } ignored.printStackTrace(); - } + } + - } else { System.out.println("Skipping Derby startup"); } @@ -93,7 +93,7 @@ public void execute() throws BuildException { e.printStackTrace(); throw new BuildException("ERROR starting Derby"); } - + } /** * @return Returns the databaseDir. diff --git a/test-utils/src/main/java/org/apache/roller/weblogger/ant/StopDerbyTask.java b/test-utils/src/main/java/org/apache/roller/weblogger/ant/StopDerbyTask.java index e83a46328a..086026513d 100644 --- a/test-utils/src/main/java/org/apache/roller/weblogger/ant/StopDerbyTask.java +++ b/test-utils/src/main/java/org/apache/roller/weblogger/ant/StopDerbyTask.java @@ -41,7 +41,7 @@ public void execute() throws BuildException { if (!isSkip()) { Class.forName("org.apache.derby.jdbc.ClientDriver"); - + String driverURL = "jdbc:derby://localhost:" + port + "/rollerdb"; Connection conn = @@ -60,7 +60,7 @@ public void execute() throws BuildException { System.out.println("=============="); System.out.println("Stopping Derby"); System.out.println("=============="); - + try { DriverManager.getConnection(driverURL + ";shutdown=true"); } catch (Exception ignored) {} diff --git a/tlp-resolution.txt b/tlp-resolution.txt index db0263f91f..64bd8909e6 100644 --- a/tlp-resolution.txt +++ b/tlp-resolution.txt @@ -3,8 +3,8 @@ Establish the Apache Roller project WHEREAS, the Board of Directors deems it to be in the best interests of the Foundation and consistent with the Foundation's purpose to establish a Project Management - Committee charged with the creation and maintenance of - open-source software related to the Roller blog server, + Committee charged with the creation and maintenance of + open-source software related to the Roller blog server, for distribution at no charge to the public. NOW, THEREFORE, BE IT RESOLVED, that a Project Management @@ -13,7 +13,7 @@ Establish the Apache Roller project Foundation; and be it further RESOLVED, that the Apache Roller Project be and hereby is - responsible for the creation and maintenance of open-source + responsible for the creation and maintenance of open-source software related to the Roller blog server; and be it further RESOLVED, that the office of "Vice President, Roller" be and diff --git a/weblogger-assembly/pom.xml b/weblogger-assembly/pom.xml index 92d86e00be..22747c5299 100644 --- a/weblogger-assembly/pom.xml +++ b/weblogger-assembly/pom.xml @@ -58,14 +58,14 @@ - + tomcat-assembly tomcat - + @@ -82,14 +82,14 @@ - + javaee-assembly javaee - + @@ -105,14 +105,14 @@ - + jboss-assembly jboss - + @@ -128,7 +128,7 @@ - + release-sign-artifacts diff --git a/weblogger-assembly/src/main/assembly/for-javaee.xml b/weblogger-assembly/src/main/assembly/for-javaee.xml index 5c6021ae4a..6c6caab2c6 100644 --- a/weblogger-assembly/src/main/assembly/for-javaee.xml +++ b/weblogger-assembly/src/main/assembly/for-javaee.xml @@ -18,7 +18,7 @@ --> @@ -29,35 +29,35 @@ false - - + + ../weblogger-war-assembly/target/roller-${artifact.version}-javaee.war ${artifact.artifactId}-${artifact.version}-javaee/webapp - - + + ../README.txt ${artifact.artifactId}-${artifact.version}-javaee - - + + ../NOTICE.txt ${artifact.artifactId}-${artifact.version}-javaee - - + + ../LICENSE.txt ${artifact.artifactId}-${artifact.version}-javaee - - + + ../weblogger-docs/installguide/generated/roller-install-guide.pdf ${artifact.artifactId}-${artifact.version}-javaee/docs - - + + ../weblogger-docs/userguide/generated/roller-user-guide.pdf ${artifact.artifactId}-${artifact.version}-javaee/docs - - + + ../weblogger-docs/templateguide/generated/roller-template-guide.pdf ${artifact.artifactId}-${artifact.version}-javaee/docs - + diff --git a/weblogger-assembly/src/main/assembly/for-jboss.xml b/weblogger-assembly/src/main/assembly/for-jboss.xml index 960f9a2b47..68c0aaa3f0 100644 --- a/weblogger-assembly/src/main/assembly/for-jboss.xml +++ b/weblogger-assembly/src/main/assembly/for-jboss.xml @@ -18,7 +18,7 @@ --> @@ -29,35 +29,35 @@ false - - + + ../weblogger-war-assembly/target/roller-${artifact.version}-jboss.war ${artifact.artifactId}-${artifact.version}-jboss/webapp - - + + ../README.txt ${artifact.artifactId}-${artifact.version}-jboss - - + + ../NOTICE.txt ${artifact.artifactId}-${artifact.version}-jboss - - + + ../LICENSE.txt ${artifact.artifactId}-${artifact.version}-jboss - - + + ../weblogger-docs/installguide/generated/roller-install-guide.pdf ${artifact.artifactId}-${artifact.version}-jboss/docs - - + + ../weblogger-docs/userguide/generated/roller-user-guide.pdf ${artifact.artifactId}-${artifact.version}-jboss/docs - - + + ../weblogger-docs/templateguide/generated/roller-template-guide.pdf ${artifact.artifactId}-${artifact.version}-jboss/docs - + diff --git a/weblogger-assembly/src/main/assembly/for-tomcat.xml b/weblogger-assembly/src/main/assembly/for-tomcat.xml index fd753c3780..66bdcc5a5c 100644 --- a/weblogger-assembly/src/main/assembly/for-tomcat.xml +++ b/weblogger-assembly/src/main/assembly/for-tomcat.xml @@ -18,7 +18,7 @@ --> @@ -29,35 +29,35 @@ false - - + + ../weblogger-war-assembly/target/roller-${artifact.version}-tomcat.war ${artifact.artifactId}-${artifact.version}-tomcat/webapp - - + + ../README.txt ${artifact.artifactId}-${artifact.version}-tomcat - - + + ../NOTICE.txt ${artifact.artifactId}-${artifact.version}-tomcat - - + + ../LICENSE.txt ${artifact.artifactId}-${artifact.version}-tomcat - - + + ../weblogger-docs/installguide/generated/roller-install-guide.pdf ${artifact.artifactId}-${artifact.version}-tomcat/docs - - + + ../weblogger-docs/userguide/generated/roller-user-guide.pdf ${artifact.artifactId}-${artifact.version}-tomcat/docs - - + + ../weblogger-docs/templateguide/generated/roller-template-guide.pdf ${artifact.artifactId}-${artifact.version}-tomcat/docs - + diff --git a/weblogger-assembly/src/main/assembly/source.xml b/weblogger-assembly/src/main/assembly/source.xml index 36c75e0e8a..2a76ac2c47 100644 --- a/weblogger-assembly/src/main/assembly/source.xml +++ b/weblogger-assembly/src/main/assembly/source.xml @@ -1,13 +1,13 @@ - source diff --git a/weblogger-business/pom.xml b/weblogger-business/pom.xml index 3b124e8fe8..6f5cfdb562 100644 --- a/weblogger-business/pom.xml +++ b/weblogger-business/pom.xml @@ -91,7 +91,7 @@ 1.5.6 runtime --> - + javax.mail mail @@ -232,7 +232,7 @@ once -javaagent:${user.home}/.m2/repository/org/apache/openjpa/openjpa/2.0.1/openjpa-2.0.1.jar - + catalina.base @@ -418,13 +418,13 @@ - + jboss jboss - + java:/RollerDS @@ -435,7 +435,7 @@ !jboss - + jdbc/rollerdb @@ -448,7 +448,7 @@ !javaee - + org.apache.openjpa @@ -486,6 +486,6 @@ - + diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/TestUtils.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/TestUtils.java index e9a9ce5224..d859eccc81 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/TestUtils.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/TestUtils.java @@ -51,48 +51,48 @@ * Utility class for unit test classes. */ public final class TestUtils { - - + + public static void setupWeblogger() throws Exception { - + if(!WebloggerFactory.isBootstrapped()) { // do core services preparation WebloggerStartup.prepare(); - + // do application bootstrapping WebloggerFactory.bootstrap(); - + // always initialize the properties manager and flush WebloggerFactory.getWeblogger().initialize(); } } - - + + public static void shutdownWeblogger() throws Exception { - + // trigger shutdown WebloggerFactory.getWeblogger().shutdown(); } - - + + public static void setupPlanet() throws Exception { - + if(!PlanetFactory.isBootstrapped()) { // do core services preparation PlanetStartup.prepare(); - + // do application bootstrapping String guiceModule = WebloggerConfig.getProperty("planet.aggregator.guice.module"); PlanetProvider provider = new GuicePlanetProvider(guiceModule); PlanetFactory.bootstrap(provider); - + // always initialize the properties manager and flush PlanetFactory.getPlanet().getPropertiesManager().initialize(); PlanetFactory.getPlanet().flush(); } } - - + + /** * Convenience method that simulates the end of a typical session. * @@ -102,20 +102,20 @@ public static void setupPlanet() throws Exception { * @param flush true if you want to flush changes to db before releasing */ public static void endSession(boolean flush) throws Exception { - + if(flush) { WebloggerFactory.getWeblogger().flush(); } - + WebloggerFactory.getWeblogger().release(); } - - + + /** * Convenience method that creates a user and stores it. */ public static User setupUser(String username) throws Exception { - + User testUser = new User(); testUser.setUserName(username); testUser.setPassword("password"); @@ -126,46 +126,46 @@ public static User setupUser(String username) throws Exception { testUser.setTimeZone("America/Los_Angeles"); testUser.setDateCreated(new java.util.Date()); testUser.setEnabled(Boolean.TRUE); - + // store the user UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); mgr.addUser(testUser); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for the user to make sure we return the persisted object User user = mgr.getUserByUserName(username); - + if(user == null) throw new WebloggerException("error inserting new user"); - + return user; } - - + + /** * Convenience method for removing a user. */ public static void teardownUser(String userName) throws Exception { - + // lookup the user UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); User user = mgr.getUserByUserName(userName, null); - + // remove the user mgr.removeUser(user); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method that creates a weblog and stores it. */ public static Weblog setupWeblog(String handle, User creator) throws Exception { - + Weblog testWeblog = new Weblog(); testWeblog.setName("Test Weblog"); testWeblog.setDescription("Test Weblog"); @@ -179,55 +179,55 @@ public static Weblog setupWeblog(String handle, User creator) throws Exception { testWeblog.setTimeZone("America/Los_Angeles"); testWeblog.setDateCreated(new java.util.Date()); testWeblog.setCreatorUserName(creator.getUserName()); - + // add weblog WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); mgr.addWeblog(testWeblog); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for the new weblog and return it Weblog weblog = mgr.getWeblogByHandle(handle); - + if(weblog == null) throw new WebloggerException("error setting up weblog"); - + return weblog; } - - + + /** * Convenience method for removing a weblog. */ public static void teardownWeblog(String id) throws Exception { - + // lookup the weblog WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); Weblog weblog = mgr.getWeblog(id); - + // remove the weblog mgr.removeWeblog(weblog); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for removing a permission. */ public static void teardownPermissions(WeblogPermission perm) throws Exception { - + // remove all permissions - UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); mgr.revokeWeblogPermission(perm.getWeblog(), perm.getUser(), WeblogPermission.ALL_ACTIONS); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a weblog category. */ @@ -235,47 +235,47 @@ public static WeblogCategory setupWeblogCategory(Weblog weblog, String name, WeblogCategory parent) throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogCategory root = mgr.getRootWeblogCategory(weblog); - + WeblogCategory catParent = root; if(parent != null) { catParent = parent; } WeblogCategory testCat = new WeblogCategory(weblog, catParent, name, null, null); mgr.saveWeblogCategory(testCat); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for object WeblogCategory cat = mgr.getWeblogCategory(testCat.getId()); - + if(cat == null) throw new WebloggerException("error setting up weblog category"); - + return cat; } - - + + /** * Convenience method for removing a weblog category. */ public static void teardownWeblogCategory(String id) throws Exception { - + // lookup the cat WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogCategory cat = mgr.getWeblogCategory(id); - + // remove the cat mgr.removeWeblogCategory(cat); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a weblog entry. */ @@ -284,7 +284,7 @@ public static WeblogEntry setupWeblogEntry(String anchor, Weblog weblog, User user) throws Exception { - + WeblogEntry testEntry = new WeblogEntry(); testEntry.setTitle(anchor); testEntry.setLink("testEntryLink"); @@ -296,47 +296,47 @@ public static WeblogEntry setupWeblogEntry(String anchor, testEntry.setWebsite(getManagedWebsite(weblog)); testEntry.setCreatorUserName(getManagedUser(user).getUserName()); testEntry.setCategory(cat); - + // store entry WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.saveWeblogEntry(testEntry); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for object WeblogEntry entry = mgr.getWeblogEntry(testEntry.getId()); - + if(entry == null) throw new WebloggerException("error setting up weblog entry"); - + return entry; } - - + + /** * Convenience method for removing a weblog entry. */ public static void teardownWeblogEntry(String id) throws Exception { - + // lookup the entry WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry entry = mgr.getWeblogEntry(id); - + // remove the entry mgr.removeWeblogEntry(entry); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a comment. */ public static WeblogEntryComment setupComment(String content, WeblogEntry entry) throws Exception { - + WeblogEntryComment testComment = new WeblogEntryComment(); testComment.setName("test"); testComment.setEmail("test"); @@ -346,171 +346,171 @@ public static WeblogEntryComment setupComment(String content, WeblogEntry entry) testComment.setPostTime(new java.sql.Timestamp(new java.util.Date().getTime())); testComment.setWeblogEntry(getManagedWeblogEntry(entry)); testComment.setStatus(WeblogEntryComment.APPROVED); - + // store testComment WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.saveComment(testComment); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for object WeblogEntryComment comment = mgr.getComment(testComment.getId()); - + if(comment == null) throw new WebloggerException("error setting up comment"); - + return comment; } - - + + /** * Convenience method for removing a comment. */ public static void teardownComment(String id) throws Exception { - + // lookup the comment WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntryComment comment = mgr.getComment(id); - + // remove the comment mgr.removeComment(comment); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a ping target. */ - public static PingTarget setupPingTarget(String name, String url) + public static PingTarget setupPingTarget(String name, String url) throws Exception { - + PingTarget testPing = new PingTarget(); testPing.setName("testCommonPing"); testPing.setPingUrl("http://localhost/testCommonPing"); - + // store ping PingTargetManager pingMgr = WebloggerFactory.getWeblogger().getPingTargetManager(); pingMgr.savePingTarget(testPing); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for it PingTarget ping = pingMgr.getPingTarget(testPing.getId()); - + if(ping == null) throw new WebloggerException("error setting up ping target"); - + return ping; } - - + + /** * Convenience method for removing a ping target. */ public static void teardownPingTarget(String id) throws Exception { - + // query for it PingTargetManager pingMgr = WebloggerFactory.getWeblogger().getPingTargetManager(); PingTarget ping = pingMgr.getPingTarget(id); - + // remove the ping pingMgr.removePingTarget(ping); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating an auto ping. */ public static AutoPing setupAutoPing(PingTarget ping, Weblog weblog) throws Exception { - + AutoPingManager mgr = WebloggerFactory.getWeblogger().getAutopingManager(); - + // store auto ping AutoPing autoPing = new AutoPing(null, ping, getManagedWebsite(weblog) ); mgr.saveAutoPing(autoPing); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for it autoPing = mgr.getAutoPing(autoPing.getId()); - + if(autoPing == null) throw new WebloggerException("error setting up auto ping"); - + return autoPing; } - - + + /** * Convenience method for removing an auto ping. */ public static void teardownAutoPing(String id) throws Exception { - + // query for it AutoPingManager mgr = WebloggerFactory.getWeblogger().getAutopingManager(); AutoPing autoPing = mgr.getAutoPing(id); - + // remove the auto ping mgr.removeAutoPing(autoPing); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a hit count. */ public static WeblogHitCount setupHitCount(Weblog weblog, int amount) throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + // store WeblogHitCount testCount = new WeblogHitCount(); testCount.setWeblog(getManagedWebsite(weblog)); testCount.setDailyHits(amount); mgr.saveHitCount(testCount); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for it testCount = mgr.getHitCount(testCount.getId()); - + if(testCount == null) throw new WebloggerException("error setting up hit count"); - + return testCount; } - - + + /** * Convenience method for removing a hit count. */ public static void teardownHitCount(String id) throws Exception { - + // query for it WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogHitCount testCount = mgr.getHitCount(id); - + // remove mgr.removeHitCount(testCount); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method for creating a weblog folder. */ @@ -518,47 +518,47 @@ public static WeblogBookmarkFolder setupFolder(Weblog weblog, String name, WeblogBookmarkFolder parent) throws Exception { - + BookmarkManager mgr = WebloggerFactory.getWeblogger().getBookmarkManager(); WeblogBookmarkFolder root = mgr.getRootFolder(weblog); - + WeblogBookmarkFolder folderParent = root; if(parent != null) { folderParent = parent; } WeblogBookmarkFolder testFolder = new WeblogBookmarkFolder(folderParent, name, null, weblog); mgr.saveFolder(testFolder); - + // flush to db WebloggerFactory.getWeblogger().flush(); - + // query for object WeblogBookmarkFolder cat = mgr.getFolder(testFolder.getId()); - + if(testFolder == null) throw new WebloggerException("error setting up weblog folder"); - + return testFolder; } - - + + /** * Convenience method for removing a weblog folder. */ public static void teardownFolder(String id) throws Exception { - + // lookup the folder BookmarkManager mgr = WebloggerFactory.getWeblogger().getBookmarkManager(); WeblogBookmarkFolder folder = mgr.getFolder(id); - + // remove the cat mgr.removeFolder(folder); - + // flush to db WebloggerFactory.getWeblogger().flush(); } - - + + /** * Convenience method that returns managed copy of given user. */ @@ -566,14 +566,14 @@ public static User getManagedUser(User user) throws WebloggerException { UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); return mgr.getUserByUserName(user.getUserName()); } - + /** * Convenience method that returns managed copy of given website. */ public static Weblog getManagedWebsite(Weblog website) throws WebloggerException { return WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(website.getId()); } - + /** * Convenience method that returns managed copy of given WeblogEntry. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/WebloggerException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/WebloggerException.java index dcfd0fe4b8..043d954d70 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/WebloggerException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/WebloggerException.java @@ -25,13 +25,13 @@ * A base exception class for Roller Weblogger. */ public class WebloggerException extends RollerException { - - + + public WebloggerException() { super(); } - - + + /** * Construct WebloggerException with message string. * @@ -40,8 +40,8 @@ public WebloggerException() { public WebloggerException(String s) { super(s); } - - + + /** * Construct WebloggerException, wrapping existing throwable. * @@ -51,8 +51,8 @@ public WebloggerException(String s) { public WebloggerException(String s, Throwable t) { super(s, t); } - - + + /** * Construct WebloggerException, wrapping existing throwable. * @@ -61,5 +61,5 @@ public WebloggerException(String s, Throwable t) { public WebloggerException(Throwable t) { super(t); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/AbstractURLStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/AbstractURLStrategy.java index 65eb820521..c62f66f925 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/AbstractURLStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/AbstractURLStrategy.java @@ -29,48 +29,48 @@ * which are not likely to change for any alternate url strategies. */ public abstract class AbstractURLStrategy implements URLStrategy { - + public AbstractURLStrategy() {} - - + + /** * Url to login page. */ public String getLoginURL(boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/login-redirect.rol"); - + return url.toString(); } - - + + /** * Url to logout page. */ public String getLogoutURL(boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/logout.rol"); - + return url.toString(); } - - + + /** * Get a url to a UI action in a given namespace, optionally specifying * a weblogHandle parameter if that is needed by the action. @@ -80,137 +80,137 @@ public String getActionURL(String action, String weblogHandle, Map parameters, boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append(namespace); url.append("/").append(action).append(".rol"); - + // put weblog handle parameter, if necessary Map params = new HashMap(); if(weblogHandle != null) { params.put("weblog", weblogHandle); } - + // add custom parameters if they exist if(parameters != null) { params.putAll(parameters); } - + if(!params.isEmpty()) { return url.toString() + URLUtilities.getQueryString(params); } else { return url.toString(); } } - - + + /** * Get a url to add a new weblog entry. */ public String getEntryAddURL(String weblogHandle, boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/entryAdd.rol"); - + Map params = new HashMap(); params.put("weblog", weblogHandle); - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get a url to edit a specific weblog entry. */ public String getEntryEditURL(String weblogHandle, String entryId, boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/entryEdit.rol"); - + Map params = new HashMap(); params.put("weblog", weblogHandle); params.put("bean.id", entryId); - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get a url to weblog config page. */ public String getWeblogConfigURL(String weblogHandle, boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/weblogConfig.rol"); - + Map params = new HashMap(); params.put("weblog", weblogHandle); - + return url.toString() + URLUtilities.getQueryString(params); } - - + + public String getXmlrpcURL(boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-services/xmlrpc"); - + return url.toString(); } - - + + public String getAtomProtocolURL(boolean absolute) { - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-services/app"); - + return url.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BookmarkManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BookmarkManager.java index 66ede17fa3..db839dc9cd 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BookmarkManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BookmarkManager.java @@ -30,31 +30,31 @@ * moving, removing and querying for folders and bookmarks. */ public interface BookmarkManager { - - + + /** - * Save a Folder. - * - * Also saves any bookmarks in the folder. This method should enforce the + * Save a Folder. + * + * Also saves any bookmarks in the folder. This method should enforce the * fact that a weblog cannot have 2 folders with the same path. * * @param folder The folder to be saved. * @throws WebloggerException If there is a problem. */ public void saveFolder(WeblogBookmarkFolder folder) throws WebloggerException; - - + + /** - * Remove a Folder. - * + * Remove a Folder. + * * Also removes any subfolders and bookmarks. * * @param folder The folder to be removed. * @throws WebloggerException If there is a problem. */ public void removeFolder(WeblogBookmarkFolder folder) throws WebloggerException; - - + + /** * Move a folder under another folder. * @@ -65,8 +65,8 @@ public void moveFolder(WeblogBookmarkFolder src, WeblogBookmarkFolder dest ) throws WebloggerException; - - + + /** * Lookup a folder by ID. * @@ -75,9 +75,9 @@ public void moveFolder(WeblogBookmarkFolder src, * @throws WebloggerException If there is a problem. */ public WeblogBookmarkFolder getFolder(String id) throws WebloggerException; - - - /** + + + /** * Get all folders for a weblog. * * @param weblog The weblog we want the folders from. @@ -85,10 +85,10 @@ public void moveFolder(WeblogBookmarkFolder src, * @throws WebloggerException If there is a problem. */ public List getAllFolders(Weblog weblog) throws WebloggerException; - - - /** - * Get root folder for a weblog. + + + /** + * Get root folder for a weblog. * All weblogs should have only 1 root folder. * * @param weblog The weblog we want the root folder from. @@ -96,9 +96,9 @@ public void moveFolder(WeblogBookmarkFolder src, * @throws WebloggerException If there is a problem. */ public WeblogBookmarkFolder getRootFolder(Weblog weblog) throws WebloggerException; - - - /** + + + /** * Get a folder from a weblog based on its path. * * @param weblog The weblog we want the folder from. @@ -108,8 +108,8 @@ public void moveFolder(WeblogBookmarkFolder src, */ public WeblogBookmarkFolder getFolder(Weblog weblog, String path) throws WebloggerException; - - + + /** * Save a Bookmark. * @@ -117,8 +117,8 @@ public WeblogBookmarkFolder getFolder(Weblog weblog, String path) * @throws WebloggerException If there is a problem. */ public void saveBookmark(WeblogBookmark bookmark) throws WebloggerException; - - + + /** * Remove a Bookmark. * @@ -126,9 +126,9 @@ public WeblogBookmarkFolder getFolder(Weblog weblog, String path) * @throws WebloggerException If there is a problem. */ public void removeBookmark(WeblogBookmark bookmark) throws WebloggerException; - - - /** + + + /** * Lookup a Bookmark by ID. * * @param id The id of the bookmark to lookup. @@ -136,9 +136,9 @@ public WeblogBookmarkFolder getFolder(Weblog weblog, String path) * @throws WebloggerException If there is a problem. */ public WeblogBookmark getBookmark(String id) throws WebloggerException; - - - /** + + + /** * Lookup all Bookmarks in a folder, optionally search recursively. * * @param folder The folder to get the bookmarks from. @@ -148,9 +148,9 @@ public WeblogBookmarkFolder getFolder(Weblog weblog, String path) */ public List getBookmarks(WeblogBookmarkFolder folder, boolean recurse) throws WebloggerException; - - - /** + + + /** * Import bookmarks and folders from OPML string into the specified folder. * * @param weblog The weblog to import the OPML into. @@ -159,11 +159,11 @@ public List getBookmarks(WeblogBookmarkFolder folder, boolean recurse) */ public void importBookmarks(Weblog weblog, String folder, String opml) throws WebloggerException; - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BootstrapException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BootstrapException.java index e24a2acda7..5fc8e5da7e 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BootstrapException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/BootstrapException.java @@ -25,13 +25,13 @@ * Exception generated from Weblogger bootstrapping process. */ public class BootstrapException extends WebloggerException { - + public BootstrapException(String msg) { super(msg); } - + public BootstrapException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/DatabaseProvider.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/DatabaseProvider.java index 8c14891f54..42c4436dc2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/DatabaseProvider.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/DatabaseProvider.java @@ -35,22 +35,22 @@ /** * Encapsulates Roller database configuration via JDBC properties or JNDI. - * - *

      To keep the logs from filling up with DB connection errors, will only + * + *

      To keep the logs from filling up with DB connection errors, will only * attempt to connect once.

      - * + * *

      Keeps startup exception and log so we can present useful debugging * information to whoever is installing Roller.

      - * - * + * + * *

      Reads configuration properties from WebloggerConfig:

      *
        * # Specify database configuration type of 'jndi' or 'jdbc'
        * database.configurationType=jndi
      - * 
      + *
        * # For database configuration type 'jndi',this will be used
        * database.jndi.name=jdbc/rollerdb
      - * 
      + *
        * # For database configuration type of 'jdbc', you MUST override these
        * database.jdbc.driverClass=
        * database.jdbc.connectionURL=
      @@ -59,31 +59,31 @@
        * 
      */ public class DatabaseProvider { - + private static Log log = LogFactory.getLog(DatabaseProvider.class); public enum ConfigurationType {JNDI_NAME, JDBC_PROPERTIES;} private ConfigurationType type = ConfigurationType.JNDI_NAME; private List startupLog = new ArrayList(); - - private DataSource dataSource = null; - private String jndiName = null; - + + private DataSource dataSource = null; + private String jndiName = null; + private String jdbcDriverClass = null; private String jdbcConnectionURL = null; private String jdbcPassword = null; private String jdbcUsername = null; private Properties props = null; - - + + /** * Reads configuraiton, loads driver or locates data-source and attempts * to get test connecton so that we can fail early. - */ + */ public DatabaseProvider() throws StartupException { - - String connectionTypeString = - WebloggerConfig.getProperty("database.configurationType"); + + String connectionTypeString = + WebloggerConfig.getProperty("database.configurationType"); if ("jdbc".equals(connectionTypeString)) { type = ConfigurationType.JDBC_PROPERTIES; } @@ -92,7 +92,7 @@ public DatabaseProvider() throws StartupException { jdbcConnectionURL = WebloggerConfig.getProperty("database.jdbc.connectionURL"); jdbcUsername = WebloggerConfig.getProperty("database.jdbc.username"); jdbcPassword = WebloggerConfig.getProperty("database.jdbc.password"); - + successMessage("SUCCESS: Got parameters. Using configuration type " + type); // If we're doing JDBC then attempt to load JDBC driver class @@ -104,63 +104,63 @@ public DatabaseProvider() throws StartupException { try { Class.forName(getJdbcDriverClass()); } catch (ClassNotFoundException ex) { - String errorMsg = + String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass()+ "]. " +"Likely problem: JDBC driver jar missing from server classpath."; errorMessage(errorMsg); throw new StartupException(errorMsg, ex, startupLog); } successMessage("SUCCESS: loaded JDBC driver class [" +getJdbcDriverClass()+ "]"); - + if (getJdbcUsername() != null || getJdbcPassword() != null) { props = new Properties(); if (getJdbcUsername() != null) props.put("user", getJdbcUsername()); if (getJdbcPassword() != null) props.put("password", getJdbcPassword()); } - + // Else attempt to locate JNDI datasource - } else { + } else { String name = (getJndiName().indexOf(":") == -1 ? "java:comp/env/" + getJndiName() : getJndiName()); successMessage("-- Using JNDI datasource name: " + name); try { InitialContext ic = new InitialContext(); dataSource = (DataSource)ic.lookup(name); } catch (NamingException ex) { - String errorMsg = + String errorMsg = "ERROR: cannot locate JNDI DataSource [" +name+ "]. " +"Likely problem: no DataSource or datasource is misconfigured."; errorMessage(errorMsg); throw new StartupException(errorMsg, ex, startupLog); - } + } successMessage("SUCCESS: located JNDI DataSource [" +name+ "]"); } - + // So far so good. Now, can we get a connection? - try { + try { Connection testcon = getConnection(); testcon.close(); } catch (Throwable t) { - String errorMsg = + String errorMsg = "ERROR: unable to obtain database connection. " +"Likely problem: bad connection parameters or database unavailable."; errorMessage(errorMsg); throw new StartupException(errorMsg, t, startupLog); } } - - + + private void successMessage(String msg) { startupLog.add(msg); log.info(msg); } - + private void errorMessage(String msg) { startupLog.add(msg); log.error(msg); } - - /** + + /** * List of success and error messages when class was first instantiated. **/ public List getStartupLog() { @@ -168,7 +168,7 @@ public List getStartupLog() { } /** - * Get database connection from data-source or driver manager, depending + * Get database connection from data-source or driver manager, depending * on which is configured. */ public Connection getConnection() throws SQLException { @@ -177,7 +177,7 @@ public Connection getConnection() throws SQLException { } else { return dataSource.getConnection(); } - } + } public ConfigurationType getType() { return type; @@ -202,7 +202,7 @@ public String getJdbcPassword() { public String getJdbcUsername() { return jdbcUsername; } - + public String getFullJndiName() { if (null != jndiName && jndiName.startsWith("java:")) { return jndiName; diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManager.java index 577fdc0337..0f09870513 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManager.java @@ -30,10 +30,10 @@ public interface FileContentManager { /** * Get a reference to the content of a specific file in a weblog's uploads area. - * + * * This method always returns a valid file content object or will throw an exception * if the specificed path doesn't exist, or can't be read. - * + * * @param weblog The weblog we are working on. * @param fileId file identifier from database. * @@ -45,7 +45,7 @@ public FileContent getFileContent(Weblog weblog, String fileId) /** * Save a file's content to weblog's uploads area. - * + * * @param weblog The weblog we are working on. * @param fileId file identifier from database. * @param is InputStream to read the file from. @@ -61,7 +61,7 @@ public void saveFileContent(Weblog weblog, /** * Delete file content from weblog's uploads area. - * + * * @param weblog The weblog we are working on. * @param fileId file identifier from database. * @@ -83,7 +83,7 @@ public void deleteFile(Weblog weblog, String fileId) public void deleteAllFiles(Weblog weblog) throws FileIOException; - /** + /** * Is the given weblog over the file-upload quota limit? * * @param weblog The weblog we are working on. @@ -93,13 +93,13 @@ public void deleteAllFiles(Weblog weblog) /** * Determine if file can be saved given current WebloggerConfig settings. - * + * * @param weblog The weblog we are working on. * @param fileName name of the file to be saved * @param contentType content type of the file * @param size size of the file in bytes. * @param messages output parameter for adding messages. - * @return true if the file can be saved, false otherwise. + * @return true if the file can be saved, false otherwise. */ public boolean canSave(Weblog weblog, String fileName, diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManagerImpl.java index def228384b..fb70c55440 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/FileContentManagerImpl.java @@ -36,35 +36,35 @@ /** - * Manages contents of the file uploaded to Roller weblogs. - * + * Manages contents of the file uploaded to Roller weblogs. + * * This base implementation writes file content to a file system. */ public class FileContentManagerImpl implements FileContentManager { - + private static Log log = LogFactory.getLog(FileContentManagerImpl.class); - + private String storage_dir = null; /** * Create file content manager. */ public FileContentManagerImpl() { - + String storagedir = WebloggerConfig.getProperty("mediafiles.storage.dir"); - + // Note: System property expansion is now handled by WebloggerConfig. - + if (storagedir == null || storagedir.trim().length() < 1) storagedir = System.getProperty("user.home") + File.separator+"roller_data"+File.separator+"mediafiles"; - + if (! storagedir.endsWith(File.separator)) storagedir += File.separator; - + this.storage_dir = storagedir.replace('/',File.separatorChar); } - + public void initialize() { } @@ -74,37 +74,37 @@ public void initialize() { /** * @see org.apache.roller.weblogger.model.FileContentManager#getFileContent(weblog, java.lang.String) */ - public FileContent getFileContent(Weblog weblog, String fileId) + public FileContent getFileContent(Weblog weblog, String fileId) throws FileNotFoundException, FilePathException { - + // get a reference to the file, checks that file exists & is readable File resourceFile = this.getRealFile(weblog, fileId); - + // make sure file is not a directory if(resourceFile.isDirectory()) { throw new FilePathException("Invalid file id ["+fileId+"], "+ "path is a directory."); } - + // everything looks good, return resource return new FileContent(weblog, fileId, resourceFile); } - + /** - * @see org.apache.roller.weblogger.model.FileContentManager#saveFileContent(weblog, java.lang.String, + * @see org.apache.roller.weblogger.model.FileContentManager#saveFileContent(weblog, java.lang.String, * java.lang.String, java.io.InputStream, boolean) */ - public void saveFileContent(Weblog weblog, - String fileId, + public void saveFileContent(Weblog weblog, + String fileId, InputStream is) throws FileNotFoundException, FilePathException, FileIOException { - + // make sure uploads area exists for this weblog File dirPath = this.getRealFile(weblog, null); - + // create File that we are about to save File saveFile = new File(dirPath.getAbsolutePath() + File.separator + fileId); - + byte[] buffer = new byte[8192]; int bytesRead = 0; OutputStream bos = null; @@ -112,7 +112,7 @@ public void saveFileContent(Weblog weblog, bos = new FileOutputStream(saveFile); while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); - } + } log.debug("The file has been written to ["+saveFile.getAbsolutePath()+"]"); } catch (Exception e) { throw new FileIOException("ERROR uploading file", e); @@ -122,48 +122,48 @@ public void saveFileContent(Weblog weblog, bos.close(); } catch (Exception ignored) {} } - - + + } - - + + /** * @see org.apache.roller.weblogger.model.FileContentManager#deleteFile(weblog, java.lang.String) */ - public void deleteFile(Weblog weblog, String fileId) + public void deleteFile(Weblog weblog, String fileId) throws FileNotFoundException, FilePathException, FileIOException { - + // get path to delete file, checks that path exists and is readable File delFile = this.getRealFile(weblog, fileId); - + if (!delFile.delete()) { log.warn("Delete appears to have failed for ["+fileId+"]"); } } - + /** * @inheritDoc */ public void deleteAllFiles(Weblog weblog) throws FileIOException { // TODO: Implement } - + /** * @see org.apache.roller.weblogger.model.FileContentManager#overQuota(weblog) */ public boolean overQuota(Weblog weblog) { - + String maxDir = WebloggerRuntimeConfig.getProperty("uploads.dir.maxsize"); String maxFile = WebloggerRuntimeConfig.getProperty("uploads.file.maxsize"); BigDecimal maxDirSize = new BigDecimal(maxDir); // in megabytes BigDecimal maxFileSize = new BigDecimal(maxFile); // in megabytes - + long maxDirBytes = (long)(1024000 * maxDirSize.doubleValue()); - + try { File storageDir = this.getRealFile(weblog, null); long weblogDirSize = this.getDirSize(storageDir, true); - + return weblogDirSize > maxDirBytes; } catch (Exception ex) { // shouldn't ever happen, this means user's uploads dir is bad @@ -171,12 +171,12 @@ public boolean overQuota(Weblog weblog) { throw new RuntimeException(ex); } } - - + + public void release() { } - - + + /** * @see org.apache.roller.weblogger.model.FileContentManager#canSave( * weblog, java.lang.String, java.lang.String, long, messages) @@ -184,15 +184,15 @@ public void release() { public boolean canSave(Weblog weblog, String fileName, String contentType, - long size, + long size, RollerMessages messages) { - + // first check, is uploading enabled? if(!WebloggerRuntimeConfig.getBooleanProperty("uploads.enabled")) { messages.addError("error.upload.disabled"); return false; } - + // second check, does upload exceed max size for file? BigDecimal maxFileMB = new BigDecimal( WebloggerRuntimeConfig.getProperty("uploads.file.maxsize")); @@ -204,7 +204,7 @@ public boolean canSave(Weblog weblog, messages.addError("error.upload.filemax", args); return false; } - + // third check, does file cause weblog to exceed quota? BigDecimal maxDirMB = new BigDecimal( WebloggerRuntimeConfig.getProperty("uploads.dir.maxsize")); @@ -221,7 +221,7 @@ public boolean canSave(Weblog weblog, // rethrow as a runtime exception throw new RuntimeException(ex); } - + // fourth check, is upload type allowed? String allows = WebloggerRuntimeConfig.getProperty("uploads.types.allowed"); String forbids = WebloggerRuntimeConfig.getProperty("uploads.types.forbid"); @@ -232,18 +232,18 @@ public boolean canSave(Weblog weblog, messages.addError("error.upload.forbiddenFile", args); return false; } - + return true; } - - + + /** * Get the size in bytes of given directory. * * Optionally works recursively counting subdirectories if they exist. */ private long getDirSize(File dir, boolean recurse) { - + long size = 0; if(dir.exists() && dir.isDirectory() && dir.canRead()) { File[] files = dir.listFiles(); @@ -258,41 +258,41 @@ private long getDirSize(File dir, boolean recurse) { } size += dirSize; } - + return size; } - - + + /** * Return true if file is allowed to be uplaoded given specified allowed and * forbidden file types. */ private boolean checkFileType(String[] allowFiles, String[] forbidFiles, String fileName, String contentType) { - + // TODO: Atom Publushing Protocol figure out how to handle file // allow/forbid using contentType. // TEMPORARY SOLUTION: In the allow/forbid lists we will continue to // allow user to specify file extensions (e.g. gif, png, jpeg) but will // now also allow them to specify content-type rules (e.g. */*, image/*, // text/xml, etc.). - + // if content type is invalid, reject file if (contentType == null || contentType.indexOf("/") == -1) { return false; } - + // default to false boolean allowFile = false; - + // if this person hasn't listed any allows, then assume they want // to allow *all* filetypes, except those listed under forbid if(allowFiles == null || allowFiles.length < 1) { allowFile = true; } - + // First check against what is ALLOWED - + // check file against allowed file extensions if (allowFiles != null && allowFiles.length > 0) { for (int y=0; y 0) { for (int y=0; y 0) { for (int x=0; x 0) { for (int x=0; x fetchRecentPublicMediaFiles(int length) throws WebloggerException; - + /** * Remove all media files associated with a weblog. * @param website diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/MultiWeblogURLStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/MultiWeblogURLStrategy.java index 16c8f63f4c..47e49c7000 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/MultiWeblogURLStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/MultiWeblogURLStrategy.java @@ -32,18 +32,18 @@ * A Weblogger URLStrategy which builds urls for a multi-weblog environment. */ public class MultiWeblogURLStrategy extends AbstractURLStrategy { - + public MultiWeblogURLStrategy() {} - - + + /** * @inheritDoc */ public URLStrategy getPreviewURLStrategy(String previewTheme) { return new PreviewURLStrategy(previewTheme); } - - + + /** * Get root url for a given weblog. Optionally for a certain locale. */ @@ -72,8 +72,8 @@ public String getWeblogURL(Weblog weblog, return url.toString(); } - - + + /** * Get url for a single weblog entry on a given weblog. */ @@ -81,20 +81,20 @@ public String getWeblogEntryURL(Weblog weblog, String locale, String entryAnchor, boolean absolute) { - + if(weblog == null || entryAnchor == null) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, locale, absolute)); url.append("entry/").append(URLUtilities.encode(entryAnchor)); - + return url.toString(); } - - + + /** * Get url for a single weblog media file on a given weblog. */ @@ -102,17 +102,17 @@ public String getMediaFileURL( Weblog weblog, String fileAnchor, boolean absolute) { - + if(fileAnchor == null) { return null; } - + StringBuilder url = new StringBuilder(); url.append(getWeblogURL(weblog, null, absolute)); url.append("mediaresource"); url.append("/"); url.append(URLUtilities.encode(fileAnchor)); - + return url.toString(); } @@ -123,11 +123,11 @@ public String getMediaFileURL( public String getMediaFileThumbnailURL(Weblog weblog, String fileAnchor, boolean absolute) { - + return getMediaFileURL(weblog, fileAnchor, absolute) + "?t=true"; } - + /** * Get url for a single weblog entry comments on a given weblog. */ @@ -135,11 +135,11 @@ public String getWeblogCommentsURL(Weblog weblog, String locale, String entryAnchor, boolean absolute) { - + return getWeblogEntryURL(weblog, locale, entryAnchor, absolute)+"#comments"; } - - + + /** * Get url for a single weblog entry comment on a given weblog. */ @@ -148,11 +148,11 @@ public String getWeblogCommentURL(Weblog weblog, String entryAnchor, String timeStamp, boolean absolute) { - + return getWeblogEntryURL(weblog, locale, entryAnchor, absolute)+"#comment-"+timeStamp; } - - + + /** * Get url for a collection of entries on a given weblog. */ @@ -163,29 +163,29 @@ public String getWeblogCollectionURL(Weblog weblog, List tags, int pageNum, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuilder pathinfo = new StringBuilder(); Map params = new HashMap(); - + pathinfo.append(getWeblogURL(weblog, locale, absolute)); - + String cat = null; if(category != null && "/".equals(category)) { cat = null; } else if(category != null && category.startsWith("/")) { cat = category.substring(1); } - + if(cat != null && dateString == null) { pathinfo.append("category/").append(URLUtilities.encodePath(cat)); - + } else if(dateString != null && cat == null) { - pathinfo.append("date/").append(dateString); - + pathinfo.append("date/").append(dateString); + } else if(tags != null && tags.size() > 0) { pathinfo.append("tags/").append(URLUtilities.getEncodedTagsString(tags)); } else { @@ -196,11 +196,11 @@ public String getWeblogCollectionURL(Weblog weblog, if(pageNum > 0) { params.put("page", Integer.toString(pageNum)); } - + return pathinfo.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get url for a custom page on a given weblog. */ @@ -213,19 +213,19 @@ public String getWeblogPageURL(Weblog weblog, List tags, int pageNum, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuilder pathinfo = new StringBuilder(); Map params = new HashMap(); - + pathinfo.append(getWeblogURL(weblog, locale, absolute)); - + if(pageLink != null) { pathinfo.append("page/").append(pageLink); - + // for custom pages we only allow query params if(dateString != null) { params.put("date", dateString); @@ -243,11 +243,11 @@ public String getWeblogPageURL(Weblog weblog, // if there is no page link then this is just a typical collection url return getWeblogCollectionURL(weblog, locale, category, dateString, tags, pageNum, absolute); } - + return pathinfo.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get url for a feed on a given weblog. */ @@ -260,16 +260,16 @@ public String getWeblogFeedURL(Weblog weblog, List tags, boolean excerpts, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, locale, absolute)); url.append("feed/").append(type).append("/").append(format); - + Map params = new HashMap(); if(category != null && category.trim().length() > 0) { params.put("cat", URLUtilities.encode(category)); @@ -283,11 +283,11 @@ public String getWeblogFeedURL(Weblog weblog, if(excerpts) { params.put("excerpts", "true"); } - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get url to search endpoint on a given weblog. */ @@ -297,20 +297,20 @@ public String getWeblogSearchURL(Weblog weblog, String category, int pageNum, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, locale, absolute)); url.append("search"); - + Map params = new HashMap(); if(query != null) { params.put("q", URLUtilities.encode(query)); - + // other stuff only makes sense if there is a query if(category != null) { params.put("cat", URLUtilities.encode(category)); @@ -319,116 +319,116 @@ public String getWeblogSearchURL(Weblog weblog, params.put("page", Integer.toString(pageNum)); } } - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get url to a resource on a given weblog. */ public String getWeblogResourceURL(Weblog weblog, String filePath, boolean absolute) { - + if(weblog == null || StringUtils.isEmpty(filePath)) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, null, absolute)); url.append("resource/"); - + if(filePath.startsWith("/")) { url.append(URLUtilities.encodePath(filePath.substring(1))); } else { url.append(URLUtilities.encodePath(filePath)); } - + return url.toString(); } - - + + /** * Get url to rsd file on a given weblog. */ public String getWeblogRsdURL(Weblog weblog, boolean absolute) { - + if(weblog == null) { return null; } - + return getWeblogURL(weblog, null, absolute)+"rsd"; } - - + + /** * Get url to JSON tags service url, optionally for a given weblog. */ public String getWeblogTagsJsonURL(Weblog weblog, boolean absolute, int pageNum) { - + StringBuilder url = new StringBuilder(); - + if (absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + // json tags service base url.append("/roller-services/tagdata/"); - + // is this for a specific weblog or site-wide? if (weblog != null) { url.append("/weblog/"); url.append(weblog.getHandle()); url.append("/"); } - + if (pageNum > 0) { url.append("?page=").append(pageNum); } - + return url.toString(); } - + public String getWeblogSearchFeedURLTemplate(Weblog weblog) { if(weblog == null) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, null, true)); url.append("feed/entries/atom"); - + Map params = new HashMap(); params.put("q", "{searchTerms}"); params.put("page", "{startPage}"); - + return url.toString() + URLUtilities.getQueryString(params); } - + public String getWeblogSearchPageURLTemplate(Weblog weblog) { if(weblog == null) { return null; } - + StringBuilder url = new StringBuilder(); - + url.append(getWeblogURL(weblog, null, true)); url.append("search"); - + Map params = new HashMap(); params.put("q", "{searchTerms}"); params.put("page", "{startPage}"); - + return url.toString() + URLUtilities.getQueryString(params); } @@ -453,7 +453,7 @@ public String getOAuthAuthorizationURL() { public String getOAuthAccessTokenURL() { return WebloggerRuntimeConfig.getAbsoluteContextURL() + "/roller-services/oauth/accessToken"; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java index eb71b4f427..38469e6d34 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java @@ -88,23 +88,23 @@ public OAuthAccessor getAccessor(OAuthMessage requestMessage) throws IOException, OAuthProblemException; /** - * Set the access token + * Set the access token */ public void markAsAuthorized(OAuthAccessor accessor, String userId) - throws OAuthException; + throws OAuthException; /** * Generate a fresh request token and secret for a consumer. - * + * * @throws OAuthException */ public void generateRequestToken( OAuthAccessor accessor) throws OAuthException; - + /** * Generate a fresh request token and secret for a consumer. - * + * * @throws OAuthException */ public void generateAccessToken(OAuthAccessor accessor) diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PreviewURLStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PreviewURLStrategy.java index ecca3f9651..82d9ac6703 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PreviewURLStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PreviewURLStrategy.java @@ -31,51 +31,51 @@ * A URLStrategy used by the preview rendering system. */ public class PreviewURLStrategy extends MultiWeblogURLStrategy { - + private final String previewTheme; - - + + public PreviewURLStrategy(String theme) { previewTheme = theme; } - - + + /** - * Get root url for a given *preview* weblog. + * Get root url for a given *preview* weblog. * Optionally for a certain locale. */ @Override public String getWeblogURL(Weblog weblog, String locale, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/preview/").append(weblog.getHandle()).append("/"); - + if(locale != null) { url.append(locale).append("/"); } - + Map params = new HashMap(); if(previewTheme != null) { params.put("theme", URLUtilities.encode(previewTheme)); } - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** - * Get url for a given *preview* weblog entry. + * Get url for a given *preview* weblog entry. * Optionally for a certain locale. */ @Override @@ -83,25 +83,25 @@ public String getWeblogEntryURL(Weblog weblog, String locale, String previewAnchor, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/preview/").append(weblog.getHandle()).append("/"); - + if(locale != null) { url.append(locale).append("/"); } - + Map params = new HashMap(); if(previewTheme != null) { params.put("theme", URLUtilities.encode(previewTheme)); @@ -109,11 +109,11 @@ public String getWeblogEntryURL(Weblog weblog, if(previewAnchor != null) { params.put("previewEntry", URLUtilities.encode(previewAnchor)); } - + return url.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get url for a collection of entries on a given weblog. */ @@ -124,22 +124,22 @@ public String getWeblogCollectionURL(Weblog weblog, List tags, int pageNum, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuffer pathinfo = new StringBuffer(); Map params = new HashMap(); - + if(absolute) { pathinfo.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { pathinfo.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + pathinfo.append("/roller-ui/authoring/preview/").append(weblog.getHandle()).append("/"); - + if(locale != null) { pathinfo.append(locale).append("/"); } @@ -150,13 +150,13 @@ public String getWeblogCollectionURL(Weblog weblog, } else if(category != null && category.startsWith("/")) { cat = category.substring(1); } - + if(cat != null && dateString == null) { pathinfo.append("category/").append(URLUtilities.encodePath(cat)); - + } else if(dateString != null && cat == null) { - pathinfo.append("date/").append(dateString); - + pathinfo.append("date/").append(dateString); + } else if(tags != null && tags.size() > 0) { pathinfo.append("tags/").append(URLUtilities.getEncodedTagsString(tags)); } else { @@ -167,14 +167,14 @@ public String getWeblogCollectionURL(Weblog weblog, if(pageNum > 0) { params.put("page", Integer.toString(pageNum)); } - + if(previewTheme != null) { params.put("theme", URLUtilities.encode(previewTheme)); } return pathinfo.toString() + URLUtilities.getQueryString(params); } - + /** * Get url for a custom page on a given weblog. @@ -189,33 +189,33 @@ public String getWeblogPageURL(Weblog weblog, List tags, int pageNum, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuffer pathinfo = new StringBuffer(); Map params = new HashMap(); - + if(absolute) { pathinfo.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { pathinfo.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + pathinfo.append("/roller-ui/authoring/preview/").append(weblog.getHandle()).append("/"); - + if(locale != null) { pathinfo.append(locale).append("/"); } - + if(previewTheme != null) { params.put("theme", URLUtilities.encode(previewTheme)); } - + if(pageLink != null) { pathinfo.append("page/").append(pageLink); - + // for custom pages we only allow query params if(dateString != null) { params.put("date", dateString); @@ -233,43 +233,43 @@ public String getWeblogPageURL(Weblog weblog, // if there is no page link then this is just a typical collection url return getWeblogCollectionURL(weblog, locale, category, dateString, tags, pageNum, absolute); } - + return pathinfo.toString() + URLUtilities.getQueryString(params); } - - + + /** * Get a url to a *preview* resource on a given weblog. */ @Override public String getWeblogResourceURL(Weblog weblog, String filePath, boolean absolute) { - + if(weblog == null) { return null; } - + StringBuffer url = new StringBuffer(); - + if(absolute) { url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); } else { url.append(WebloggerRuntimeConfig.getRelativeContextURL()); } - + url.append("/roller-ui/authoring/previewresource/").append(weblog.getHandle()).append("/"); - + if(filePath.startsWith("/")) { url.append(filePath.substring(1)); } else { url.append(filePath); } - + Map params = new HashMap(); if(previewTheme != null && !WeblogTheme.CUSTOM.equals(previewTheme)) { params.put("theme", URLUtilities.encode(previewTheme)); } - + return url.toString() + URLUtilities.getQueryString(params); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PropertiesManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PropertiesManager.java index 5cf79e3741..a6874c5f56 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PropertiesManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/PropertiesManager.java @@ -27,42 +27,42 @@ * Manages global properties for Roller. */ public interface PropertiesManager { - + /** * Initialize the properties manager. * * @throws InitializationException If there is a problem during initialization. */ public void initialize() throws InitializationException; - - + + /** * Release all resources associated with Roller session. */ public void release(); - - + + /** * Save a single property */ public void saveProperty(RuntimeConfigProperty property) throws WebloggerException; - - + + /** * Save a list of properties */ public void saveProperties(Map properties) throws WebloggerException; - - + + /** * Retrieve a single property by name */ public RuntimeConfigProperty getProperty(String name) throws WebloggerException; - - + + /** * Retrieve a list of all properties */ public Map getProperties() throws WebloggerException; - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/URLStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/URLStrategy.java index 50273437f3..1cb9921432 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/URLStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/URLStrategy.java @@ -30,26 +30,26 @@ * all of the public urls used by Roller Planet. */ public interface URLStrategy { - + /** * Get a version of this url strategy meant for use in previewing and set * it to preview a given theme. */ public URLStrategy getPreviewURLStrategy(String previewTheme); - - + + /** * Url to login page. */ public String getLoginURL(boolean absolute); - - + + /** * Url to logout page. */ public String getLogoutURL(boolean absolute); - - + + /** * Get a url to a UI action in a given namespace, optionally specifying * a weblogHandle parameter if that is needed by the action. @@ -59,68 +59,68 @@ public String getActionURL(String action, String weblogHandle, Map parameters, boolean absolute); - - + + /** * Get a url to add a new weblog entry. */ public String getEntryAddURL(String weblogHandle, boolean absolute); - - + + /** * Get a url to edit a specific weblog entry. */ public String getEntryEditURL(String weblogHandle, String entryId, boolean absolute); - - + + /** * Get a url to weblog config page. */ public String getWeblogConfigURL(String weblogHandle, boolean absolute); - - + + /** * URL for OpenSearch descriptor file for site. */ public String getOpenSearchSiteURL(); - + /** * URL for OpenSearch descriptor file for weblog. */ public String getOpenSearchWeblogURL(String weblogHandle); - + /** * Get OpenSearch compatible search URL template for weblog search feed. */ public String getWeblogSearchFeedURLTemplate(Weblog weblog); - + /** * Get OpenSearch compatible search URL template for weblog search page. */ public String getWeblogSearchPageURLTemplate(Weblog weblog); - + public String getXmlrpcURL(boolean absolute); - - + + public String getAtomProtocolURL(boolean absolute); - - + + /** * Get root url for a given weblog. Optionally for a certain locale. */ public String getWeblogURL(Weblog weblog, String locale, boolean absolute); - - + + /** * Get url for a single weblog entry on a given weblog. */ @@ -128,8 +128,8 @@ public String getWeblogEntryURL(Weblog weblog, String locale, String entryAnchor, boolean absolute); - - + + /** * Get url for a single weblog entry comments on a given weblog. */ @@ -137,8 +137,8 @@ public String getWeblogCommentsURL(Weblog weblog, String locale, String entryAnchor, boolean absolute); - - + + /** * Get url for a single weblog entry comment on a given weblog. */ @@ -147,8 +147,8 @@ public String getWeblogCommentURL(Weblog weblog, String entryAnchor, String timeStamp, boolean absolute); - - + + /** * Get url for a single mediafile on a given weblog. */ @@ -172,8 +172,8 @@ public String getWeblogCollectionURL(Weblog weblog, List tags, int pageNum, boolean absolute); - - + + /** * Get url for a custom page on a given weblog. */ @@ -186,8 +186,8 @@ public String getWeblogPageURL(Weblog weblog, List tags, int pageNum, boolean absolute); - - + + /** * Get url for a feed on a given weblog. */ @@ -200,8 +200,8 @@ public String getWeblogFeedURL(Weblog weblog, List tags, boolean excerpts, boolean absolute); - - + + /** * Get url to search endpoint on a given weblog. */ @@ -211,22 +211,22 @@ public String getWeblogSearchURL(Weblog weblog, String category, int pageNum, boolean absolute); - - + + /** * Get url to a resource on a given weblog. */ public String getWeblogResourceURL(Weblog weblog, String filePath, boolean absolute); - - + + /** * Get url to rsd file on a given weblog. */ public String getWeblogRsdURL(Weblog weblog, boolean absolute); - - + + /** * Get url to JSON tags service url, optionally for a given weblog. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/UserManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/UserManager.java index cd9342486d..67a7825da1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/UserManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/UserManager.java @@ -33,12 +33,12 @@ * Interface to user, role and permissions management. */ public interface UserManager { - - //--------------------------------------------------------------- user CRUD - + + //--------------------------------------------------------------- user CRUD + /** * Add a new user. - * + * * This method is used to provide supplemental data to new user accounts, * such as adding the proper roles for the user. This method should see if * the new user is the first user and give that user the admin role if so. @@ -47,8 +47,8 @@ public interface UserManager { * @throws WebloggerException If there is a problem. */ public void addUser(User newUser) throws WebloggerException; - - + + /** * Save a user. * @@ -56,8 +56,8 @@ public interface UserManager { * @throws WebloggerException If there is a problem. */ public void saveUser(User user) throws WebloggerException; - - + + /** * Remove a user. * @@ -65,57 +65,57 @@ public interface UserManager { * @throws WebloggerException If there is a problem. */ public void removeUser(User user) throws WebloggerException; - - + + /** * Get count of enabled users - */ - public long getUserCount() throws WebloggerException; - - + */ + public long getUserCount() throws WebloggerException; + + /** * get a user by activation code * @param activationCode * @return * @throws WebloggerException */ - public User getUserByActivationCode(String activationCode) + public User getUserByActivationCode(String activationCode) throws WebloggerException; - - + + //------------------------------------------------------------ user queries - - + + /** * Lookup a user by UserName. - * + * * This lookup is restricted to 'enabled' users by default. So this method * should return null if the user is found but is not enabled. - * + * * @param userName User Name of user to lookup. * @return UsUserhe user, or null if not found or is disabled. * @throws WebloggerException If there is a problem. */ public User getUserByUserName(String userName) throws WebloggerException; - + /** * Lookup a user by UserName with the given enabled status. - * + * * @param userName User Name of user to lookup. * @return The user, or null if not found or doesn't match the proper enabled status. * @throws WebloggerException If there is a problem. */ public User getUserByUserName(String userName, Boolean enabled) throws WebloggerException; - + /** * Lookup a group of users. - * + * * The lookup may be constrained to users with a certain enabled status, * to users created within a certain date range, and the results can be * confined to a certain offset & length for paging abilities. - * + * * @param weblog Confine results to users with permission to a certain weblog. * @param enabled True for enabled only, False for disabled only (or null for all) * @param startDate Restrict to those created after startDate (or null for all) @@ -131,8 +131,8 @@ public List getUsers( Date endDate, int offset, int length) throws WebloggerException; - - + + /** * Lookup users whose usernames or email addresses start with a string. * @@ -144,39 +144,39 @@ public List getUsers( */ public List getUsersStartingWith(String startsWith, Boolean enabled, int offset, int length) throws WebloggerException; - - + + /** * Get map with 26 entries, one for each letter A-Z and * containing integers reflecting the number of users whose * names start with each letter. */ public Map getUserNameLetterMap() throws WebloggerException; - - - /** - * Get collection of users whose names begin with specified letter + + + /** + * Get collection of users whose names begin with specified letter */ - public List getUsersByLetter(char letter, int offset, int length) + public List getUsersByLetter(char letter, int offset, int length) throws WebloggerException; - - + + //----------------------------------------------------- user attribute CRUD - + /** * Lookup a user by User attribute - * + * * @param name attribute name * @param value sttribute value * @return UsUserhe user, or null if not found or is disabled. * @throws WebloggerException If there is a problem */ public User getUserByAttribute(String name, String value) throws WebloggerException; - + /** * Lookup a user by User attribute - * + * * @param name Attribute name * @param value Attribute value * @param enabled True if only enable user should be returned @@ -184,8 +184,8 @@ public List getUsersByLetter(char letter, int offset, int length) * @throws WebloggerException If there is a problem */ public User getUserByAttribute(String name, String value, Boolean enabled) throws WebloggerException; - - + + /** * Get user atribute value * @param user User @@ -193,37 +193,37 @@ public List getUsersByLetter(char letter, int offset, int length) * @return List of user attributes */ public UserAttribute getUserAttribute(String userName, String attribute) throws WebloggerException; - - + + /** * Set user atribute value * @param user User - * @param attribute Atribute name + * @param attribute Atribute name * @param value Atribute value * @throws org.apache.roller.weblogger.WebloggerException */ public void setUserAttribute(String userName, String attribute, String value) throws WebloggerException; - - + + /** - * Get attribributes for a user. + * Get attribributes for a user. * @param userName Username that uniquely idenifies user. * @return List of attributes. * @throws org.apache.roller.weblogger.WebloggerException */ public List getUserAttributes(String userName) throws WebloggerException; - - + + //-------------------------------------------------------- permissions CRUD - + /** * Return true if user has permission specified. */ - public boolean checkPermission(RollerPermission perm, User user) + public boolean checkPermission(RollerPermission perm, User user) throws WebloggerException; - - + + /** * Grant to user specific actions in a weblog. * (will create new permission record if none already exists) @@ -234,7 +234,7 @@ public boolean checkPermission(RollerPermission perm, User user) public void grantWeblogPermission(Weblog weblog, User user, List actions) throws WebloggerException; - + /** * Grant to user specific actions in a weblog, but pending confirmation. * (will create new permission record if none already exists) @@ -245,7 +245,7 @@ public void grantWeblogPermission(Weblog weblog, User user, List actions public void grantWeblogPermissionPending(Weblog weblog, User user, List actions) throws WebloggerException; - + /** * Confirm user's permission within specified weblog or throw exception if no pending permission exists. * (changes state of permsission record to pending = true) @@ -256,7 +256,7 @@ public void grantWeblogPermissionPending(Weblog weblog, User user, List public void confirmWeblogPermission(Weblog weblog, User user) throws WebloggerException; - + /** * Decline permissions within specified weblog or throw exception if no pending permission exists. * (removes permission record) @@ -267,7 +267,7 @@ public void confirmWeblogPermission(Weblog weblog, User user) public void declineWeblogPermission(Weblog weblog, User user) throws WebloggerException; - + /** * Revoke from user specific actions in a weblog. * (if resulting permission has empty removes permission record) @@ -278,64 +278,64 @@ public void declineWeblogPermission(Weblog weblog, User user) public void revokeWeblogPermission(Weblog weblog, User user, List actions) throws WebloggerException; - + /** * Get all of user's weblog permissions. */ - public List getWeblogPermissions(User user) + public List getWeblogPermissions(User user) throws WebloggerException; - - + + /** * Get all of user's pending weblog permissions. */ - public List getWeblogPermissionsPending(User user) + public List getWeblogPermissionsPending(User user) throws WebloggerException; - - + + /** * Get all permissions associated with a weblog. */ - public List getWeblogPermissions(Weblog weblog) + public List getWeblogPermissions(Weblog weblog) throws WebloggerException; - - + + /** * Get all pending permissions associated with a weblog. */ - public List getWeblogPermissionsPending(Weblog weblog) + public List getWeblogPermissionsPending(Weblog weblog) throws WebloggerException; - - + + /** * Get user's permission within a weblog or null if none. */ - public WeblogPermission getWeblogPermission(Weblog weblog, User user) - throws WebloggerException; - - + public WeblogPermission getWeblogPermission(Weblog weblog, User user) + throws WebloggerException; + + //--------------------------------------------------------------- role CRUD - + /** * Grant role to user. */ public void grantRole(String roleName, User user) throws WebloggerException; - - + + /** * Revoke role from user. */ public void revokeRole(String roleName, User user) throws WebloggerException; - + /** * Returns true if user has role specified, should be used only for testing. * @deprecated User checkPermission() instead. */ public boolean hasRole(String roleName, User user) throws WebloggerException; - - + + /** * Get roles associated with user, should be used only for testing. * Get all roles associated with user. @@ -343,11 +343,11 @@ public WeblogPermission getWeblogPermission(Weblog weblog, User user) */ public List getRoles(User user) throws WebloggerException; - + /** * Release any resources held by manager. */ - public void release(); + public void release(); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogEntryManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogEntryManager.java index d829a10bf7..2ded354f5a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogEntryManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogEntryManager.java @@ -38,28 +38,28 @@ public interface WeblogEntryManager { public static final String DESCENDING = "DESCENDING"; public static final String ASCENDING = "ASCENDING"; - + /** * Save weblog entry. */ public void saveWeblogEntry(WeblogEntry entry) throws WebloggerException; - + /** * Remove weblog entry. */ - public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException; - + public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException; + /** * Get weblog entry by id. */ public WeblogEntry getWeblogEntry(String id) throws WebloggerException; - - /** - * Get weblog entry by anchor. + + /** + * Get weblog entry by anchor. */ - public WeblogEntry getWeblogEntryByAnchor(Weblog website, String anchor) + public WeblogEntry getWeblogEntryByAnchor(Weblog website, String anchor) throws WebloggerException; - + /** * Get WeblogEntries by offset/length as list in reverse chronological order. * The range offset and list arguments enable paging through query results. @@ -86,13 +86,13 @@ public List getWeblogEntries( List tags, String status, String text, - String sortBy, + String sortBy, String sortOrder, - String locale, + String locale, int offset, int range) throws WebloggerException; - + /** * Get Weblog Entries grouped by day. This method returns a Map that * contains Lists, each List contains WeblogEntryData objects, and the @@ -112,13 +112,13 @@ public Map getWeblogEntryObjectMap( Date startDate, Date endDate, String catName, - List tags, + List tags, String status, String locale, int offset, int range) throws WebloggerException; - + /** * Get Weblog Entry date strings grouped by day. This method returns a Map * that contains Lists, each List contains YYYYMMDD date strings objects, @@ -138,13 +138,13 @@ public Map getWeblogEntryStringMap( Date startDate, Date endDate, String catName, - List tags, + List tags, String status, String locale, int offset, int range) - throws WebloggerException; - + throws WebloggerException; + /** * Get weblog entries with given category or, optionally, any sub-category * of that category. @@ -152,10 +152,10 @@ public Map getWeblogEntryStringMap( * @param subcats True if sub-categories are to be fetched * @return List of weblog entries in category */ - public List getWeblogEntries(WeblogCategory cat, boolean subcats) - throws WebloggerException; - - /** + public List getWeblogEntries(WeblogCategory cat, boolean subcats) + throws WebloggerException; + + /** * Get weblog enties ordered by descending number of comments. * @param website Weblog or null to get for all weblogs. * @param startDate Start date or null for no start date. @@ -165,32 +165,32 @@ public List getWeblogEntries(WeblogCategory cat, boolean subcats) * @return List of WeblogEntryData objects. */ public List getMostCommentedWeblogEntries( - Weblog website, + Weblog website, Date startDate, Date endDate, - int offset, + int offset, int length) throws WebloggerException; - + /** * Get the WeblogEntry following, chronologically, the current entry. * Restrict by the Category, if named. * @param current The "current" WeblogEntryData * @param catName The value of the requested Category Name */ - public WeblogEntry getNextEntry(WeblogEntry current, - String catName, String locale) throws WebloggerException; - + public WeblogEntry getNextEntry(WeblogEntry current, + String catName, String locale) throws WebloggerException; + /** * Get the WeblogEntry prior to, chronologically, the current entry. * Restrict by the Category, if named. * @param current The "current" WeblogEntryData. * @param catName The value of the requested Category Name. */ - public WeblogEntry getPreviousEntry(WeblogEntry current, + public WeblogEntry getPreviousEntry(WeblogEntry current, String catName, String locale) throws WebloggerException; - - + + /** * Get specified number of most recent pinned and published Weblog Entries. * @param max Maximum number to return. @@ -216,18 +216,18 @@ public void removeWeblogEntryTag(String name,WeblogEntry entry) * Save weblog category. */ public void saveWeblogCategory(WeblogCategory cat) throws WebloggerException; - + /** * Remove weblog category. */ public void removeWeblogCategory(WeblogCategory cat) throws WebloggerException; - + /** * Get category by id. */ public WeblogCategory getWeblogCategory(String id) throws WebloggerException; - - + + /** * Move a category under another category. * @@ -235,52 +235,52 @@ public void removeWeblogEntryTag(String name,WeblogEntry entry) */ public void moveWeblogCategory(WeblogCategory src, WeblogCategory dest) throws WebloggerException; - - + + /** * Recategorize all entries with one category to another. */ - public void moveWeblogCategoryContents(WeblogCategory srcCat, WeblogCategory destCat) + public void moveWeblogCategoryContents(WeblogCategory srcCat, WeblogCategory destCat) throws WebloggerException; - + /** * Get top level categories for a website. * @param website Website. */ public WeblogCategory getRootWeblogCategory(Weblog website) throws WebloggerException; - - + + /** * Get category specified by website and categoryPath. * @param website Website of WeblogCategory. * @param categoryPath Path of WeblogCategory, relative to category root. */ - public WeblogCategory getWeblogCategoryByPath(Weblog website, + public WeblogCategory getWeblogCategoryByPath(Weblog website, String categoryPath) throws WebloggerException; - - - /** - * Get WebLogCategory objects for a website. + + + /** + * Get WebLogCategory objects for a website. */ public List getWeblogCategories(Weblog website, boolean includeRoot) throws WebloggerException; - - + + /** * Save comment. */ public void saveComment(WeblogEntryComment comment) throws WebloggerException; - + /** * Remove comment. */ public void removeComment(WeblogEntryComment comment) throws WebloggerException; - + /** * Get comment by id. */ public WeblogEntryComment getComment(String id) throws WebloggerException; - + /** * Generic comments query method. * @param website Website or null for all comments on site @@ -293,7 +293,7 @@ public List getWeblogCategories(Weblog website, boolean includeRoot) * @param length Max comments to return (or -1 for no limit) */ public List getComments( - + Weblog website, WeblogEntry entry, String searchString, @@ -303,7 +303,7 @@ public List getComments( boolean reverseChrono, int offset, int length - + ) throws WebloggerException; /** @@ -316,45 +316,45 @@ public List getComments( * @return Number of comments deleted */ public int removeMatchingComments( - + Weblog website, WeblogEntry entry, String searchString, Date startDate, Date endDate, String status - + ) throws WebloggerException; - + /** * Create unique anchor for weblog entry. */ - public String createAnchor(WeblogEntry data) throws WebloggerException; - + public String createAnchor(WeblogEntry data) throws WebloggerException; + /** * Check for duplicate category name. */ public boolean isDuplicateWeblogCategoryName(WeblogCategory data) - throws WebloggerException; - + throws WebloggerException; + /** * Check if weblog category is in use. */ public boolean isWeblogCategoryInUse(WeblogCategory data) - throws WebloggerException; - - + throws WebloggerException; + + /** * Apply comment default settings from website to all of website's entries. */ - public void applyCommentDefaultsToEntries(Weblog website) + public void applyCommentDefaultsToEntries(Weblog website) throws WebloggerException; - + /** * Release all resources held by manager. */ - public void release(); - + public void release(); + /** * Get list of TagStat. There's no offset/length params just a limit. * @param website Weblog or null to get for all weblogs. @@ -365,19 +365,19 @@ public void applyCommentDefaultsToEntries(Weblog website) */ public List getPopularTags(Weblog website, Date startDate, int offset, int limit) throws WebloggerException; - + /** * Get list of TagStat. There's no offset/length params just a limit. * @param website Weblog or null to get for all weblogs. - * @param sortBy Sort by either 'name' or 'count' (null for name) + * @param sortBy Sort by either 'name' or 'count' (null for name) * @param startsWith Prefix for tags to be returned (null or a string of length > 0) * @param limit Max TagStats to return (or -1 for no limit) * @return * @throws WebloggerException */ public List getTags(Weblog website, String sortBy, String startsWith, int offset, int limit) - throws WebloggerException; - + throws WebloggerException; + /** * Does the specified tag combination exist? Optionally confined to a specific weblog. * @@ -391,15 +391,15 @@ public List getTags(Weblog website, String sortBy, String startsWith, int offset * @return True if tags exist, false otherwise. * @throws WebloggerException If there is any problem doing the operation. */ - public boolean getTagComboExists(List tags, Weblog weblog) + public boolean getTagComboExists(List tags, Weblog weblog) throws WebloggerException; - + /** * This method maintains the tag aggregate table up-to-date with total counts. More * specifically every time this method is called it will act upon exactly two rows * in the database (tag,website,count), one with website matching the argument passed * and one where website is null. If the count ever reaches zero, the row must be deleted. - * + * * @param name The tag name * @param website The website to used when updating the stats. * @param amount The amount to increment the tag count (it can be positive or negative). @@ -407,8 +407,8 @@ public boolean getTagComboExists(List tags, Weblog weblog) */ public void updateTagCount(String name, Weblog website, int amount) throws WebloggerException; - - + + /** * Get a HitCountData by id. * @@ -417,8 +417,8 @@ public void updateTagCount(String name, Weblog website, int amount) * @throws WebloggerException If there was a problem with the backend. */ public WeblogHitCount getHitCount(String id) throws WebloggerException; - - + + /** * Get a HitCountData by weblog. * @@ -428,8 +428,8 @@ public void updateTagCount(String name, Weblog website, int amount) */ public WeblogHitCount getHitCountByWeblog(Weblog weblog) throws WebloggerException; - - + + /** * Get HitCountData objects for the hotest weblogs. * @@ -447,8 +447,8 @@ public WeblogHitCount getHitCountByWeblog(Weblog weblog) */ public List getHotWeblogs(int sinceDays, int offset, int length) throws WebloggerException; - - + + /** * Save a HitCountData object. * @@ -456,8 +456,8 @@ public List getHotWeblogs(int sinceDays, int offset, int length) * @throws WebloggerException If there was a problem with the backend. */ public void saveHitCount(WeblogHitCount hitCount) throws WebloggerException; - - + + /** * Remove a HitCountData object. * @@ -465,8 +465,8 @@ public List getHotWeblogs(int sinceDays, int offset, int length) * @throws WebloggerException If there was a problem with the backend. */ public void removeHitCount(WeblogHitCount hitCount) throws WebloggerException; - - + + /** * Increment the hit count for a weblog by a certain amount. * @@ -479,16 +479,16 @@ public List getHotWeblogs(int sinceDays, int offset, int length) */ public void incrementHitCount(Weblog weblog, int amount) throws WebloggerException; - - + + /** * Reset the hit counts for all weblogs. This sets the counts back to 0. * * @throws WebloggerException If there was a problem with the backend. */ public void resetAllHitCounts() throws WebloggerException; - - + + /** * Reset the hit counts for a single weblog. This sets the count to 0. * @@ -497,29 +497,29 @@ public void incrementHitCount(Weblog weblog, int amount) */ public void resetHitCount(Weblog weblog) throws WebloggerException; - + /** - * Get site-wide comment count + * Get site-wide comment count */ public long getCommentCount() throws WebloggerException; - + /** - * Get weblog comment count - */ + * Get weblog comment count + */ public long getCommentCount(Weblog websiteData) throws WebloggerException; - + /** - * Get site-wide entry count - */ + * Get site-wide entry count + */ public long getEntryCount() throws WebloggerException; - + /** - * Get weblog entry count - */ + * Get weblog entry count + */ public long getEntryCount(Weblog websiteData) throws WebloggerException; - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogManager.java index 6af59ce537..fe79bd88b1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WeblogManager.java @@ -31,48 +31,48 @@ * Interface to weblog and page template management. */ public interface WeblogManager { - + /** * Add new website, give creator admin permission, creates blogroll, * creates categories and other objects required for new website. * @param newWebsite New website to be created, must have creator. */ public void addWeblog(Weblog newWebsite) throws WebloggerException; - - + + /** * Store a single weblog. */ public void saveWeblog(Weblog data) throws WebloggerException; - - + + /** * Remove website object. */ public void removeWeblog(Weblog website) throws WebloggerException; - - + + /** * Get website object by name. */ public Weblog getWeblog(String id) throws WebloggerException; - - + + /** * Get website specified by handle (or null if enabled website not found). * @param handle Handle of website */ public Weblog getWeblogByHandle(String handle) throws WebloggerException; - - + + /** * Get website specified by handle with option to return only enabled websites. * @param handle Handle of website */ public Weblog getWeblogByHandle(String handle, Boolean enabled) throws WebloggerException; - - + + /** * Get websites optionally restricted by user, enabled and active status. * @param enabled Get all with this enabled state (or null or all) @@ -91,8 +91,8 @@ public List getWeblogs( int offset, int length) throws WebloggerException; - - + + /** * Get websites of a user. * @param user Get all weblogs for this user @@ -100,8 +100,8 @@ public List getWeblogs( * @return List of WebsiteData objects. */ public List getUserWeblogs(User user, boolean enabledOnly) throws WebloggerException; - - + + /** * Get users of a weblog. * @param user Get all users for this weblog @@ -109,8 +109,8 @@ public List getWeblogs( * @return List of WebsiteData objects. */ public List getWeblogUsers(Weblog weblog, boolean enabledOnly) throws WebloggerException; - - + + /** * Get websites ordered by descending number of comments. * @param startDate Restrict to those created after (or null for all) @@ -125,71 +125,71 @@ public List getMostCommentedWeblogs( int offset, int length) throws WebloggerException; - - + + /** * Get map with 26 entries, one for each letter A-Z and * containing integers reflecting the number of weblogs whose * names start with each letter. */ public Map getWeblogHandleLetterMap() throws WebloggerException; - - - /** - * Get collection of weblogs whose handles begin with specified letter + + + /** + * Get collection of weblogs whose handles begin with specified letter */ - public List getWeblogsByLetter(char letter, int offset, int length) + public List getWeblogsByLetter(char letter, int offset, int length) throws WebloggerException; - + /** * Store page. */ public void savePage(WeblogTemplate data) throws WebloggerException; - - + + /** * Remove page. */ public void removePage(WeblogTemplate page) throws WebloggerException; - - + + /** * Get page by id. */ public WeblogTemplate getPage(String id) throws WebloggerException; - - + + /** * Get user's page by action. */ public WeblogTemplate getPageByAction(Weblog w, String a) throws WebloggerException; - - + + /** * Get user's page by name. */ public WeblogTemplate getPageByName(Weblog w, String p) throws WebloggerException; - - + + /** * Get website's page by link. */ public WeblogTemplate getPageByLink(Weblog w, String p) throws WebloggerException; - - + + /** * Get website's pages */ public List getPages(Weblog w) throws WebloggerException; - - + + /** * Get count of active weblogs - */ + */ public long getWeblogCount() throws WebloggerException; - - + + /** * Release any resources held by manager. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/Weblogger.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/Weblogger.java index 13482eeef8..0489f6a0d9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/Weblogger.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/Weblogger.java @@ -32,25 +32,25 @@ /** - * + * * The main entry point interface of the Weblogger business tier. */ public interface Weblogger { /** - * + * * Get UserManager associated with this Weblogger instance. */ public UserManager getUserManager(); - - + + /** - * + * * Get BookmarkManager associated with this Weblogger instance. */ public BookmarkManager getBookmarkManager(); - - + + /** * * Get OAuthManager associated with this Weblogger instance. @@ -59,84 +59,84 @@ public interface Weblogger { /** - * + * * Get WeblogManager associated with this Weblogger instance. */ public WeblogManager getWeblogManager(); - + /** - * + * * Get WeblogManager associated with this Weblogger instance. */ public WeblogEntryManager getWeblogEntryManager(); - - + + /** - * + * * Get RefererManager associated with this Weblogger instance. */ public RefererManager getRefererManager(); - - + + /** * Get ReferrerQueueManager. */ public ReferrerQueueManager getReferrerQueueManager(); - - + + /** * Get the AutoPingManager associated with this Weblogger instance. */ public AutoPingManager getAutopingManager(); - - + + /** * Get the PingTargetManager associated with this Weblogger instance. */ public PingTargetManager getPingTargetManager(); - - + + /** * Get the PingQueueManager associated with this Weblogger instance. */ public PingQueueManager getPingQueueManager(); - - + + /** - * + * * Get PropertiesManager associated with this Weblogger instance. */ - public PropertiesManager getPropertiesManager(); - - + public PropertiesManager getPropertiesManager(); + + /** * Get ThreadManager associated with this Weblogger instance. */ public ThreadManager getThreadManager(); - - + + /** * Get IndexManager associated with this Weblogger instance. */ public IndexManager getIndexManager(); - - + + /** * Get ThemeManager associated with this Weblogger instance. */ public ThemeManager getThemeManager(); - - + + /** * Get PluginManager associated with this Weblogger instance. */ public PluginManager getPluginManager(); - + /** * Get MediaFileManager associated with this Weblogger instance. */ public MediaFileManager getMediaFileManager(); - + /** * Get FileContentManager associated with this Weblogger instance. */ @@ -146,49 +146,49 @@ public interface Weblogger { * Get the URLStrategy used to build all urls in the system. */ public URLStrategy getUrlStrategy(); - + /** * Flush object states. */ public void flush() throws WebloggerException; - - + + /** * Release all resources associated with Weblogger session. */ public void release(); - - + + /** * Initialize any resources necessary for this instance of Weblogger. */ public void initialize() throws InitializationException; - - + + /** * Release all resources necessary for this instance of Weblogger. */ public void shutdown(); - - + + /** * Weblogger version */ - public String getVersion(); - + public String getVersion(); + /** * Weblogger source code management revision */ public String getRevision(); - + /** * Weblogger build time */ public String getBuildTime(); - + /** * Get username that built Weblogger */ public String getBuildUser(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerFactory.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerFactory.java index 6668283890..fcaede74a0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerFactory.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerFactory.java @@ -28,30 +28,30 @@ * Provides access to the Weblogger instance and bootstraps the business tier. */ public final class WebloggerFactory { - + private static final Log log = LogFactory.getLog(WebloggerFactory.class); - + // our configured weblogger provider private static WebloggerProvider webloggerProvider = null; - - + + // non-instantiable private WebloggerFactory() { // hello all you beautiful people } - - + + /** * True if bootstrap process has been completed, False otherwise. */ public static boolean isBootstrapped() { return (webloggerProvider != null); } - - + + /** * Accessor to the Weblogger Weblogger business tier. - * + * * @return Weblogger An instance of Weblogger. * @throws IllegalStateException If the app has not been properly bootstrapped yet. */ @@ -59,28 +59,28 @@ public static final Weblogger getWeblogger() { if (webloggerProvider == null) { throw new IllegalStateException("Roller Weblogger has not been bootstrapped yet"); } - + return webloggerProvider.getWeblogger(); } - - + + /** * Bootstrap the Roller Weblogger business tier, uses default WebloggerProvider. * * Bootstrapping the application effectively instantiates all the necessary - * pieces of the business tier and wires them together so that the app is + * pieces of the business tier and wires them together so that the app is * ready to run. * * @throws IllegalStateException If the app has not been properly prepared yet. * @throws BootstrapException If an error happens during the bootstrap process. */ public static final void bootstrap() throws BootstrapException { - + // if the app hasn't been properly started so far then bail if (!WebloggerStartup.isPrepared()) { throw new IllegalStateException("Cannot bootstrap until application has been properly prepared"); } - + // lookup our default provider and instantiate it WebloggerProvider defaultProvider; String providerClassname = WebloggerConfig.getProperty("weblogger.provider.class"); @@ -98,49 +98,49 @@ public static final void bootstrap() throws BootstrapException { // now just bootstrap using our default provider bootstrap(defaultProvider); } - - + + /** * Bootstrap the Roller Weblogger business tier, uses specified WebloggerProvider. * * Bootstrapping the application effectively instantiates all the necessary - * pieces of the business tier and wires them together so that the app is + * pieces of the business tier and wires them together so that the app is * ready to run. * * @param provider A WebloggerProvider to use for bootstrapping. * @throws IllegalStateException If the app has not been properly prepared yet. * @throws BootstrapException If an error happens during the bootstrap process. */ - public static final void bootstrap(WebloggerProvider provider) + public static final void bootstrap(WebloggerProvider provider) throws BootstrapException { - + // if the app hasn't been properly started so far then bail if (!WebloggerStartup.isPrepared()) { throw new IllegalStateException("Cannot bootstrap until application has been properly prepared"); } - + if (provider == null) { throw new NullPointerException("WebloggerProvider is null"); } - + log.info("Bootstrapping Roller Weblogger business tier"); - + log.info("Weblogger Provider = "+provider.getClass().getName()); - + // save reference to provider webloggerProvider = provider; - + // bootstrap weblogger provider webloggerProvider.bootstrap(); - + // make sure we are all set if(webloggerProvider.getWeblogger() == null) { throw new BootstrapException("Bootstrapping failed, Weblogger instance is null"); } - + log.info("Roller Weblogger business tier successfully bootstrapped"); log.info(" Version: " + webloggerProvider.getWeblogger().getVersion()); log.info(" Revision: " + webloggerProvider.getWeblogger().getRevision()); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerImpl.java index 1faebef786..b2b73e28f1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerImpl.java @@ -37,15 +37,15 @@ /** * The abstract version of the Weblogger implementation. - * + * * Here we put code that pertains to *all* implementations of the Weblogger * interface, regardless of their persistence strategy. */ @com.google.inject.Singleton public abstract class WebloggerImpl implements Weblogger { - + private static Log log = LogFactory.getLog(WebloggerImpl.class); - + // managers private final AutoPingManager autoPingManager; private final BookmarkManager bookmarkManager; @@ -64,17 +64,17 @@ public abstract class WebloggerImpl implements Weblogger { private final WeblogManager weblogManager; private final WeblogEntryManager weblogEntryManager; private final OAuthManager oauthManager; - + // url strategy private final URLStrategy urlStrategy; - + // some simple attributes private final String version; private final String revision; private final String buildTime; private final String buildUser; - - + + protected WebloggerImpl( AutoPingManager autoPingManager, BookmarkManager bookmarkManager, @@ -86,15 +86,15 @@ protected WebloggerImpl( PluginManager pluginManager, PropertiesManager propertiesManager, RefererManager refererManager, - ReferrerQueueManager refererQueueManager, + ReferrerQueueManager refererQueueManager, ThemeManager themeManager, ThreadManager threadManager, UserManager userManager, WeblogManager weblogManager, WeblogEntryManager weblogEntryManager, OAuthManager oauthManager, - URLStrategy urlStrategy) throws WebloggerException { - + URLStrategy urlStrategy) throws WebloggerException { + this.autoPingManager = autoPingManager; this.bookmarkManager = bookmarkManager; this.indexManager = indexManager; @@ -113,169 +113,169 @@ protected WebloggerImpl( this.weblogEntryManager = weblogEntryManager; this.oauthManager = oauthManager; this.urlStrategy = urlStrategy; - + Properties props = new Properties(); try { props.load(getClass().getResourceAsStream("/roller-version.properties")); } catch (IOException e) { log.error("roller-version.properties not found", e); } - + version = props.getProperty("ro.version", "UNKNOWN"); revision = props.getProperty("ro.revision", "UNKNOWN"); buildTime = props.getProperty("ro.buildTime", "UNKNOWN"); buildUser = props.getProperty("ro.buildUser", "UNKNOWN"); } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getThreadManager() */ public ThreadManager getThreadManager() { return threadManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getIndexManager() */ public IndexManager getIndexManager() { return indexManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getThemeManager() */ public ThemeManager getThemeManager() { return themeManager; } - - + + /** * @see org.apache.roller.weblogger.business.referrers.ReferrerQueueManager */ public ReferrerQueueManager getReferrerQueueManager() { return refererQueueManager; } - - - + + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getUserManager() */ public UserManager getUserManager() { return userManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getBookmarkManager() */ public BookmarkManager getBookmarkManager() { return bookmarkManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getMediaFileManager() */ public MediaFileManager getMediaFileManager() { return mediaFileManager; } - + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getFileContentManager() */ public FileContentManager getFileContentManager() { return fileContentManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getWeblogEntryManager() */ public WeblogEntryManager getWeblogEntryManager() { return weblogEntryManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getWeblogManager() */ public WeblogManager getWeblogManager() { return weblogManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getRefererManager() */ public RefererManager getRefererManager() { return refererManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getPropertiesManager() */ public PropertiesManager getPropertiesManager() { return propertiesManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getPingTargetManager() */ public PingQueueManager getPingQueueManager() { return pingQueueManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getPingTargetManager() */ public AutoPingManager getAutopingManager() { return autoPingManager; } - - + + /** - * - * + * + * * @see org.apache.roller.weblogger.modelWebloggerr#getPingTargetManager() */ public PingTargetManager getPingTargetManager() { return pingTargetManager; } - - + + /** * * @@ -302,8 +302,8 @@ public OAuthManager getOAuthManager() { public URLStrategy getUrlStrategy() { return urlStrategy; } - - + + /** * @inheritDoc */ @@ -324,15 +324,15 @@ public void release() { log.error("Error calling Roller.release()", e); } } - - + + /** * @inheritDoc */ public void initialize() throws InitializationException { - + log.info("Initializing Roller Weblogger business tier"); - + // TODO: this should probably be done in a more uniform fashion, possibly // using annotations? biggest issue is controlling ordering getPropertiesManager().initialize(); @@ -340,23 +340,23 @@ public void initialize() throws InitializationException { getThreadManager().initialize(); getIndexManager().initialize(); getMediaFileManager().initialize(); - + try { // Initialize ping systems // TODO: this should probably be moving inside ping manager initialize() methods? - + // Initialize common targets from the configuration PingConfig.initializeCommonTargets(); - + // Initialize ping variants PingConfig.initializePingVariants(); - + // Remove custom ping targets if they have been disallowed if (PingConfig.getDisallowCustomTargets()) { log.info("Custom ping targets have been disallowed. Removing any existing custom targets."); WebloggerFactory.getWeblogger().getPingTargetManager().removeAllCustomPingTargets(); } - + // Remove all autoping configurations if ping usage has been disabled. if (PingConfig.getDisablePingUsage()) { log.info("Ping usage has been disabled. Removing any existing auto ping configurations."); @@ -365,19 +365,19 @@ public void initialize() throws InitializationException { } catch (Throwable t) { throw new InitializationException("Error initializing ping systems", t); } - + // we always need to do a flush after initialization because it's // possible that some changes need to be persisted try { flush(); } catch(WebloggerException ex) { throw new InitializationException("Error flushing after initialization", ex); - } - + } + log.info("Roller Weblogger business tier successfully initialized"); } - - + + /** * @inheritDoc */ @@ -391,35 +391,35 @@ public void shutdown() { log.error("Error calling Roller.shutdown()", e); } } - - + + /** * Weblogger version */ public String getVersion() { return version; } - + /** * Get source code repository revision # used to create build */ public String getRevision() { return revision; } - + /** * Weblogger build time */ public String getBuildTime() { return buildTime; } - - + + /** * Get username that built Weblogger */ public String getBuildUser() { return buildUser; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerProvider.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerProvider.java index 646b301954..e586cc6522 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerProvider.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/WebloggerProvider.java @@ -23,16 +23,16 @@ * Provides access to a Weblogger instance. */ public interface WebloggerProvider { - + /** * Trigger bootstrapping. */ public void bootstrap() throws BootstrapException; - - + + /** * Get a Weblogger instance. */ public Weblogger getWeblogger(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPABookmarkManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPABookmarkManagerImpl.java index eeb9834640..5a2c919359 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPABookmarkManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPABookmarkManagerImpl.java @@ -44,11 +44,11 @@ */ @com.google.inject.Singleton public class JPABookmarkManagerImpl implements BookmarkManager { - + private final Weblogger roller; private final JPAPersistenceStrategy strategy; - - + + /** * The logger instance for this class. */ @@ -65,9 +65,9 @@ protected JPABookmarkManagerImpl(Weblogger roller, JPAPersistenceStrategy strate this.strategy = strategy; } - + public void saveBookmark(WeblogBookmark bookmark) throws WebloggerException { - boolean exists = getBookmark(bookmark.getId()) != null; + boolean exists = getBookmark(bookmark.getId()) != null; if (!exists) { // New object make sure that relationship is set on managed copy of other side bookmark.getFolder().getBookmarks().add(bookmark); @@ -85,19 +85,19 @@ public WeblogBookmark getBookmark(String id) throws WebloggerException { public void removeBookmark(WeblogBookmark bookmark) throws WebloggerException { Weblog weblog = bookmark.getWebsite(); - + //Remove the bookmark from its parent folder bookmark.getFolder().getBookmarks().remove(bookmark); - + // Now remove it from database this.strategy.remove(bookmark); - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog(weblog); } public void saveFolder(WeblogBookmarkFolder folder) throws WebloggerException { - + if (folder.getId() == null || this.getFolder(folder.getId()) == null) { // New folder, so make sure name is unique if (isDuplicateFolderName(folder)) { @@ -129,19 +129,19 @@ public void removeFolder(WeblogBookmarkFolder folder) throws WebloggerException Weblog weblog = roller.getWeblogManager().getWeblog(websiteid); roller.getWeblogManager().saveWeblog(weblog); } - + public void moveFolder(WeblogBookmarkFolder srcFolder, WeblogBookmarkFolder destFolder) throws WebloggerException { - + // TODO: this check should be made before calling this method? if (destFolder.descendentOf(srcFolder)) { throw new WebloggerException( "ERROR cannot move parent folder into it's own child"); } - + log.debug("Moving folder " + srcFolder.getPath() + " under " + destFolder.getPath()); - + // Manage relationships WeblogBookmarkFolder oldParent = srcFolder.getParent(); if(oldParent != null) { @@ -149,48 +149,48 @@ public void moveFolder(WeblogBookmarkFolder srcFolder, WeblogBookmarkFolder dest } srcFolder.setParent(destFolder); destFolder.getFolders().add(srcFolder); - + if("/".equals(destFolder.getPath())) { srcFolder.setPath("/"+srcFolder.getName()); } else { srcFolder.setPath(destFolder.getPath() + "/" + srcFolder.getName()); } saveFolder(srcFolder); - - // the main work to be done for a category move is to update the + + // the main work to be done for a category move is to update the // path attribute of the category and all descendent categories updatePathTree(srcFolder); - } + } // updates the paths of all descendents of the given folder private void updatePathTree(WeblogBookmarkFolder folder) throws WebloggerException { - + log.debug("Updating path tree for folder "+folder.getPath()); - + WeblogBookmarkFolder childFolder = null; Iterator childFolders = folder.getFolders().iterator(); while(childFolders.hasNext()) { childFolder = (WeblogBookmarkFolder) childFolders.next(); - + log.debug("OLD child folder path was "+childFolder.getPath()); - + // update path and save if("/".equals(folder.getPath())) { childFolder.setPath("/" + childFolder.getName()); } else { - childFolder.setPath(folder.getPath() + "/" + + childFolder.setPath(folder.getPath() + "/" + childFolder.getName()); } saveFolder(childFolder); - + log.debug("NEW child folder path is "+ childFolder.getPath()); - + // then make recursive call to update this folders children updatePathTree(childFolder); } } - + /** * Retrieve folder and lazy-load it's sub-folders and bookmarks. */ @@ -198,7 +198,7 @@ public WeblogBookmarkFolder getFolder(String id) throws WebloggerException { return (WeblogBookmarkFolder) strategy.load(WeblogBookmarkFolder.class, id); } - + public void importBookmarks( Weblog website, String folderName, String opml) throws WebloggerException { @@ -212,7 +212,7 @@ public void importBookmarks( WeblogBookmarkFolder newFolder = getFolder(website, folderName); if (newFolder == null) { newFolder = new WeblogBookmarkFolder( - getRootFolder(website), + getRootFolder(website), folderName, folderName, website); this.strategy.store(newFolder); } @@ -231,7 +231,7 @@ public void importBookmarks( } // convenience method used when importing bookmarks - // NOTE: this method does not commit any changes; + // NOTE: this method does not commit any changes; // that is done by importBookmarks() private void importOpmlElement( Weblog website, Element elem, WeblogBookmarkFolder parent) @@ -248,7 +248,7 @@ private void importOpmlElement( desc = null!=desc ? desc : title; xmlUrl = null!=xmlUrl ? xmlUrl : url; url = null!=htmlUrl ? htmlUrl : url; - + // better to truncate imported OPML fields than to fail import or drop whole bookmark // TODO: add way to notify user that fields were truncated if (title != null && title.length() > 254) title = title.substring(0, 254); @@ -258,12 +258,12 @@ private void importOpmlElement( if (elem.getChildren().size()==0) { // Leaf element. Store a bookmark - // Currently bookmarks must have at least a name and + // Currently bookmarks must have at least a name and // HTML url to be stored. Previous logic was - // trying to skip invalid ones, but was letting ones + // trying to skip invalid ones, but was letting ones // with an xml url and no html url through // which could result in a db exception. - // TODO: Consider providing error feedback instead of + // TODO: Consider providing error feedback instead of // silently skipping the invalid bookmarks here. if (null != title && null != url) { WeblogBookmark bd = new WeblogBookmark(parent, @@ -326,7 +326,7 @@ public WeblogBookmarkFolder getFolder(Weblog website, String path) * @see org.apache.roller.weblogger.model.BookmarkManager#retrieveBookmarks( * org.apache.roller.weblogger.pojos.WeblogBookmarkFolder, boolean) */ - public List getBookmarks(WeblogBookmarkFolder folder, boolean subfolders) + public List getBookmarks(WeblogBookmarkFolder folder, boolean subfolders) throws WebloggerException { Query query = null; List results = null; @@ -339,13 +339,13 @@ public List getBookmarks(WeblogBookmarkFolder folder, boolean subfolders) } else { // if we are doing subfolders then do a case sensitive // query using folder path - query = strategy.getNamedQuery( + query = strategy.getNamedQuery( "BoomarkData.getByFolder.pathLike&Folder.website"); query.setParameter(1, folder.getPath() + '%'); query.setParameter(2, folder.getWebsite()); results = query.getResultList(); } - + return results; } @@ -353,7 +353,7 @@ public WeblogBookmarkFolder getRootFolder(Weblog website) throws WebloggerException { if (website == null) throw new WebloggerException("website is null"); - + Query q = strategy.getNamedQuery("WeblogBookmarkFolder.getByWebsite&ParentNull"); q.setParameter(1, website); try { @@ -367,17 +367,17 @@ public List getAllFolders(Weblog website) throws WebloggerException { if (website == null) throw new WebloggerException("Website is null"); - + Query q = strategy.getNamedQuery("WeblogBookmarkFolder.getByWebsite"); q.setParameter(1, website); return q.getResultList(); } - + /** * make sure the given folder doesn't already exist. */ - private boolean isDuplicateFolderName(WeblogBookmarkFolder folder) + private boolean isDuplicateFolderName(WeblogBookmarkFolder folder) throws WebloggerException { // ensure that no sibling categories share the same name @@ -385,11 +385,11 @@ private boolean isDuplicateFolderName(WeblogBookmarkFolder folder) if (null != parent) { return (getFolder(folder.getWebsite(), folder.getPath()) != null); } - + return false; } public void release() {} - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java index 5faab7f32a..242a01eaa0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java @@ -112,7 +112,7 @@ public void moveMediaFiles(Collection mediaFiles, MediaFileDirectory List moved = new ArrayList(); moved.addAll(mediaFiles); - + for (MediaFile mediaFile : moved) { mediaFile.getDirectory().getMediaFiles().remove(mediaFile); @@ -425,7 +425,7 @@ public MediaFile getMediaFileByPath(Weblog weblog, String path) */ public MediaFile getMediaFileByOriginalPath(Weblog weblog, String origpath) throws WebloggerException { - + if (null == origpath) return null; if (!origpath.startsWith("/")) { @@ -810,7 +810,7 @@ private void upgradeUploadsDir(Weblog weblog, User user, File oldDir, MediaFileD } } - try { // flush changes to this directory + try { // flush changes to this directory roller.flush(); log.debug("Count of dirs created: " + dirCount); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java index 089f26daac..88f8184667 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java @@ -18,7 +18,7 @@ package org.apache.roller.weblogger.business.jpa; -import java.io.IOException; +import java.io.IOException; import java.sql.Timestamp; import java.util.Date; import java.util.UUID; @@ -65,7 +65,7 @@ public JPAOAuthManagerImpl( this.strategy = strategy; this.validator = validator; } - + public OAuthServiceProvider getServiceProvider() { return new OAuthServiceProvider( roller.getUrlStrategy().getOAuthRequestTokenURL(), @@ -94,9 +94,9 @@ public OAuthConsumer getConsumer( return consumer; } - + /** - * Get the access token and token secret for the given oauth_token. + * Get the access token and token secret for the given oauth_token. */ public OAuthAccessor getAccessor(OAuthMessage requestMessage) throws IOException, OAuthProblemException { @@ -121,7 +121,7 @@ public OAuthAccessor getAccessor(OAuthMessage requestMessage) } /** - * Set the access token + * Set the access token */ public void markAsAuthorized(OAuthAccessor accessor, String userId) throws OAuthException { @@ -131,7 +131,7 @@ public void markAsAuthorized(OAuthAccessor accessor, String userId) record.setUserName(userId); record.setAuthorized(Boolean.TRUE); strategy.store(record); - + } catch (WebloggerException ex) { throw new OAuthException("ERROR: setting authorization flag", ex); } @@ -163,7 +163,7 @@ public void generateRequestToken( // add to the local cache addAccessor(accessor); } - + /** * Generate a fresh request token and secret for a consumer. * @throws OAuthException @@ -178,7 +178,7 @@ public void generateAccessToken(OAuthAccessor accessor) OAuthAccessorRecord record = (OAuthAccessorRecord) strategy.load( OAuthAccessorRecord.class, accessor.consumer.consumerKey); - + // for now use md5 of name + current time as token String token_data = consumer_key + System.nanoTime(); String token = DigestUtils.md5Hex(token_data); @@ -204,7 +204,7 @@ public OAuthConsumer addConsumer(String username, String consumerKey) throws OAu } catch (WebloggerException ex) { throw new OAuthException("ERROR storing accessor", ex); } - + OAuthConsumer consumer = new OAuthConsumer( null, record.getConsumerKey(), @@ -214,7 +214,7 @@ public OAuthConsumer addConsumer(String username, String consumerKey) throws OAu return consumer; } - public OAuthConsumer addConsumer(String consumerKey) + public OAuthConsumer addConsumer(String consumerKey) throws OAuthException, WebloggerException { if (getConsumer() == null) { return addConsumer(null, consumerKey); @@ -265,7 +265,7 @@ record = (OAuthConsumerRecord)q.getSingleResult(); return null; } - + //--------------------------------------------- package protected internals OAuthConsumer consumerFromRecord(OAuthConsumerRecord record) { @@ -330,7 +330,7 @@ void addAccessor(OAuthAccessor accessor) throws OAuthException { } else { record.setCreated(new Timestamp(new Date().getTime())); } - + if (record.getUpdated() != null) { record.setUpdated(record.getUpdated()); } else { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPersistenceStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPersistenceStrategy.java index 5dbd43ae84..56fcfbfcaa 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPersistenceStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPersistenceStrategy.java @@ -47,21 +47,21 @@ */ @com.google.inject.Singleton public class JPAPersistenceStrategy { - - private static Log logger = + + private static Log logger = LogFactory.getFactory().getInstance(JPAPersistenceStrategy.class); - + /** * The thread local EntityManager. */ private final ThreadLocal threadLocalEntityManager = new ThreadLocal(); - + /** * The EntityManagerFactory for this Roller instance. */ private EntityManagerFactory emf = null; - - + + /** * Construct by finding JPA EntityManagerFactory. * @param dbProvider database configuration information for manual configuration. @@ -85,8 +85,8 @@ protected JPAPersistenceStrategy(DatabaseProvider dbProvider) throws WebloggerEx Enumeration keys = WebloggerConfig.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); - if ( key.startsWith("javax.persistence.") - || key.startsWith("openjpa.") + if ( key.startsWith("javax.persistence.") + || key.startsWith("openjpa.") || key.startsWith("hibernate.")) { String value = WebloggerConfig.getProperty(key); logger.info(key + ": " + value); @@ -106,14 +106,14 @@ protected JPAPersistenceStrategy(DatabaseProvider dbProvider) throws WebloggerEx try { this.emf = Persistence.createEntityManagerFactory("RollerPU", emfProps); - + } catch (Throwable pe) { logger.error("ERROR: creating entity manager", pe); throw new WebloggerException(pe); } } } - + /** * Flush changes to the datastore, commit transaction, release em. * @throws org.apache.roller.weblogger.WebloggerException on any error @@ -126,7 +126,7 @@ public void flush() throws WebloggerException { throw new WebloggerException(pe); } } - + /** * Release database session, rolls back any uncommitted changes. */ @@ -138,7 +138,7 @@ public void release() { em.close(); setThreadLocalEntityManager(null); } - + /** * Store object using an existing transaction. * @param obj the object to persist @@ -153,7 +153,7 @@ public Object store(Object obj) throws WebloggerException { } return obj; } - + /** * Remove object from persistence storage. * @param clazz the class of object to remove @@ -165,7 +165,7 @@ public void remove(Class clazz, String id) throws WebloggerException { Object po = em.find(clazz, id); em.remove(po); } - + /** * Remove object from persistence storage. * @param po the persistent object to remove @@ -175,7 +175,7 @@ public void remove(Object po) throws WebloggerException { EntityManager em = getEntityManager(true); em.remove(po); } - + /** * Remove object from persistence storage. * @param pos the persistent objects to remove @@ -187,8 +187,8 @@ public void removeAll(Collection pos) throws WebloggerException { Object obj = iterator.next(); em.remove(obj); } - } - + } + /** * Retrieve object, no transaction needed. * @param clazz the class of object to retrieve @@ -201,7 +201,7 @@ public Object load(Class clazz, String id) EntityManager em = getEntityManager(false); return em.find(clazz, id); } - + /** * Return true if a transaction is active on the current EntityManager. * @param em the persistence manager @@ -214,7 +214,7 @@ private boolean isTransactionActive(EntityManager em) { } return em.getTransaction().isActive(); } - + /** * Get the EntityManager associated with the current thread of control. * @param isTransactionRequired true if a transaction is begun if not @@ -228,7 +228,7 @@ public EntityManager getEntityManager(boolean isTransactionRequired) { } return em; } - + /** * Get the current ThreadLocal EntityManager */ @@ -240,14 +240,14 @@ private EntityManager getThreadLocalEntityManager() { } return em; } - + /** * Set the current ThreadLocal EntityManager */ private void setThreadLocalEntityManager(Object em) { threadLocalEntityManager.set(em); } - + /** * Get named query with FlushModeType.COMMIT * @param queryName the name of the query @@ -261,7 +261,7 @@ public Query getNamedQuery(String queryName) q.setFlushMode(FlushModeType.COMMIT); return q; } - + /** * Create query from queryString with FlushModeType.COMMIT * @param queryString the quuery @@ -275,7 +275,7 @@ public Query getDynamicQuery(String queryString) q.setFlushMode(FlushModeType.COMMIT); return q; } - + /** * Get named update query with default flush mode * @param queryName the name of the query @@ -287,7 +287,7 @@ public Query getNamedUpdate(String queryName) Query q = em.createNamedQuery(queryName); return q; } - + /** * Loads properties from given resourceName using given class loader * @param resourceName The name of the resource containing properties @@ -316,10 +316,10 @@ private static Properties loadPropertiesFromResourceName( } catch (IOException ioe) { } } - + return props; } - + /** * Get the context class loader associated with the current thread. This is * done in a doPrivileged block because it is a secure method. @@ -332,5 +332,5 @@ public Object run() { return Thread.currentThread().getContextClassLoader(); } }); - } + } } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingQueueManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingQueueManagerImpl.java index a70dd11ba0..f4ac2f3f95 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingQueueManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingQueueManagerImpl.java @@ -48,7 +48,7 @@ public class JPAPingQueueManagerImpl implements PingQueueManager { /** The strategy for this manager. */ private final Weblogger roller; private final JPAPersistenceStrategy strategy; - + /** * Creates a new instance of JPAPingQueueManagerImpl @@ -59,31 +59,31 @@ protected JPAPingQueueManagerImpl(Weblogger roller, JPAPersistenceStrategy strat this.strategy = strategy; } - - public PingQueueEntry getQueueEntry(String id) + + public PingQueueEntry getQueueEntry(String id) throws WebloggerException { return (PingQueueEntry)strategy.load( PingQueueEntry.class, id); } - public void saveQueueEntry(PingQueueEntry pingQueueEntry) + public void saveQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerException { log.debug("Storing ping queue entry: " + pingQueueEntry); strategy.store(pingQueueEntry); } - public void removeQueueEntry(PingQueueEntry pingQueueEntry) + public void removeQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerException { log.debug("Removing ping queue entry: " + pingQueueEntry); strategy.remove(pingQueueEntry); } - + public void addQueueEntry(AutoPing autoPing) throws WebloggerException { - log.debug("Creating new ping queue entry for auto ping configuration: " + log.debug("Creating new ping queue entry for auto ping configuration: " + autoPing); - - // First check if there is an existing ping queue entry + + // First check if there is an existing ping queue entry // for the same target and website if (isAlreadyQueued(autoPing)) { log.debug("A ping queue entry is already present" + @@ -94,20 +94,20 @@ public void addQueueEntry(AutoPing autoPing) throws WebloggerException { Timestamp now = new Timestamp(System.currentTimeMillis()); PingQueueEntry pingQueueEntry = new PingQueueEntry( - null, now, autoPing.getPingTarget(), + null, now, autoPing.getPingTarget(), autoPing.getWebsite(), 0); this.saveQueueEntry(pingQueueEntry); } - public List getAllQueueEntries() + public List getAllQueueEntries() throws WebloggerException { return (List)strategy.getNamedQuery( "PingQueueEntry.getAllOrderByEntryTime").getResultList(); } - // private helper to determine if an has already been queued + // private helper to determine if an has already been queued // for the same website and ping target. - private boolean isAlreadyQueued(AutoPing autoPing) + private boolean isAlreadyQueued(AutoPing autoPing) throws WebloggerException { // first, determine if an entry already exists Query q = strategy.getNamedQuery("PingQueueEntry.getByPingTarget&Website"); @@ -117,6 +117,6 @@ private boolean isAlreadyQueued(AutoPing autoPing) } public void release() {} - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingTargetManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingTargetManagerImpl.java index 48d59273f1..1107489fc4 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingTargetManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPingTargetManagerImpl.java @@ -45,23 +45,23 @@ */ @com.google.inject.Singleton public class JPAPingTargetManagerImpl implements PingTargetManager { - + /** The logger instance for this class. */ private static Log log = LogFactory.getLog( JPAPingTargetManagerImpl.class); private final Weblogger roller; private final JPAPersistenceStrategy strategy; - - + + @com.google.inject.Inject protected JPAPingTargetManagerImpl(Weblogger roller, JPAPersistenceStrategy strategy) { this.roller = roller; this.strategy = strategy; } - - public void removePingTarget(PingTarget pingTarget) + + public void removePingTarget(PingTarget pingTarget) throws WebloggerException { // remove contents and then target this.removePingTargetContents(pingTarget); @@ -72,13 +72,13 @@ public void removePingTarget(PingTarget pingTarget) * Convenience method which removes any queued pings or auto pings that * reference the given ping target. */ - private void removePingTargetContents(PingTarget ping) + private void removePingTargetContents(PingTarget ping) throws WebloggerException { // Remove the website's ping queue entries Query q = strategy.getNamedUpdate("PingQueueEntry.removeByPingTarget"); q.setParameter(1, ping); q.executeUpdate(); - + // Remove the website's auto ping configurations q = strategy.getNamedUpdate("AutoPing.removeByPingTarget"); q.setParameter(1, ping); @@ -102,14 +102,14 @@ public PingTarget getPingTarget(String id) return (PingTarget)strategy.load(PingTarget.class, id); } - public boolean isNameUnique(PingTarget pingTarget) + public boolean isNameUnique(PingTarget pingTarget) throws WebloggerException { String name = pingTarget.getName(); if (name == null || name.trim().length() == 0) return false; - + String id = pingTarget.getId(); - - // Determine the set of "brother" targets (custom or common) + + // Determine the set of "brother" targets (custom or common) // among which this name should be unique. List brotherTargets = null; Weblog website = pingTarget.getWebsite(); @@ -118,14 +118,14 @@ public boolean isNameUnique(PingTarget pingTarget) } else { brotherTargets = getCustomPingTargets(website); } - - // Within that set of targets, fail if there is a target + + // Within that set of targets, fail if there is a target // with the same name and that target doesn't // have the same id. for (Iterator i = brotherTargets.iterator(); i.hasNext();) { PingTarget brother = (PingTarget) i.next(); // Fail if it has the same name but not the same id. - if (brother.getName().equals(name) && + if (brother.getName().equals(name) && (id == null || !brother.getId().equals(id))) { return false; } @@ -134,17 +134,17 @@ public boolean isNameUnique(PingTarget pingTarget) return true; } - - public boolean isUrlWellFormed(PingTarget pingTarget) + + public boolean isUrlWellFormed(PingTarget pingTarget) throws WebloggerException { String url = pingTarget.getPingUrl(); if (url == null || url.trim().length() == 0) return false; try { URL parsedUrl = new URL(url); - // OK. If we get here, it parses ok. Now just check + // OK. If we get here, it parses ok. Now just check // that the protocol is http and there is a host portion. boolean isHttp = parsedUrl.getProtocol().equals("http"); - boolean hasHost = (parsedUrl.getHost() != null) && + boolean hasHost = (parsedUrl.getHost() != null) && (parsedUrl.getHost().trim().length() > 0); return isHttp && hasHost; } catch (MalformedURLException e) { @@ -152,8 +152,8 @@ public boolean isUrlWellFormed(PingTarget pingTarget) } } - - public boolean isHostnameKnown(PingTarget pingTarget) + + public boolean isHostnameKnown(PingTarget pingTarget) throws WebloggerException { String url = pingTarget.getPingUrl(); if (url == null || url.trim().length() == 0) return false; @@ -186,5 +186,5 @@ public List getCustomPingTargets(Weblog website) } public void release() {} - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPropertiesManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPropertiesManagerImpl.java index acd8ad642b..fa957cba8c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPropertiesManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAPropertiesManagerImpl.java @@ -47,15 +47,15 @@ */ @com.google.inject.Singleton public class JPAPropertiesManagerImpl implements PropertiesManager { - + /** The logger instance for this class. */ private static Log log = LogFactory.getLog( JPAPropertiesManagerImpl.class); private final Weblogger roller; private final JPAPersistenceStrategy strategy; - - + + /** * Creates a new instance of JPAPropertiesManagerImpl */ @@ -65,13 +65,13 @@ protected JPAPropertiesManagerImpl(Weblogger roller, JPAPersistenceStrategy stra this.roller = roller; this.strategy = strategy; } - - + + /** * @inheritDoc */ public void initialize() throws InitializationException { - + Map props = null; try { props = this.getProperties(); @@ -91,10 +91,10 @@ public void initialize() throws InitializationException { "Please check that the database has been upgraded!", e); throw new RuntimeException(e); } - + } - - + + /** * Retrieve a single property by name. */ @@ -106,7 +106,7 @@ public RuntimeConfigProperty getProperty(String name) throws WebloggerException /** * Retrieve all properties. - * + * * Properties are returned in a Map to make them easy to lookup. The Map * uses the property name as the key and the RuntimeConfigProperty object * as the value. @@ -135,7 +135,7 @@ public Map getProperties() throws WebloggerException { /** * Save a single property. */ - public void saveProperty(RuntimeConfigProperty property) + public void saveProperty(RuntimeConfigProperty property) throws WebloggerException { this.strategy.store(property); } @@ -152,7 +152,7 @@ public void saveProperties(Map properties) throws WebloggerException { this.strategy.store((RuntimeConfigProperty) props.next()); } } - + /** * This method compares the property definitions in the RuntimeConfigDefs @@ -201,7 +201,7 @@ private Map initializeMissingProps(Map props) { log.info("Found uninitialized property " + propDef.getName() + - " ... setting value to [" + + " ... setting value to [" + propDef.getDefaultValue() + "]"); } } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPARefererManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPARefererManagerImpl.java index fefcbc5c3b..4427f46770 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPARefererManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPARefererManagerImpl.java @@ -55,14 +55,14 @@ public class JPARefererManagerImpl implements RefererManager { protected static final String DAYHITS = "dayHits"; protected static final String TOTALHITS = "totalHits"; - - private static final Comparator statCountCountReverseComparator = + + private static final Comparator statCountCountReverseComparator = Collections.reverseOrder(StatCountCountComparator.getInstance()); - + /** The strategy for this manager. */ private final Weblogger roller; private final JPAPersistenceStrategy strategy; - + /** * Creates a new instance of JPARefererManagerImpl @@ -74,7 +74,7 @@ protected JPARefererManagerImpl(Weblogger roller, JPAPersistenceStrategy strateg this.strategy = strategy; } - + public void saveReferer(WeblogReferrer referer) throws WebloggerException { strategy.store(referer); } @@ -124,7 +124,7 @@ public void applyRefererFilters(Weblog website) throws WebloggerException { if (null == website) throw new WebloggerException("website is null"); if (null == website.getBlacklist()) return; - + String[] blacklist = StringUtils.split( StringUtils.deleteWhitespace(website.getBlacklist()),","); if (blacklist.length == 0) return; @@ -138,7 +138,7 @@ public void applyRefererFilters(Weblog website) protected List getExistingReferers(Weblog website, String dateString, String permalink) throws WebloggerException { - Query q = strategy.getNamedQuery( + Query q = strategy.getNamedQuery( "WeblogReferrer.getByWebsite&DateString&RefererPermalink"); q.setParameter(1, website); q.setParameter(2, dateString); @@ -149,7 +149,7 @@ protected List getExistingReferers(Weblog website, String dateString, protected List getMatchingReferers(Weblog website, String requestUrl, String refererUrl) throws WebloggerException { - Query q = strategy.getNamedQuery( + Query q = strategy.getNamedQuery( "WeblogReferrer.getByWebsite&RequestUrl&RefererUrl"); q.setParameter(1, website); q.setParameter(2, requestUrl); @@ -167,21 +167,21 @@ protected List getMatchingReferers(Weblog website, String requestUrl, */ public List getHotWeblogs(int sinceDays, int offset, int length) throws WebloggerException { - + String msg = "Getting hot weblogs"; List results = new ArrayList(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -1 * sinceDays); Date startDate = cal.getTime(); - + if (length == -1) { length = Integer.MAX_VALUE - offset; } - Query q = strategy.getNamedQuery( + Query q = strategy.getNamedQuery( "WeblogReferrer.getHotWeblogsByWebsite.enabled&Website.active&Website.lastModifiedGreater"); - + if (offset != 0 || length != -1) { q.setFirstResult(offset); q.setMaxResults(length); @@ -202,7 +202,7 @@ public List getHotWeblogs(int sinceDays, int offset, int length) websiteHandle, websiteName, "statCount.weblogDayHits", - hits)); + hits)); } // Original query ordered by desc hits. // JPA QL doesn't allow queries to be ordered by agregates; do it in memory @@ -211,14 +211,14 @@ public List getHotWeblogs(int sinceDays, int offset, int length) return results; } - protected int getHits(Weblog website, String type) + protected int getHits(Weblog website, String type) throws WebloggerException { int hits = -1; if (log.isDebugEnabled()) { log.debug("getHits: " + website.getName()); } //TODO: JPAPort. This query retrieves both SUM(r.dayHits), SUM(r.totalHits) - //The method only comsumes one of them. We can optimize the logic to retrieve only the + //The method only comsumes one of them. We can optimize the logic to retrieve only the //requied SUM Query query = strategy.getNamedQuery( "WeblogReferrer.getHitsByWebsite.enabled&Website.id"); @@ -227,7 +227,7 @@ protected int getHits(Weblog website, String type) List results = query.getResultList(); Object[] resultsArray = (Object[]) results.get(0); - + if (resultsArray.length > 0 && type.equals(DAYHITS)) { if ( resultsArray[0] != null ) { hits = ((Long) resultsArray[0]).intValue(); @@ -239,7 +239,7 @@ protected int getHits(Weblog website, String type) } else { hits = 0; } - + return hits; } @@ -279,10 +279,10 @@ public List getReferersToDate(Weblog website, String date) if (website==null ) throw new WebloggerException("website is null"); - + if (date==null ) throw new WebloggerException("Date is null"); - + Query q = strategy.getNamedQuery( "WeblogReferrer.getByWebsite&DateString&DuplicateOrderByTotalHitsDesc"); q.setParameter(1, website); @@ -315,7 +315,7 @@ public List getReferersToEntry(String entryid) throws WebloggerException { */ protected List getReferersToWebsite(Weblog website, String refererUrl) throws WebloggerException { - Query q = strategy.getNamedQuery( + Query q = strategy.getNamedQuery( "WeblogReferrer.getByWebsite&RefererUrl"); q.setParameter(1, website); q.setParameter(2, refererUrl); @@ -330,7 +330,7 @@ protected List getReferersWithSameTitle(Weblog website, String title, String excerpt) throws WebloggerException { - Query q = strategy.getNamedQuery( + Query q = strategy.getNamedQuery( "WeblogReferrer.getByWebsite&RequestURL&TitleOrExcerpt"); q.setParameter(1, website); q.setParameter(2, requestUrl); @@ -416,7 +416,7 @@ public void processReferrer(String requestUrl, String referrerUrl, secondTryUrl = "http://www"+referrerUrl.substring(7); } - matchRef = getMatchingReferers(weblog, requestUrl, + matchRef = getMatchingReferers(weblog, requestUrl, secondTryUrl); if ( matchRef.size() == 1 ) { referrerUrl = secondTryUrl; @@ -623,12 +623,12 @@ public void run() { } } - + /** * Release all resources held by manager. */ public void release() {} - + protected void clearDayHits() throws WebloggerException { Query query = strategy.getNamedUpdate("WeblogReferrer.clearDayHits"); query.executeUpdate(); @@ -647,7 +647,7 @@ protected List getBlackListedReferer(String[] blacklist) throws return (List) query.getResultList(); } - protected List getBlackListedReferer(Weblog website, String[] blacklist) + protected List getBlackListedReferer(Weblog website, String[] blacklist) throws WebloggerException { StringBuffer queryString = getQueryStringForBlackList(blacklist); queryString.append(" AND r.website = ?1 "); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAThreadManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAThreadManagerImpl.java index 03d3c73138..e4f0b3a11b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAThreadManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAThreadManagerImpl.java @@ -63,12 +63,12 @@ protected JPAThreadManagerImpl(Weblogger roller, JPAPersistenceStrategy strat) { */ @Override public boolean registerLease(RollerTask task) { - + log.debug("Attempting to register lease for task - "+task.getName()); - + // keep a copy of the current time Date currentTime = new Date(); - + // query for existing lease record first TaskLock taskLock = null; try { @@ -85,7 +85,7 @@ public boolean registerLease(RollerTask task) { if(taskLock != null) try { // calculate lease expiration time Date leaseExpiration = taskLock.getLeaseExpiration(); - + // calculate run time for task, this is expected time, not actual time // i.e. if a task is meant to run daily at midnight this should // reflect 00:00:00 on the current day @@ -100,7 +100,7 @@ public boolean registerLease(RollerTask task) { // start of this minute runTime = DateUtil.getStartOfMinute(currentTime); } - + if(log.isDebugEnabled()) { log.debug("last run = "+taskLock.getLastRun()); log.debug("new run time = "+runTime); @@ -118,7 +118,7 @@ public boolean registerLease(RollerTask task) { q.setParameter(5, taskLock.getTimeAquired()); q.setParameter(6, new Timestamp(leaseExpiration.getTime())); int result = q.executeUpdate(); - + if(result == 1) { strategy.flush(); return true; @@ -165,7 +165,7 @@ public boolean unregisterLease(RollerTask task) { q.setParameter(2, task.getName()); q.setParameter(3, task.getClientId()); int result = q.executeUpdate(); - + if(result == 1) { strategy.flush(); return true; @@ -183,8 +183,8 @@ public boolean unregisterLease(RollerTask task) { return false; } - - + + /** * @inheritDoc */ @@ -199,7 +199,7 @@ public TaskLock getTaskLockByName(String name) throws WebloggerException { } } - + /** * @inheritDoc */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java index 916a4eadc7..81c3ff39b5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java @@ -44,10 +44,10 @@ public class JPAUserManagerImpl implements UserManager { private static Log log = LogFactory.getLog(JPAUserManagerImpl.class); private final JPAPersistenceStrategy strategy; - + // cached mapping of userNames -> userIds private Map userNameToIdMap = new Hashtable(); - + @com.google.inject.Inject protected JPAUserManagerImpl(JPAPersistenceStrategy strat) { @@ -57,18 +57,18 @@ protected JPAUserManagerImpl(JPAPersistenceStrategy strat) { public void release() {} - - + + //--------------------------------------------------------------- user CRUD - + public void saveUser(User data) throws WebloggerException { this.strategy.store(data); } - + public void removeUser(User user) throws WebloggerException { String userName = user.getUserName(); - + // remove permissions, maintaining both sides of relationship List perms = getWeblogPermissions(user); for (WeblogPermission perm : perms) { @@ -78,7 +78,7 @@ public void removeUser(User user) throws WebloggerException { // remove entry from cache mapping this.userNameToIdMap.remove(userName); - + // remove all associated attributes List atts = getUserAttributes(userName); for (UserAttribute att : atts) { @@ -86,12 +86,12 @@ public void removeUser(User user) throws WebloggerException { } } - + public void addUser(User newUser) throws WebloggerException { if(newUser == null) throw new WebloggerException("cannot add null user"); - + // TODO BACKEND: we must do this in a better fashion, like getUserCnt()? boolean adminUser = false; List existingUsers = this.getUsers(Boolean.TRUE, null, null, 0, 1); @@ -100,7 +100,7 @@ public void addUser(User newUser) throws WebloggerException { // Make first user an admin adminUser = true; - //if user was disabled (because of activation user + //if user was disabled (because of activation user // account with e-mail property), enable it for admin user newUser.setEnabled(Boolean.TRUE); newUser.setActivationCode(null); @@ -119,25 +119,25 @@ public void addUser(User newUser) throws WebloggerException { } } - + public User getUser(String id) throws WebloggerException { return (User)this.strategy.load(User.class, id); } - + //------------------------------------------------------------ user queries public User getUserByUserName(String userName) throws WebloggerException { return getUserByUserName(userName, Boolean.TRUE); } - + public User getUserByUserName(String userName, Boolean enabled) throws WebloggerException { if (userName==null ) throw new WebloggerException("userName cannot be null"); - + // check cache first // NOTE: if we ever allow changing usernames then this needs updating if(this.userNameToIdMap.containsKey(userName)) { @@ -254,12 +254,12 @@ public List getUsers(Weblog weblog, Boolean enabled, Date startDate, return query.getResultList(); } - + public List getUsers(int offset, int length) throws WebloggerException { return getUsers(Boolean.TRUE, null, null, offset, length); } - + public List getUsers(Boolean enabled, Date startDate, Date endDate, int offset, int length) throws WebloggerException { @@ -268,7 +268,7 @@ public List getUsers(Boolean enabled, Date startDate, Date endDate, boolean setRange = offset != 0 || length != -1; if (endDate == null) endDate = new Date(); - + if (enabled != null) { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); @@ -309,7 +309,7 @@ public List getUsers(Boolean enabled, Date startDate, Date endDate, return query.getResultList(); } - + /** * Get users of a website */ @@ -348,7 +348,7 @@ public List getUsers(Weblog website, Boolean enabled, int offset, int length) th return query.getResultList(); } - + public List getUsersStartingWith(String startsWith, Boolean enabled, int offset, int length) throws WebloggerException { Query query = null; @@ -383,7 +383,7 @@ public List getUsersStartingWith(String startsWith, Boolean enabled, return query.getResultList(); } - + public Map getUserNameLetterMap() throws WebloggerException { String lc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Map results = new TreeMap(); @@ -399,7 +399,7 @@ public Map getUserNameLetterMap() throws WebloggerException { return results; } - + public List getUsersByLetter(char letter, int offset, int length) throws WebloggerException { Query query = strategy.getNamedQuery( @@ -414,7 +414,7 @@ public List getUsersByLetter(char letter, int offset, int length) return query.getResultList(); } - + /** * Get count of users, enabled only */ @@ -423,19 +423,19 @@ public long getUserCount() throws WebloggerException { Query q = strategy.getNamedQuery("User.getCountEnabledDistinct"); q.setParameter(1, Boolean.TRUE); List results = q.getResultList(); - ret =((Long)results.get(0)).longValue(); + ret =((Long)results.get(0)).longValue(); return ret; } - + public User getUserByAttribute(String name, String value) throws WebloggerException { return getUserByAttribute(name, value, Boolean.TRUE); } - + public User getUserByAttribute(String name, String value, Boolean enabled) throws WebloggerException { - + if (value == null) { throw new WebloggerException("user attribute cannot be null!"); } @@ -476,30 +476,30 @@ public User getUserByAttribute(String name, String value, Boolean enabled) throw return user; } - + public UserAttribute getUserAttribute(String userName, String attribute) throws WebloggerException { Query q = strategy.getNamedQuery("UserAttribute.getByUserNameAndAttrName"); q.setParameter(1, userName); q.setParameter(2, attribute); try { return (UserAttribute) q.getSingleResult(); - } catch (NoResultException e) { + } catch (NoResultException e) { return null; } } - + public List getUserAttributes(String userName) throws WebloggerException { Query q = strategy.getNamedQuery("UserAttribute.getByUserName"); q.setParameter(1, userName); try { return (List)q.getResultList(); - } catch (NoResultException e) { + } catch (NoResultException e) { return null; } } - + public void setUserAttribute(String userName, String attribute, String value) throws WebloggerException { UserAttribute userAttribute = null; Query q = strategy.getNamedQuery("UserAttribute.getByUserNameAndAttrName"); @@ -522,7 +522,7 @@ public void setUserAttribute(String userName, String attribute, String value) th } } - + public User getUserByActivationCode(String activationCode) throws WebloggerException { if (activationCode == null) { throw new WebloggerException("activationcode is null"); @@ -535,10 +535,10 @@ public User getUserByActivationCode(String activationCode) throws WebloggerExcep return null; } } - - + + //-------------------------------------------------------- permissions CRUD - + public boolean checkPermission(RollerPermission perm, User user) throws WebloggerException { RollerPermission existingPerm = null; @@ -548,21 +548,21 @@ public boolean checkPermission(RollerPermission perm, User user) throws Weblogge WeblogPermission permToCheck = (WeblogPermission)perm; try { existingPerm = getWeblogPermission(permToCheck.getWeblog(), user); - } catch (WebloggerException ignored) {} + } catch (WebloggerException ignored) {} } - if (existingPerm != null && existingPerm.implies(perm)) return true; - + if (existingPerm != null && existingPerm.implies(perm)) return true; + // user has no existing perm in a weblog, so try his global perms GlobalPermission globalPerm = new GlobalPermission(user); if (globalPerm.implies(perm)) return true; - + if (log.isDebugEnabled()) { log.debug("PERM CHECK FAILED: user "+user.getUserName()+" does not have " + perm.toString()); } return false; } - + public WeblogPermission getWeblogPermission(Weblog weblog, User user) throws WebloggerException { Query q = strategy.getNamedQuery("WeblogPermission.getByUserName&WeblogId&NotPending"); q.setParameter(1, user.getUserName()); @@ -574,7 +574,7 @@ public WeblogPermission getWeblogPermission(Weblog weblog, User user) throws Web } } - + public void grantWeblogPermission(Weblog weblog, User user, List actions) throws WebloggerException { // first, see if user already has a permission for the specified object @@ -597,7 +597,7 @@ public void grantWeblogPermission(Weblog weblog, User user, List actions } } - + public void grantWeblogPermissionPending(Weblog weblog, User user, List actions) throws WebloggerException { // first, see if user already has a permission for the specified object @@ -609,7 +609,7 @@ public void grantWeblogPermissionPending(Weblog weblog, User user, List existingPerm = (WeblogPermission)q.getSingleResult(); } catch (NoResultException ignored) {} - // permission already exists, so complain + // permission already exists, so complain if (existingPerm != null) { throw new WebloggerException("Cannot make existing permission into pending permission"); @@ -621,7 +621,7 @@ public void grantWeblogPermissionPending(Weblog weblog, User user, List } } - + public void confirmWeblogPermission(Weblog weblog, User user) throws WebloggerException { // get specified permission @@ -640,7 +640,7 @@ public void confirmWeblogPermission(Weblog weblog, User user) throws WebloggerEx this.strategy.store(existingPerm); } - + public void declineWeblogPermission(Weblog weblog, User user) throws WebloggerException { // get specified permission @@ -657,7 +657,7 @@ public void declineWeblogPermission(Weblog weblog, User user) throws WebloggerEx this.strategy.remove(existingPerm); } - + public void revokeWeblogPermission(Weblog weblog, User user, List actions) throws WebloggerException { // get specified permission @@ -683,21 +683,21 @@ public void revokeWeblogPermission(Weblog weblog, User user, List action } } - + public List getWeblogPermissions(User user) throws WebloggerException { Query q = strategy.getNamedQuery("WeblogPermission.getByUserName"); q.setParameter(1, user.getUserName()); return (List)q.getResultList(); } - + public List getWeblogPermissions(Weblog weblog) throws WebloggerException { Query q = strategy.getNamedQuery("WeblogPermission.getByWeblogId"); q.setParameter(1, weblog.getHandle()); return (List)q.getResultList(); } - + public List getWeblogPermissionsPending(User user) throws WebloggerException { Query q = strategy.getNamedQuery("WeblogPermission.getByUserName&Pending"); q.setParameter(1, user.getUserName()); @@ -711,10 +711,10 @@ public List getWeblogPermissionsPending(Weblog weblog) throws return (List)q.getResultList(); } - + //-------------------------------------------------------------- role CRUD - - + + /** * Returns true if user has role specified. */ @@ -730,7 +730,7 @@ public boolean hasRole(String roleName, User user) throws WebloggerException { return true; } - + /** * Get all of user's roles. */ @@ -757,7 +757,7 @@ public void grantRole(String roleName, User user) throws WebloggerException { } } - + public void revokeRole(String roleName, User user) throws WebloggerException { Query q = strategy.getNamedQuery("UserRole.getByUserNameAndRole"); q.setParameter(1, user.getUserName()); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogEntryManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogEntryManagerImpl.java index 01f1619e5c..354f079113 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogEntryManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogEntryManagerImpl.java @@ -67,35 +67,35 @@ */ @com.google.inject.Singleton public class JPAWeblogEntryManagerImpl implements WeblogEntryManager { - + protected static Log log = LogFactory.getLog( JPAWeblogEntryManagerImpl.class); - + private final Weblogger roller; private final JPAPersistenceStrategy strategy; - + // cached mapping of entryAnchors -> entryIds private Hashtable entryAnchorToIdMap = new Hashtable(); - + /* inline creation of reverse comparator, anonymous inner class */ private static final Comparator reverseComparator = new ReverseComparator(); - + private static final Comparator tagStatNameComparator = new TagStatComparator(); - + private static final Comparator tagStatCountReverseComparator = Collections.reverseOrder(TagStatCountComparator.getInstance()); - + private static final Comparator statCountCountReverseComparator = Collections.reverseOrder(StatCountCountComparator.getInstance()); - - + + @com.google.inject.Inject protected JPAWeblogEntryManagerImpl(Weblogger roller, JPAPersistenceStrategy strategy) { log.debug("Instantiating JPA Weblog Manager"); this.roller = roller; this.strategy = strategy; } - + /** * @inheritDoc */ @@ -112,12 +112,12 @@ public void saveWeblogCategory(WeblogCategory cat) throws WebloggerException { parent.getWeblogCategories().add(cat); } } - + // update weblog last modified date. date updated by saveWebsite() - roller.getWeblogManager().saveWeblog(cat.getWebsite()); + roller.getWeblogManager().saveWeblog(cat.getWebsite()); this.strategy.store(cat); } - + /** * @inheritDoc */ @@ -126,7 +126,7 @@ public void removeWeblogCategory(WeblogCategory cat) if(cat.retrieveWeblogEntries(true).size() > 0) { throw new WebloggerException("Cannot remove category with entries"); } - + // remove cat this.strategy.remove(cat); //relationship management for the other side @@ -134,74 +134,74 @@ public void removeWeblogCategory(WeblogCategory cat) if(parent != null) { parent.getWeblogCategories().remove(cat); } - + // update website default cats if needed if(cat.getWebsite().getBloggerCategory().equals(cat)) { WeblogCategory rootCat = this.getRootWeblogCategory(cat.getWebsite()); cat.getWebsite().setBloggerCategory(rootCat); this.strategy.store(cat.getWebsite()); } - + if(cat.getWebsite().getDefaultCategory().equals(cat)) { WeblogCategory rootCat = this.getRootWeblogCategory(cat.getWebsite()); cat.getWebsite().setDefaultCategory(rootCat); this.strategy.store(cat.getWebsite()); } - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog( cat.getWebsite()); } - + /** * @inheritDoc */ public void moveWeblogCategory(WeblogCategory srcCat, WeblogCategory destCat) throws WebloggerException { - + // TODO: this check should be made before calling this method? if (destCat.descendentOf(srcCat)) { throw new WebloggerException( "ERROR cannot move parent category into it's own child"); } - + log.debug("Moving category "+srcCat.getPath() + " under "+destCat.getPath()); - - + + WeblogCategory oldParent = srcCat.getParent(); if(oldParent != null) { oldParent.getWeblogCategories().remove(srcCat); } srcCat.setParent(destCat); destCat.getWeblogCategories().add(srcCat); - + if("/".equals(destCat.getPath())) { srcCat.setPath("/"+srcCat.getName()); } else { srcCat.setPath(destCat.getPath() + "/" + srcCat.getName()); } saveWeblogCategory(srcCat); - + // the main work to be done for a category move is to update the // path attribute of the category and all descendent categories updatePathTree(srcCat); } - - + + // updates the paths of all descendents of the given category private void updatePathTree(WeblogCategory cat) throws WebloggerException { - + log.debug("Updating path tree for category "+cat.getPath()); - + WeblogCategory childCat = null; Iterator childCats = cat.getWeblogCategories().iterator(); while(childCats.hasNext()) { childCat = (WeblogCategory) childCats.next(); - + log.debug("OLD child category path was "+childCat.getPath()); - + // update path and save if("/".equals(cat.getPath())) { childCat.setPath("/" + childCat.getName()); @@ -209,30 +209,30 @@ private void updatePathTree(WeblogCategory cat) childCat.setPath(cat.getPath() + "/" + childCat.getName()); } saveWeblogCategory(childCat); - + log.debug("NEW child category path is "+ childCat.getPath()); - + // then make recursive call to update this cats children updatePathTree(childCat); } } - + /** * @inheritDoc */ public void moveWeblogCategoryContents(WeblogCategory srcCat, WeblogCategory destCat) throws WebloggerException { - + // TODO: this check should be made before calling this method? if (destCat.descendentOf(srcCat)) { throw new WebloggerException( "ERROR cannot move parent category into it's own child"); } - + // get all entries in category and subcats List results = srcCat.retrieveWeblogEntries(true); - + // Loop through entries in src cat, assign them to dest cat Iterator iter = results.iterator(); Weblog website = destCat.getWebsite(); @@ -242,17 +242,17 @@ public void moveWeblogCategoryContents(WeblogCategory srcCat, entry.setWebsite(website); this.strategy.store(entry); } - + // Make sure website's default and bloggerapi categories // are valid after the move - + if (srcCat.getWebsite().getDefaultCategory().getId() .equals(srcCat.getId()) || srcCat.getWebsite().getDefaultCategory().descendentOf(srcCat)) { srcCat.getWebsite().setDefaultCategory(destCat); this.strategy.store(srcCat.getWebsite()); } - + if (srcCat.getWebsite().getBloggerCategory().getId() .equals(srcCat.getId()) || srcCat.getWebsite().getBloggerCategory().descendentOf(srcCat)) { @@ -260,27 +260,27 @@ public void moveWeblogCategoryContents(WeblogCategory srcCat, this.strategy.store(srcCat.getWebsite()); } } - + /** * @inheritDoc */ public void saveComment(WeblogEntryComment comment) throws WebloggerException { this.strategy.store(comment); - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog(comment.getWeblogEntry().getWebsite()); } - + /** * @inheritDoc */ public void removeComment(WeblogEntryComment comment) throws WebloggerException { this.strategy.remove(comment); - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog(comment.getWeblogEntry().getWebsite()); } - + /** * @inheritDoc */ @@ -303,21 +303,21 @@ public void saveWeblogEntry(WeblogEntry entry) throws WebloggerException { if (entry.getLocale() == null) { entry.setLocale(entry.getWebsite().getLocale()); } - + if (entry.getAnchor() == null || entry.getAnchor().trim().equals("")) { entry.setAnchor(this.createAnchor(entry)); } - + for(Iterator it = entry.getAddedTags().iterator(); it.hasNext();) { String name = (String) it.next(); updateTagCount(name, entry.getWebsite(), 1); } - + for(Iterator it = entry.getRemovedTags().iterator(); it.hasNext();) { String name = (String) it.next(); updateTagCount(name, entry.getWebsite(), -1); } - + // if the entry was published to future, set status as SCHEDULED // we only consider an entry future published if it is scheduled // more than 1 minute into the future @@ -325,29 +325,29 @@ public void saveWeblogEntry(WeblogEntry entry) throws WebloggerException { entry.getPubTime().after(new Date(System.currentTimeMillis() + 60000))) { entry.setStatus(WeblogEntry.SCHEDULED); } - + // Store value object (creates new or updates existing) entry.setUpdateTime(new Timestamp(new Date().getTime())); - + this.strategy.store(entry); - + // update weblog last modified date. date updated by saveWebsite() if(entry.isPublished()) { roller.getWeblogManager().saveWeblog(entry.getWebsite()); } - + if(entry.isPublished()) { // Queue applicable pings for this update. roller.getAutopingManager().queueApplicableAutoPings(entry); } } - + /** * @inheritDoc */ public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException { Weblog weblog = entry.getWebsite(); - + Query q = strategy.getNamedQuery("WeblogReferrer.getByWeblogEntry"); q.setParameter(1, entry); List referers = q.getResultList(); @@ -355,7 +355,7 @@ public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException { WeblogReferrer referer = (WeblogReferrer) iter.next(); this.strategy.remove(referer); } - + // remove comments List comments = getComments( null, // website @@ -371,7 +371,7 @@ public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException { while (commentsIT.hasNext()) { this.strategy.remove((WeblogEntryComment) commentsIT.next()); } - + // remove tags aggregates if (entry.getTags() != null) { for(Iterator it = entry.getTags().iterator(); it.hasNext(); ) { @@ -381,7 +381,7 @@ public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException { this.strategy.remove(tag); } } - + // remove attributes if (entry.getEntryAttributes() != null) { for (Iterator it = entry.getEntryAttributes().iterator(); it.hasNext(); ) { @@ -392,43 +392,43 @@ public void removeWeblogEntry(WeblogEntry entry) throws WebloggerException { } // TODO: can we eliminate this unnecessary flush with OpenJPA 1.0 this.strategy.flush(); - + // remove entry this.strategy.remove(entry); - + // update weblog last modified date. date updated by saveWebsite() if (entry.isPublished()) { roller.getWeblogManager().saveWeblog(weblog); } - + // remove entry from cache mapping this.entryAnchorToIdMap.remove(entry.getWebsite().getHandle()+":"+entry.getAnchor()); } - + public List getNextPrevEntries(WeblogEntry current, String catName, String locale, int maxEntries, boolean next) throws WebloggerException { Query query = null; List results = null; WeblogCategory category = null; - + if (catName != null && !catName.trim().equals("/")) { category = getWeblogCategoryByPath(current.getWebsite(), null, catName); } - + List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); StringBuffer whereClause = new StringBuffer(); queryString.append("SELECT e FROM WeblogEntry e WHERE "); - + params.add(size++, current.getWebsite()); - whereClause.append("e.website = ?" + size); - + whereClause.append("e.website = ?" + size); + params.add(size++, WeblogEntry.PUBLISHED); whereClause.append(" AND e.status = ?" + size); - + if (next) { params.add(size++, current.getPubTime()); whereClause.append(" AND e.pubTime > ?" + size); @@ -436,7 +436,7 @@ public List getNextPrevEntries(WeblogEntry current, String catName, params.add(size++, current.getPubTime()); whereClause.append(" AND e.pubTime < ?" + size); } - + if (catName != null && !catName.trim().equals("/")) { category = getWeblogCategoryByPath(current.getWebsite(), catName); if (category != null) { @@ -444,14 +444,14 @@ public List getNextPrevEntries(WeblogEntry current, String catName, whereClause.append(" AND e.category = ?" + size); } else { throw new WebloggerException("Cannot find category: " + catName); - } + } } - + if(locale != null) { params.add(size++, locale + '%'); whereClause.append(" AND e.locale like ?" + size); } - + if (next) { whereClause.append(" ORDER BY e.pubTime ASC"); } else { @@ -462,10 +462,10 @@ public List getNextPrevEntries(WeblogEntry current, String catName, query.setParameter(i+1, params.get(i)); } query.setMaxResults(maxEntries); - + return query.getResultList(); } - + /** * @inheritDoc */ @@ -473,7 +473,7 @@ public WeblogCategory getRootWeblogCategory(Weblog website) throws WebloggerException { if (website == null) throw new WebloggerException("website is null"); - + Query q = strategy.getNamedQuery( "WeblogCategory.getByWebsite&ParentNull"); q.setParameter(1, website); @@ -483,7 +483,7 @@ public WeblogCategory getRootWeblogCategory(Weblog website) return null; } } - + /** * @inheritDoc */ @@ -491,15 +491,15 @@ public List getWeblogCategories(Weblog website, boolean includeRoot) throws WebloggerException { if (website == null) throw new WebloggerException("website is null"); - + if (includeRoot) return getWeblogCategories(website); - + Query q = strategy.getNamedQuery( "WeblogCategory.getByWebsite&ParentNotNull"); q.setParameter(1, website); return q.getResultList(); } - + /** * @inheritDoc */ @@ -507,13 +507,13 @@ public List getWeblogCategories(Weblog website) throws WebloggerException { if (website == null) throw new WebloggerException("website is null"); - + Query q = strategy.getNamedQuery( "WeblogCategory.getByWebsite"); q.setParameter(1, website); return q.getResultList(); } - + /** * @inheritDoc */ @@ -531,7 +531,7 @@ public List getWeblogEntries( String locale, int offset, int length) throws WebloggerException { - + WeblogCategory cat = null; if (StringUtils.isNotEmpty(catName) && website != null) { cat = getWeblogCategoryByPath(website, catName); @@ -540,11 +540,11 @@ public List getWeblogEntries( if (catName != null && catName.trim().equals("/")) { catName = null; } - + List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); - + //queryString.append("SELECT e FROM WeblogEntry e WHERE "); if (tags == null || tags.size()==0) { queryString.append("SELECT e FROM WeblogEntry e WHERE "); @@ -554,11 +554,11 @@ public List getWeblogEntries( for(int i = 0; i < tags.size(); i++) { if (i != 0) queryString.append(" OR "); params.add(size++, tags.get(i)); - queryString.append(" t.name = ?").append(size); + queryString.append(" t.name = ?").append(size); } queryString.append(") AND "); } - + if (website != null) { params.add(size++, website.getId()); queryString.append("e.website.id = ?").append(size); @@ -566,7 +566,7 @@ public List getWeblogEntries( params.add(size++, Boolean.TRUE); queryString.append("e.website.enabled = ?").append(size); } - + /*if (tags != null && tags.size() > 0) { // A JOIN with WeblogEntryTag in parent quert will cause a DISTINCT in SELECT clause // WeblogEntry has a clob field and many databases do not link DISTINCT for CLOB fields @@ -590,34 +590,34 @@ public List getWeblogEntries( params.add(size++, user.getUserName()); queryString.append(" AND e.creatorUserName = ?").append(size); } - + if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); params.add(size++, start); queryString.append(" AND e.pubTime >= ?").append(size); } - + if (endDate != null) { Timestamp end = new Timestamp(endDate.getTime()); params.add(size++, end); queryString.append(" AND e.pubTime <= ?").append(size); } - + if (cat != null && website != null) { params.add(size++, cat.getId()); queryString.append(" AND e.category.id = ?").append(size); } - + if (status != null) { params.add(size++, status); queryString.append(" AND e.status = ?").append(size); } - + if (locale != null) { params.add(size++, locale + '%'); queryString.append(" AND e.locale like ?").append(size); } - + if (text != null) { params.add(size++, '%' + text + '%'); queryString.append(" AND ( e.text LIKE ?").append(size); @@ -625,35 +625,35 @@ public List getWeblogEntries( queryString.append(" OR e.title LIKE ?").append(size); queryString.append(") "); } - + if (sortby != null && sortby.equals("updateTime")) { queryString.append(" ORDER BY e.updateTime "); } else { queryString.append(" ORDER BY e.pubTime "); } - + if (sortOrder != null && sortOrder.equals(ASCENDING)) { queryString.append("ASC "); } else { queryString.append("DESC "); } - - + + Query query = strategy.getDynamicQuery(queryString.toString()); for (int i=0; i 0) { name = base + count; } - + Query q = strategy.getNamedQuery( "WeblogEntry.getByWebsite&Anchor"); q.setParameter(1, entry.getWebsite()); q.setParameter(2, name); List results = q.getResultList(); - + if (results.size() < 1) { break; } else { @@ -811,37 +811,37 @@ public String createAnchor(WeblogEntry entry) throws WebloggerException { } return name; } - + /** * @inheritDoc */ public boolean isDuplicateWeblogCategoryName(WeblogCategory cat) throws WebloggerException { - + // ensure that no sibling categories share the same name WeblogCategory parent = cat.getParent(); if (null != parent) { return (getWeblogCategoryByPath( cat.getWebsite(), cat.getPath()) != null); } - + return false; } - + /** * @inheritDoc */ public boolean isWeblogCategoryInUse(WeblogCategory cat) throws WebloggerException { - + Query q = strategy.getNamedQuery("WeblogEntry.getByCategory"); q.setParameter(1, cat); int entryCount = q.getResultList().size(); - + if (entryCount > 0) { return true; } - + Iterator cats = cat.getWeblogCategories().iterator(); while (cats.hasNext()) { WeblogCategory childCat = (WeblogCategory)cats.next(); @@ -849,18 +849,18 @@ public boolean isWeblogCategoryInUse(WeblogCategory cat) return true; } } - + if (cat.getWebsite().getBloggerCategory().equals(cat)) { return true; } - + if (cat.getWebsite().getDefaultCategory().equals(cat)) { return true; } - + return false; } - + /** * @inheritDoc */ @@ -874,12 +874,12 @@ public List getComments( boolean reverseChrono, int offset, int length) throws WebloggerException { - + List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); queryString.append("SELECT c FROM WeblogEntryComment c "); - + StringBuffer whereClause = new StringBuffer(); if (entry != null) { params.add(size++, entry); @@ -888,25 +888,25 @@ public List getComments( params.add(size++, website); whereClause.append("c.weblogEntry.website = ?").append(size); } - + if (searchString != null) { params.add(size++, "%" + searchString + "%"); appendConjuctionToWhereclause(whereClause, "(c.url LIKE ?") .append(size).append(" OR c.content LIKE ?").append(size).append(")"); } - + if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); params.add(size++, start); appendConjuctionToWhereclause(whereClause, "c.postTime >= ?").append(size); } - + if (endDate != null) { Timestamp end = new Timestamp(endDate.getTime()); params.add(size++, end); appendConjuctionToWhereclause(whereClause, "c.postTime <= ?").append(size); } - + if (status != null) { String comparisionOperator; if("ALL_IGNORE_SPAM".equals(status)) { @@ -921,7 +921,7 @@ public List getComments( appendConjuctionToWhereclause(whereClause, "c.status ") .append(comparisionOperator).append('?').append(size); } - + if(whereClause.length() != 0) { queryString.append(" WHERE ").append(whereClause); } @@ -930,7 +930,7 @@ public List getComments( } else { queryString.append(" ORDER BY c.postTime ASC"); } - + Query query = strategy.getDynamicQuery(queryString.toString()); if (offset != 0) { query.setFirstResult(offset); @@ -942,10 +942,10 @@ public List getComments( query.setParameter(i+1, params.get(i)); } return query.getResultList(); - + } - - + + /** * @inheritDoc */ @@ -956,11 +956,11 @@ public int removeMatchingComments( Date startDate, Date endDate, String status) throws WebloggerException { - + // TODO dynamic bulk delete query: I'd MUCH rather use a bulk delete, // but MySQL says "General error, message from server: "You can't // specify target table 'roller_comment' for update in FROM clause" - + List comments = getComments( website, entry, searchString, startDate, endDate, status, true, 0, -1); @@ -972,8 +972,8 @@ public int removeMatchingComments( } return count; } - - + + /** * @inheritDoc */ @@ -982,9 +982,9 @@ public WeblogCategory getWeblogCategory(String id) return (WeblogCategory) this.strategy.load( WeblogCategory.class, id); } - + //--------------------------------------------- WeblogCategory Queries - + /** * @inheritDoc */ @@ -992,24 +992,24 @@ public WeblogCategory getWeblogCategoryByPath(Weblog website, String categoryPath) throws WebloggerException { return getWeblogCategoryByPath(website, null, categoryPath); } - + /** * @inheritDoc */ // TODO: ditch this method in favor of getWeblogCategoryByPath(weblog, path) public WeblogCategory getWeblogCategoryByPath(Weblog website, WeblogCategory category, String path) throws WebloggerException { - + if (path == null || path.trim().equals("/")) { return getRootWeblogCategory(website); } else { String catPath = path; - + // all cat paths must begin with a '/' if(!catPath.startsWith("/")) { catPath = "/"+catPath; } - + // now just do simple lookup by path Query q = strategy.getNamedQuery( "WeblogCategory.getByPath&Website"); @@ -1022,21 +1022,21 @@ public WeblogCategory getWeblogCategoryByPath(Weblog website, } } } - + /** * @inheritDoc */ public WeblogEntryComment getComment(String id) throws WebloggerException { return (WeblogEntryComment) this.strategy.load(WeblogEntryComment.class, id); } - + /** * @inheritDoc */ public WeblogEntry getWeblogEntry(String id) throws WebloggerException { return (WeblogEntry)strategy.load(WeblogEntry.class, id); } - + /** * @inheritDoc */ @@ -1062,7 +1062,7 @@ public Map getWeblogEntryObjectMap( offset, length); } - + /** * @inheritDoc */ @@ -1089,7 +1089,7 @@ public Map getWeblogEntryStringMap( offset, length); } - + private Map getWeblogEntryMap( Weblog website, Date startDate, @@ -1101,10 +1101,10 @@ private Map getWeblogEntryMap( String locale, int offset, int length) throws WebloggerException { - + TreeMap map = new TreeMap(reverseComparator); - - List entries = getWeblogEntries( + + List entries = getWeblogEntries( website, null, // user startDate, @@ -1118,12 +1118,12 @@ private Map getWeblogEntryMap( locale, offset, length); - + Calendar cal = Calendar.getInstance(); if (website != null) { cal.setTimeZone(website.getTimeZoneInstance()); } - + SimpleDateFormat formatter = DateUtil.get8charDateFormat(); for (Iterator wbItr = entries.iterator(); wbItr.hasNext();) { WeblogEntry entry = (WeblogEntry) wbItr.next(); @@ -1142,7 +1142,7 @@ private Map getWeblogEntryMap( } return map; } - + /** * @inheritDoc */ @@ -1150,9 +1150,9 @@ public List getMostCommentedWeblogEntries(Weblog website, Date startDate, Date endDate, int offset, int length) throws WebloggerException { Query query = null; - List queryResults = null; + List queryResults = null; if (endDate == null) endDate = new Date(); - + if (website != null) { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); @@ -1206,10 +1206,10 @@ public List getMostCommentedWeblogEntries(Weblog website, // Original query ordered by desc count. // JPA QL doesn't allow queries to be ordered by agregates; do it in memory Collections.sort(results, statCountCountReverseComparator); - + return results; } - + /** * @inheritDoc */ @@ -1222,7 +1222,7 @@ public WeblogEntry getNextEntry(WeblogEntry current, } return entry; } - + /** * @inheritDoc */ @@ -1235,12 +1235,12 @@ public WeblogEntry getPreviousEntry(WeblogEntry current, } return entry; } - + /** * @inheritDoc */ public void release() {} - + /** * @inheritDoc */ @@ -1249,7 +1249,7 @@ public void applyCommentDefaultsToEntries(Weblog website) if (log.isDebugEnabled()) { log.debug("applyCommentDefaults"); } - + // TODO: Non-standard JPA bulk update, using parameter values in set clause Query q = strategy.getNamedUpdate( "WeblogEntry.updateAllowComments&CommentDaysByWebsite"); @@ -1258,7 +1258,7 @@ public void applyCommentDefaultsToEntries(Weblog website) q.setParameter(3, website); q.executeUpdate(); } - + /** * @inheritDoc */ @@ -1266,7 +1266,7 @@ public List getPopularTags(Weblog website, Date startDate, int offset, int limit throws WebloggerException { Query query = null; List queryResults = null; - + if (website != null) { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); @@ -1297,39 +1297,39 @@ public List getPopularTags(Weblog website, Date startDate, int offset, int limit query.setMaxResults(limit); } queryResults = query.getResultList(); - + double min = Integer.MAX_VALUE; double max = Integer.MIN_VALUE; - + List results = new ArrayList(limit); - + for (Iterator iter = queryResults.iterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); TagStat t = new TagStat(); t.setName((String) row[0]); t.setCount(((Number) row[1]).intValue()); - + min = Math.min(min, t.getCount()); max = Math.max(max, t.getCount()); results.add(t); } - + min = Math.log(1+min); max = Math.log(1+max); - + double range = Math.max(.01, max - min) * 1.0001; - + for (Iterator iter = results.iterator(); iter.hasNext(); ) { TagStat t = (TagStat) iter.next(); t.setIntensity((int) (1 + Math.floor(5 * (Math.log(1+t.getCount()) - min) / range))); } - + // sort results by name, because query had to sort by total Collections.sort(results, tagStatNameComparator); - + return results; } - + /** * @inheritDoc */ @@ -1338,24 +1338,24 @@ public List getTags(Weblog website, String sortBy, Query query = null; List queryResults = null; boolean sortByName = sortBy == null || !sortBy.equals("count"); - + List params = new ArrayList(); int size = 0; - StringBuffer queryString = new StringBuffer(); + StringBuffer queryString = new StringBuffer(); queryString.append("SELECT w.name, SUM(w.total) FROM WeblogEntryTagAggregate w WHERE "); - + if (website != null) { params.add(size++, website.getId()); queryString.append(" w.weblog.id = ?").append(size); } else { - queryString.append(" w.weblog IS NULL"); + queryString.append(" w.weblog IS NULL"); } - + if (startsWith != null && startsWith.length() > 0) { params.add(size++, startsWith + '%'); queryString.append(" AND w.name LIKE ?" + size); } - + if (sortBy != null && sortBy.equals("count")) { sortBy = "w.total DESC"; } else { @@ -1374,7 +1374,7 @@ public List getTags(Weblog website, String sortBy, query.setMaxResults(limit); } queryResults = query.getResultList(); - + List results = new ArrayList(); for (Iterator iter = queryResults.iterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); @@ -1384,26 +1384,26 @@ public List getTags(Weblog website, String sortBy, ce.setCount(((Long) row[1]).intValue()); results.add(ce); } - + if (sortByName) { Collections.sort(results, tagStatNameComparator); } else { Collections.sort(results, tagStatCountReverseComparator); } - + return results; } - - + + /** * @inheritDoc */ public boolean getTagComboExists(List tags, Weblog weblog) throws WebloggerException{ - + if(tags == null || tags.size() == 0) { return false; } - + StringBuffer queryString = new StringBuffer(); queryString.append("SELECT DISTINCT w.name "); queryString.append("FROM WeblogEntryTagAggregate w WHERE w.name IN ("); @@ -1417,32 +1417,32 @@ public boolean getTagComboExists(List tags, Weblog weblog) throws WebloggerExcep queryString.append('?').append(i+1).append(PARAM_SEPERATOR); params.add(tags.get(i)); } - + // Remove the trailing PARAM_SEPERATOR queryString.delete(queryString.length() - PARAM_SEPERATOR.length(), queryString.length()); // Close the brace of IN clause queryString.append(')'); - + if(weblog != null) { queryString.append(" AND w.weblog = ?").append(i+1); params.add(weblog); } else { queryString.append(" AND w.weblog IS NULL"); } - + Query q = strategy.getDynamicQuery(queryString.toString()); for (int j=0; j 0) { weblogTagData = new WeblogEntryTagAggregate(null, website, name, amount); weblogTagData.setLastUsed(lastUsed); strategy.store(weblogTagData); - + } else if (weblogTagData != null) { weblogTagData.setTotal(weblogTagData.getTotal() + amount); weblogTagData.setLastUsed(lastUsed); @@ -1501,13 +1501,13 @@ public void updateTagCount(String name, Weblog website, int amount) // update.setParameter(4, website); // update.executeUpdate(); } - + // create it only if we are going to need it. if (siteTagData == null && amount > 0) { siteTagData = new WeblogEntryTagAggregate(null, null, name, amount); siteTagData.setLastUsed(lastUsed); strategy.store(siteTagData); - + } else if(siteTagData != null) { siteTagData.setTotal(siteTagData.getTotal() + amount); siteTagData.setLastUsed(lastUsed); @@ -1519,23 +1519,23 @@ public void updateTagCount(String name, Weblog website, int amount) // update.setParameter(2, siteTagData.getName()); // update.executeUpdate(); } - + // delete all bad counts Query removeq = strategy.getNamedUpdate( "WeblogEntryTagAggregate.removeByTotalLessEqual"); removeq.setParameter(1, new Integer(0)); removeq.executeUpdate(); } - + /** * @inheritDoc */ public WeblogHitCount getHitCount(String id) throws WebloggerException { - + // do lookup return (WeblogHitCount) strategy.load(WeblogHitCount.class, id); } - + /** * @inheritDoc */ @@ -1549,23 +1549,23 @@ public WeblogHitCount getHitCountByWeblog(Weblog weblog) return null; } } - + /** * @inheritDoc */ public List getHotWeblogs(int sinceDays, int offset, int length) throws WebloggerException { - + // figure out start date Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -1 * sinceDays); Date startDate = cal.getTime(); - + Query query = strategy.getNamedQuery( "WeblogHitCount.getByWeblogEnabledTrueAndActiveTrue&DailyHitsGreaterThenZero&WeblogLastModifiedGreaterOrderByDailyHitsDesc"); query.setParameter(1, startDate); - + // Was commented out due to https://glassfish.dev.java.net/issues/show_bug.cgi?id=2084 // TODO: determine if this is still an issue. Is it a problem with other JPA implementations? if (offset != 0) { @@ -1573,41 +1573,41 @@ public List getHotWeblogs(int sinceDays, int offset, int length) } if (length != -1) { query.setMaxResults(length); - } + } return query.getResultList(); } - - + + /** * @inheritDoc */ public void saveHitCount(WeblogHitCount hitCount) throws WebloggerException { this.strategy.store(hitCount); } - - + + /** * @inheritDoc */ public void removeHitCount(WeblogHitCount hitCount) throws WebloggerException { this.strategy.remove(hitCount); } - - + + /** * @inheritDoc */ public void incrementHitCount(Weblog weblog, int amount) throws WebloggerException { - + if(amount == 0) { throw new WebloggerException("Tag increment amount cannot be zero."); } - + if(weblog == null) { throw new WebloggerException("Website cannot be NULL."); } - + Query q = strategy.getNamedQuery("WeblogHitCount.getByWeblog"); q.setParameter(1, weblog); WeblogHitCount hitCount = null; @@ -1616,7 +1616,7 @@ public void incrementHitCount(Weblog weblog, int amount) } catch (NoResultException e) { hitCount = null; } - + // create it if it doesn't exist if(hitCount == null && amount > 0) { hitCount = new WeblogHitCount(); @@ -1628,15 +1628,15 @@ public void incrementHitCount(Weblog weblog, int amount) strategy.store(hitCount); } } - + /** * @inheritDoc */ - public void resetAllHitCounts() throws WebloggerException { + public void resetAllHitCounts() throws WebloggerException { Query q = strategy.getNamedUpdate("WeblogHitCount.updateDailyHitCountZero"); q.executeUpdate(); } - + /** * @inheritDoc */ @@ -1650,10 +1650,10 @@ public void resetHitCount(Weblog weblog) throws WebloggerException { strategy.store(hitCount); } catch (NoResultException e) { // ignore: no hit count for weblog - } + } } - + /** * @inheritDoc */ @@ -1664,7 +1664,7 @@ public long getCommentCount() throws WebloggerException { List results = q.getResultList(); return ((Long)results.get(0)).longValue(); } - + /** * @inheritDoc */ @@ -1676,7 +1676,7 @@ public long getCommentCount(Weblog website) throws WebloggerException { List results = q.getResultList(); return ((Long)results.get(0)).longValue(); } - + /** * @inheritDoc */ @@ -1687,7 +1687,7 @@ public long getEntryCount() throws WebloggerException { List results = q.getResultList(); return ((Long)results.get(0)).longValue(); } - + /** * @inheritDoc */ @@ -1699,7 +1699,7 @@ public long getEntryCount(Weblog website) throws WebloggerException { List results = q.getResultList(); return ((Long)results.get(0)).longValue(); } - + /** * Appends given expression to given whereClause. If whereClause already * has other conditions, an " AND " is also appended before appending @@ -1715,5 +1715,5 @@ private static StringBuffer appendConjuctionToWhereclause(StringBuffer whereClau } return whereClause.append(expression); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java index 7af79ce7a4..af3f5b0277 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java @@ -71,71 +71,71 @@ */ @com.google.inject.Singleton public class JPAWeblogManagerImpl implements WeblogManager { - + /** The logger instance for this class. */ private static Log log = LogFactory.getLog(JPAWeblogManagerImpl.class); - + private static final Comparator statCountCountReverseComparator = Collections.reverseOrder(StatCountCountComparator.getInstance()); - + private final Weblogger roller; private final JPAPersistenceStrategy strategy; - + // cached mapping of weblogHandles -> weblogIds private Map weblogHandleToIdMap = new Hashtable(); - + // cached mapping of userNames -> userIds private Map userNameToIdMap = new Hashtable(); - - + + @com.google.inject.Inject protected JPAWeblogManagerImpl(Weblogger roller, JPAPersistenceStrategy strat) { log.debug("Instantiating JPA Weblog Manager"); this.roller = roller; this.strategy = strat; } - - + + public void release() {} - - + + /** * Update existing website. */ public void saveWeblog(Weblog website) throws WebloggerException { - + website.setLastModified(new java.util.Date()); strategy.store(website); } - + public void removeWeblog(Weblog weblog) throws WebloggerException { - + // remove contents first, then remove website this.removeWebsiteContents(weblog); this.strategy.remove(weblog); - + // remove entry from cache mapping this.weblogHandleToIdMap.remove(weblog.getHandle()); } - + /** * convenience method for removing contents of a weblog. * TODO BACKEND: use manager methods instead of queries here */ private void removeWebsiteContents(Weblog website) throws WebloggerException { - + UserManager umgr = roller.getUserManager(); WeblogManager wmgr = roller.getWeblogManager(); WeblogEntryManager emgr = roller.getWeblogEntryManager(); BookmarkManager bmgr = roller.getBookmarkManager(); MediaFileManager mmgr = roller.getMediaFileManager(); - + // remove tags Query tagQuery = strategy.getNamedQuery("WeblogEntryTag.getByWeblog"); tagQuery.setParameter(1, website); List results = tagQuery.getResultList(); - + for(Iterator iter = results.iterator(); iter.hasNext();) { WeblogEntryTag tagData = (WeblogEntryTag) iter.next(); if (tagData.getWeblogEntry() != null) { @@ -143,24 +143,24 @@ private void removeWebsiteContents(Weblog website) } this.strategy.remove(tagData); } - + // remove site tag aggregates List tags = emgr.getTags(website, null, null, 0, -1); updateTagAggregates(tags); - + // delete all weblog tag aggregates Query removeAggs= strategy.getNamedUpdate( "WeblogEntryTagAggregate.removeByWeblog"); removeAggs.setParameter(1, website); removeAggs.executeUpdate(); - + // delete all bad counts Query removeCounts = strategy.getNamedUpdate( "WeblogEntryTagAggregate.removeByTotalLessEqual"); removeCounts.setParameter(1, new Integer(0)); removeCounts.executeUpdate(); - - + + // Remove the website's ping queue entries Query q = strategy.getNamedQuery("PingQueueEntry.getByWebsite"); q.setParameter(1, website); @@ -169,7 +169,7 @@ private void removeWebsiteContents(Weblog website) while(it.hasNext()) { this.strategy.remove((PingQueueEntry) it.next()); } - + // Remove the website's auto ping configurations AutoPingManager autoPingMgr = roller .getAutopingManager(); @@ -178,7 +178,7 @@ private void removeWebsiteContents(Weblog website) while(it.hasNext()) { this.strategy.remove((AutoPing) it.next()); } - + // Remove the website's custom ping targets PingTargetManager pingTargetMgr = roller.getPingTargetManager(); List pingtargets = pingTargetMgr.getCustomPingTargets(website); @@ -186,7 +186,7 @@ private void removeWebsiteContents(Weblog website) while(it.hasNext()) { this.strategy.remove((PingTarget) it.next()); } - + // remove associated referers Query refQuery2 = strategy.getNamedQuery("WeblogReferrer.getByWebsite"); refQuery2.setParameter(1, website); @@ -196,8 +196,8 @@ private void removeWebsiteContents(Weblog website) this.strategy.remove(referer.getClass(), referer.getId()); } // TODO: can we eliminate this unnecessary flush with OpenJPA 1.0 - this.strategy.flush(); - + this.strategy.flush(); + // remove associated pages Query pageQuery = strategy.getNamedQuery("WeblogTemplate.getByWebsite"); pageQuery.setParameter(1, website); @@ -206,7 +206,7 @@ private void removeWebsiteContents(Weblog website) WeblogTemplate page = (WeblogTemplate) iter.next(); this.strategy.remove(page); } - + // remove folders (including bookmarks) WeblogBookmarkFolder rootFolder = bmgr.getRootFolder(website); if (null != rootFolder) { @@ -233,27 +233,27 @@ private void removeWebsiteContents(Weblog website) emgr.removeWeblogEntry(entry); } this.strategy.flush(); - + // remove categories WeblogCategory rootCat = emgr.getRootWeblogCategory(website); if (null != rootCat) { this.strategy.remove(rootCat); } - + // remove permissions for (Iterator iterator = umgr.getWeblogPermissions(website).iterator(); iterator.hasNext();) { WeblogPermission perm = (WeblogPermission) iterator.next(); - umgr.revokeWeblogPermission(perm.getWeblog(), perm.getUser(), WeblogPermission.ALL_ACTIONS); + umgr.revokeWeblogPermission(perm.getWeblog(), perm.getUser(), WeblogPermission.ALL_ACTIONS); } - + // flush the changes before returning. This is required as there is a // circular dependency between WeblogCategory and Weblog - this.strategy.flush(); + this.strategy.flush(); } - + protected void updateTagAggregates(List tags) throws WebloggerException { for(Iterator iter = tags.iterator(); iter.hasNext();) { - TagStat stat = (TagStat) iter.next(); + TagStat stat = (TagStat) iter.next(); Query query = strategy.getNamedUpdate( "WeblogEntryTagAggregate.getByName&WebsiteNullOrderByLastUsedDesc"); query.setParameter(1, stat.getName()); @@ -263,40 +263,40 @@ protected void updateTagAggregates(List tags) throws WebloggerException { } catch (NoResultException ignored) {} // no agg to be updated } } - + /** * @see org.apache.roller.weblogger.model.UserManager#storePage(org.apache.roller.weblogger.pojos.WeblogTemplate) */ public void savePage(WeblogTemplate page) throws WebloggerException { this.strategy.store(page); - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog(page.getWebsite()); } - + public void removePage(WeblogTemplate page) throws WebloggerException { this.strategy.remove(page); - + // update weblog last modified date. date updated by saveWebsite() roller.getWeblogManager().saveWeblog(page.getWebsite()); } - + public void addWeblog(Weblog newWeblog) throws WebloggerException { - + this.strategy.store(newWeblog); this.strategy.flush(); this.addWeblogContents(newWeblog); } - + private void addWeblogContents(Weblog newWeblog) throws WebloggerException { - + // grant weblog creator ADMIN permission List actions = new ArrayList(); actions.add(WeblogPermission.ADMIN); roller.getUserManager().grantWeblogPermission( newWeblog, newWeblog.getCreator(), actions); - + // add default category WeblogCategory rootCat = new WeblogCategory( newWeblog, // newWeblog @@ -305,7 +305,7 @@ private void addWeblogContents(Weblog newWeblog) "root", // description null ); // image this.strategy.store(rootCat); - + String cats = WebloggerConfig.getProperty("newuser.categories"); WeblogCategory firstCat = rootCat; if (cats != null && cats.trim().length() > 0) { @@ -322,20 +322,20 @@ private void addWeblogContents(Weblog newWeblog) this.strategy.store(c); } } - + // Use first category as default for Blogger API newWeblog.setBloggerCategory(firstCat); - + // But default category for weblog itself should be root newWeblog.setDefaultCategory(rootCat); - + this.strategy.store(newWeblog); - + // add default bookmarks WeblogBookmarkFolder root = new WeblogBookmarkFolder( null, "root", "root", newWeblog); this.strategy.store(root); - + Integer zero = new Integer(0); String blogroll = WebloggerConfig.getProperty("newuser.blogroll"); if (blogroll != null) { @@ -357,16 +357,16 @@ private void addWeblogContents(Weblog newWeblog) } } } - + // add any auto enabled ping targets PingTargetManager pingTargetMgr = roller.getPingTargetManager(); AutoPingManager autoPingMgr = roller.getAutopingManager(); - + Iterator pingTargets = pingTargetMgr.getCommonPingTargets().iterator(); PingTarget pingTarget = null; while(pingTargets.hasNext()) { pingTarget = (PingTarget) pingTargets.next(); - + if(pingTarget.isAutoEnabled()) { AutoPing autoPing = new AutoPing( null, pingTarget, newWeblog); @@ -377,28 +377,28 @@ private void addWeblogContents(Weblog newWeblog) roller.getMediaFileManager().createRootMediaFileDirectory(newWeblog); } - + public Weblog getWeblog(String id) throws WebloggerException { return (Weblog) this.strategy.load(Weblog.class, id); } - + public Weblog getWeblogByHandle(String handle) throws WebloggerException { return getWeblogByHandle(handle, Boolean.TRUE); } - + /** * Return website specified by handle. */ public Weblog getWeblogByHandle(String handle, Boolean enabled) throws WebloggerException { - + if (handle==null ) throw new WebloggerException("Handle cannot be null"); - + // check cache first // NOTE: if we ever allow changing handles then this needs updating if(this.weblogHandleToIdMap.containsKey(handle)) { - + Weblog weblog = this.getWeblog( (String) this.weblogHandleToIdMap.get(handle)); if(weblog != null) { @@ -412,7 +412,7 @@ public Weblog getWeblogByHandle(String handle, Boolean enabled) this.weblogHandleToIdMap.remove(handle); } } - + Query query = strategy.getNamedQuery("Weblog.getByHandle"); query.setParameter(1, handle); Weblog website = null; @@ -421,13 +421,13 @@ public Weblog getWeblogByHandle(String handle, Boolean enabled) } catch (NoResultException e) { website = null; } - + // add mapping to cache if(website != null) { log.debug("weblogHandleToId CACHE MISS - "+handle); this.weblogHandleToIdMap.put(website.getHandle(), website.getId()); } - + if(website != null && (enabled == null || enabled.equals(website.getEnabled()))) { return website; @@ -435,21 +435,21 @@ public Weblog getWeblogByHandle(String handle, Boolean enabled) return null; } } - + /** * Get websites of a user */ public List getWeblogs( Boolean enabled, Boolean active, Date startDate, Date endDate, int offset, int length) throws WebloggerException { - + //if (endDate == null) endDate = new Date(); - + List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); StringBuffer whereClause = new StringBuffer(); - + queryString.append("SELECT w FROM Weblog w WHERE "); if (startDate != null) { @@ -473,10 +473,10 @@ public List getWeblogs( if (whereClause.length() > 0) whereClause.append(" AND "); params.add(size++, active); whereClause.append(" w.active = ?" + size); - } - + } + whereClause.append(" ORDER BY w.dateCreated DESC"); - + Query query = strategy.getDynamicQuery(queryString.toString() + whereClause.toString()); if (offset != 0) { query.setFirstResult(offset); @@ -487,10 +487,10 @@ public List getWeblogs( for (int i=0; i perms = roller.getUserManager().getWeblogPermissions(user); @@ -504,7 +504,7 @@ public List getUserWeblogs(User user, boolean enabledOnly) throws WebloggerExcep } return weblogs; } - + public List getWeblogUsers(Weblog weblog, boolean enabledOnly) throws WebloggerException { List users = new ArrayList(); List perms = roller.getUserManager().getWeblogPermissions(weblog); @@ -524,22 +524,22 @@ public List getWeblogUsers(Weblog weblog, boolean enabledOnly) throws WebloggerE public WeblogTemplate getPage(String id) throws WebloggerException { // Don't hit database for templates stored on disk if (id != null && id.endsWith(".vm")) return null; - + return (WeblogTemplate)this.strategy.load(WeblogTemplate.class,id); } - + /** * Use JPA directly because Weblogger's Query API does too much allocation. */ public WeblogTemplate getPageByLink(Weblog website, String pagelink) throws WebloggerException { - + if (website == null) throw new WebloggerException("userName is null"); - + if (pagelink == null) throw new WebloggerException("Pagelink is null"); - + Query query = strategy.getNamedQuery("WeblogTemplate.getByWebsite&Link"); query.setParameter(1, website); query.setParameter(2, pagelink); @@ -549,42 +549,42 @@ public WeblogTemplate getPageByLink(Weblog website, String pagelink) return null; } } - + /** * @see org.apache.roller.weblogger.model.UserManager#getPageByAction(Weblog, java.lang.String) */ public WeblogTemplate getPageByAction(Weblog website, String action) throws WebloggerException { - + if (website == null) throw new WebloggerException("website is null"); - + if (action == null) throw new WebloggerException("Action name is null"); - - - Query query = strategy.getNamedQuery("WeblogTemplate.getByAction"); + + + Query query = strategy.getNamedQuery("WeblogTemplate.getByAction"); query.setParameter(1, website); query.setParameter(2, action); try { return (WeblogTemplate)query.getSingleResult(); } catch (NoResultException e) { return null; - } + } } - + /** * @see org.apache.roller.weblogger.model.UserManager#getPageByName(Weblog, java.lang.String) */ public WeblogTemplate getPageByName(Weblog website, String pagename) throws WebloggerException { - + if (website == null) throw new WebloggerException("website is null"); - + if (pagename == null) throw new WebloggerException("Page name is null"); - + Query query = strategy.getNamedQuery("WeblogTemplate.getByWebsite&Name"); query.setParameter(1, website); query.setParameter(2, pagename); @@ -594,7 +594,7 @@ public WeblogTemplate getPageByName(Weblog website, String pagename) return null; } } - + /** * @see org.apache.roller.weblogger.model.UserManager#getPages(Weblog) */ @@ -607,7 +607,7 @@ public List getPages(Weblog website) throws WebloggerException { return q.getResultList(); } - + public Map getWeblogHandleLetterMap() throws WebloggerException { String lc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Map results = new TreeMap(); @@ -622,7 +622,7 @@ public Map getWeblogHandleLetterMap() throws WebloggerException { } return results; } - + public List getWeblogsByLetter(char letter, int offset, int length) throws WebloggerException { Query query = strategy.getNamedQuery( @@ -636,15 +636,15 @@ public List getWeblogsByLetter(char letter, int offset, int length) } return query.getResultList(); } - + public List getMostCommentedWeblogs(Date startDate, Date endDate, int offset, int length) throws WebloggerException { - + Query query = null; - + if (endDate == null) endDate = new Date(); - + if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); Timestamp end = new Timestamp(endDate.getTime()); @@ -680,10 +680,10 @@ public List getMostCommentedWeblogs(Date startDate, Date endDate, // Original query ordered by desc # comments. // JPA QL doesn't allow queries to be ordered by agregates; do it in memory Collections.sort(results, statCountCountReverseComparator); - + return results; } - + /** * Get count of weblogs, active and inactive */ @@ -691,9 +691,9 @@ public long getWeblogCount() throws WebloggerException { long ret = 0; List results = strategy.getNamedQuery( "Weblog.getCountAllDistinct").getResultList(); - + ret = ((Long)results.get(0)).longValue(); - + return ret; } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerImpl.java index 0321305d2f..7ffc38cf73 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerImpl.java @@ -52,8 +52,8 @@ public class JPAWebloggerImpl extends WebloggerImpl { // a persistence utility class private final JPAPersistenceStrategy strategy; - - + + /** * Single constructor. * @throws org.apache.roller.weblogger.WebloggerException on any error @@ -79,7 +79,7 @@ protected JPAWebloggerImpl( WeblogEntryManager weblogEntryManager, OAuthManager oauthManager, URLStrategy urlStrategy) throws WebloggerException { - + super( autoPingManager, bookmarkManager, @@ -99,23 +99,23 @@ protected JPAWebloggerImpl( weblogEntryManager, oauthManager, urlStrategy); - + this.strategy = strategy; } - - + + public void flush() throws WebloggerException { this.strategy.flush(); } - + public void release() { super.release(); // tell JPA to close down this.strategy.release(); } - + public void shutdown() { // do our own shutdown first this.release(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerModule.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerModule.java index dccdb050e4..545aa54a6b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerModule.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWebloggerModule.java @@ -57,32 +57,32 @@ public class JPAWebloggerModule implements Module { public void configure(Binder binder) { binder.bind(Weblogger.class).to(JPAWebloggerImpl.class); - - binder.bind(JPAPersistenceStrategy.class); + + binder.bind(JPAPersistenceStrategy.class); binder.bind(org.apache.roller.weblogger.planet.business.jpa.JPARollerPlanetPersistenceStrategy.class); - - binder.bind(AutoPingManager.class).to( JPAAutoPingManagerImpl.class); - binder.bind(BookmarkManager.class).to( JPABookmarkManagerImpl.class); - binder.bind(PingQueueManager.class).to( JPAPingQueueManagerImpl.class); - binder.bind(PingTargetManager.class).to( JPAPingTargetManagerImpl.class); - binder.bind(PropertiesManager.class).to( JPAPropertiesManagerImpl.class); + + binder.bind(AutoPingManager.class).to( JPAAutoPingManagerImpl.class); + binder.bind(BookmarkManager.class).to( JPABookmarkManagerImpl.class); + binder.bind(PingQueueManager.class).to( JPAPingQueueManagerImpl.class); + binder.bind(PingTargetManager.class).to( JPAPingTargetManagerImpl.class); + binder.bind(PropertiesManager.class).to( JPAPropertiesManagerImpl.class); binder.bind(RefererManager.class).to( JPARefererManagerImpl.class); - binder.bind(ThreadManager.class).to( JPAThreadManagerImpl.class); - binder.bind(UserManager.class).to( JPAUserManagerImpl.class); - binder.bind(WeblogManager.class).to( JPAWeblogManagerImpl.class); - binder.bind(WeblogEntryManager.class).to( JPAWeblogEntryManagerImpl.class); + binder.bind(ThreadManager.class).to( JPAThreadManagerImpl.class); + binder.bind(UserManager.class).to( JPAUserManagerImpl.class); + binder.bind(WeblogManager.class).to( JPAWeblogManagerImpl.class); + binder.bind(WeblogEntryManager.class).to( JPAWeblogEntryManagerImpl.class); binder.bind(OAuthManager.class).to( JPAOAuthManagerImpl.class); binder.bind(OAuthValidator.class).to( SimpleOAuthValidator.class); - - binder.bind(ReferrerQueueManager.class).to(ReferrerQueueManagerImpl.class); + + binder.bind(ReferrerQueueManager.class).to(ReferrerQueueManagerImpl.class); binder.bind(MediaFileManager.class).to( JPAMediaFileManagerImpl.class); binder.bind(FileContentManager.class).to( FileContentManagerImpl.class); binder.bind(IndexManager.class).to( IndexManagerImpl.class); - binder.bind(PluginManager.class).to( PluginManagerImpl.class); + binder.bind(PluginManager.class).to( PluginManagerImpl.class); binder.bind(ThemeManager.class).to( ThemeManagerImpl.class); - + binder.bind(URLStrategy.class).to( MultiWeblogURLStrategy.class); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/AutoPingManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/AutoPingManager.java index 199596847e..1187301854 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/AutoPingManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/AutoPingManager.java @@ -31,8 +31,8 @@ * Manages autoping storage/retrieval, queries and queue. */ public interface AutoPingManager { - - + + /** * Store an auto ping configuration. * @@ -40,8 +40,8 @@ public interface AutoPingManager { * @throws WebloggerException */ public void saveAutoPing(AutoPing autoPing) throws WebloggerException; - - + + /** * Remove the auto ping configuration with given id. * @@ -49,8 +49,8 @@ public interface AutoPingManager { * @throws WebloggerException */ public void removeAutoPing(AutoPing autoPing) throws WebloggerException; - - + + /** * Remove the auto ping configuration for the given ping target and website, if one exists. Returns silently if it * doesn't exist. @@ -60,25 +60,25 @@ public interface AutoPingManager { * @throws WebloggerException */ public void removeAutoPing(PingTarget pingTarget, Weblog website) throws WebloggerException; - - + + /** * Remove a collection of auto ping configurations. - * + * * @param autopings a Collection of AAutoPing/code> objects * @throws WebloggerException */ public void removeAutoPings(Collection autopings) throws WebloggerException; - - + + /** * Remove all auto ping configurations for all websites. * * @throws WebloggerException */ public void removeAllAutoPings() throws WebloggerException; - - + + /** * Retrieve an auto ping configuration by id. * @@ -87,26 +87,26 @@ public interface AutoPingManager { * @throws WebloggerException */ public AutoPing getAutoPing(String id) throws WebloggerException; - - + + /** * Get all of the auto ping configurations for the given website. - * + * * @param website * @return a list of auto ping configurations for the given website as AuAutoPingcode> objects. */ public List getAutoPingsByWebsite(Weblog website) throws WebloggerException; - - + + /** * Get all of the auto ping configurations for a given target (across all websites). - * + * * @param pingTarget * @return a list of auto ping configurations for the given target as AuAutoPingcode> objects. */ public List getAutoPingsByTarget(PingTarget pingTarget) throws WebloggerException; - - + + /** * Get the auto ping configurations that should be pinged upon creation/change of the given weblog entry. * @@ -114,8 +114,8 @@ public interface AutoPingManager { * @return a list of the ping configurations that should be applied due to this change */ public List getApplicableAutoPings(WeblogEntry changedWeblogEntry) throws WebloggerException; - - + + /** * Queue the auto ping configurations that should be pinged upon change to the given weblog entry. This calls the * {@link PingQueueManager} to queue ping requests for each ping configuration that should be applied on change to @@ -124,8 +124,8 @@ public interface AutoPingManager { * @param changedWeblogEntry the entry that has been created or changed */ public void queueApplicableAutoPings(WeblogEntry changedWeblogEntry) throws WebloggerException; - - + + /** * Get the category restrictions on the given auto ping configuration. * @@ -135,8 +135,8 @@ public interface AutoPingManager { * in any category of the website). */ public List getCategoryRestrictions(AutoPing autoPing) throws WebloggerException; - - + + /** * Set the category restrictions on the given ping configuration to the specified ones. If the new collection is * empty, all category restrictions are removed. @@ -146,11 +146,11 @@ public interface AutoPingManager { */ public void setCategoryRestrictions(AutoPing autoPing, Collection newCategories); - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueManager.java index 0a04d05639..5b54f5ee36 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueManager.java @@ -30,8 +30,8 @@ * layer. */ public interface PingQueueManager { - - + + /** * Add a new persistent entry to the queue. If the queue already contains an entry for the ping target and website * specified by this auto ping configuration, a new one will not be added. @@ -39,8 +39,8 @@ public interface PingQueueManager { * @param autoPing auto ping configuration for the ping request to be queued. */ public void addQueueEntry(AutoPing autoPing) throws WebloggerException; - - + + /** * Store the given queue entry. * @@ -48,8 +48,8 @@ public interface PingQueueManager { * @throws WebloggerException */ public void saveQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerException; - - + + /** * Remove a queue entry. * @@ -57,8 +57,8 @@ public interface PingQueueManager { * @throws WebloggerException */ public void removeQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerException; - - + + /** * Retrieve an entry from the queue. * @@ -67,20 +67,20 @@ public interface PingQueueManager { * @throws WebloggerException */ public PingQueueEntry getQueueEntry(String id) throws WebloggerException; - - + + /** * Get all of the queue entries. - * + * * @return the queue as a List of {@link PPingQueueEntry objects. * @throws WebloggerException */ public List getAllQueueEntries() throws WebloggerException; - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueProcessor.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueProcessor.java index 2c995169f2..0a353bac2f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueProcessor.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueProcessor.java @@ -37,24 +37,24 @@ * @author Anil Gangolli */ public class PingQueueProcessor { - + private static final Log logger = LogFactory.getLog(PingQueueProcessor.class); - + private static PingQueueProcessor theInstance; - + private PingQueueManager pingQueueMgr; - - + + public static PingQueueProcessor getInstance() { return theInstance; } - - + + private PingQueueProcessor() throws WebloggerException { pingQueueMgr = WebloggerFactory.getWeblogger().getPingQueueManager(); } - - + + /** * Initialize the singleton. This is called during RollerContext initialization. * @@ -68,8 +68,8 @@ public static synchronized void init() throws WebloggerException { theInstance = new PingQueueProcessor(); if (logger.isDebugEnabled()) logger.debug("Ping queue processor initialized."); } - - + + /** * Process the ping queue. Performs one pass through the ping queue, processing every entry once. On ping failure * an entry is requeued for processing on subsequent passes until the configured maximum number of attempts is @@ -80,23 +80,23 @@ public synchronized void processQueue() { logger.info("Ping processing has been suspended. Skipping current round of ping queue processing."); return; } - + String absoluteContextUrl = WebloggerRuntimeConfig.getAbsoluteContextURL(); if (absoluteContextUrl == null) { logger.warn("WARNING: Skipping current ping queue processing round because we cannot yet determine the site's absolute context url."); return; } - + // TODO: Group by ping target and ping all sites for that target? // We're currently not taking advantage of grouping by ping target site and then sending // all of the pings for that target at once. If it becomes an efficiency issue, we should do // that. - + try { if (logger.isDebugEnabled()) logger.debug("Started processing ping queue."); // Get all of the entries List entries = pingQueueMgr.getAllQueueEntries(); - + // Process each entry for (Iterator i = entries.iterator(); i.hasNext();) { PingQueueEntry pingQueueEntry = (PingQueueEntry) i.next(); @@ -107,8 +107,8 @@ public synchronized void processQueue() { logger.error("Unexpected exception processing ping queue! Aborting this pass of ping queue processing.", ex); } } - - + + /** * Process an individual ping queue entry. * @@ -118,7 +118,7 @@ public synchronized void processQueue() { */ private void processQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerException { if (logger.isDebugEnabled()) logger.debug("Processing ping queue entry: " + pingQueueEntry); - + PingTarget pingTarget = pingQueueEntry.getPingTarget(); Weblog website = pingQueueEntry.getWebsite(); boolean pingSucceeded = false; @@ -145,8 +145,8 @@ private void processQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerEx pingQueueMgr.removeQueueEntry(pingQueueEntry); } } - - + + /** * Handle any ping error. * @@ -156,7 +156,7 @@ private void processQueueEntry(PingQueueEntry pingQueueEntry) throws WebloggerEx */ private void handlePingError(PingQueueEntry pingQueueEntry, Exception ex) throws WebloggerException { - + if ((pingQueueEntry.incrementAttempts() < PingConfig.getMaxPingAttempts()) && WeblogUpdatePinger.shouldRetry(ex)) { // We have attempts remaining, and it looks like we should retry, // so requeue the entry for processing on subsequent rounds @@ -171,5 +171,5 @@ private void handlePingError(PingQueueEntry pingQueueEntry, Exception ex) // TODO: mark ping target invalid? } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueTask.java index 22e52c95b2..0ad987daf5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingQueueTask.java @@ -44,38 +44,38 @@ public class PingQueueTask extends RollerTaskWithLeasing { // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = null; - + // a String description of when to start this task private String startTimeDesc = "immediate"; - + // interval at which the task is run, default is 5 minutes private int interval = 5; - + // lease time given to task lock, default is 30 minutes private int leaseTime = 30; - - + + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - - + + public void init() throws WebloggerException { this.init(PingQueueTask.NAME); } @@ -85,19 +85,19 @@ public void init(String name) throws WebloggerException { // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -107,7 +107,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -117,25 +117,25 @@ public void init(String name) throws WebloggerException { log.warn("Invalid leaseTime: "+leaseTimeStr); } } - + // initialize queue processor PingQueueProcessor.init(); } - + /** * Run the task once. */ public void runTask() { - + try { log.debug("task started"); - + PingQueueProcessor.getInstance().processQueue(); WebloggerFactory.getWeblogger().flush(); - + log.debug("task completed"); - + } catch (WebloggerException e) { log.error("Error while processing ping queue", e); } catch (Exception ee) { @@ -144,10 +144,10 @@ public void runTask() { // always release WebloggerFactory.getWeblogger().release(); } - + } - - + + /** * Main method so that this task may be run from outside the webapp. */ @@ -162,5 +162,5 @@ public static void main(String[] args) throws Exception { System.exit(-1); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingTargetManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingTargetManager.java index 68405b5f29..a5e940df79 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingTargetManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/pings/PingTargetManager.java @@ -30,8 +30,8 @@ * @author Anil Gangolli */ public interface PingTargetManager { - - + + /** * Store a ping target. * @@ -39,8 +39,8 @@ public interface PingTargetManager { * @throws WebloggerException */ public void savePingTarget(PingTarget pingTarget) throws WebloggerException; - - + + /** * Remove a ping target. * @@ -48,14 +48,14 @@ public interface PingTargetManager { * @throws WebloggerException */ public void removePingTarget(PingTarget pingTarget) throws WebloggerException; - - + + /** * Remove all custom targets (regardless of website). */ public void removeAllCustomPingTargets() throws WebloggerException; - - + + /** * Retrieve a specific ping target by id. * @@ -64,27 +64,27 @@ public interface PingTargetManager { * @throws WebloggerException */ public PingTarget getPingTarget(String id) throws WebloggerException; - - + + /** * Get a list of the common (shared) ping targets. - * + * * @return the list of common ping targets as a List of {@link PPingTarget objects * @throws WebloggerException */ public List getCommonPingTargets() throws WebloggerException; - - + + /** * Get a list of the custom ping targets for the given website. - * + * * @param website the website whose custom targets should be returned. * @return the list of custom ping targets for the given website as a List of {@link PiPingTarget objects * @throws WebloggerException */ public List getCustomPingTargets(Weblog website) throws WebloggerException; - - + + /** * Check if the ping target has a name that is unique in the appropriate set. If the ping target has no website id * (is common), then this checks if the name is unique amongst common targets, and if custom then unique amongst @@ -96,8 +96,8 @@ public interface PingTargetManager { * @throws WebloggerException */ public boolean isNameUnique(PingTarget pingTarget) throws WebloggerException; - - + + /** * Check if the url of the ping target is well-formed. For this test, it must parse as a java.net.URL, * with protocol http and a non-empty host portion. @@ -107,8 +107,8 @@ public interface PingTargetManager { * @throws WebloggerException */ public boolean isUrlWellFormed(PingTarget pingTarget) throws WebloggerException; - - + + /** * Check if the host portion of the url of the ping target is known, meaning it is either a well-formed IP address * or a hostname that resolves from the server. The ping target url must parse as a java.net.URL in @@ -120,11 +120,11 @@ public interface PingTargetManager { * @throws WebloggerException */ public boolean isHostnameKnown(PingTarget pingTarget) throws WebloggerException; - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManager.java index d88b9e447e..9fcdbe758a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManager.java @@ -30,13 +30,13 @@ * Plugin management for business layer and more generally applied plugins. */ public interface PluginManager { - + /** * Returns true if plugins are present */ public boolean hasPagePlugins(); - - + + /** * Returns a list of all registered weblog entry plugins initialized for * use with the specified weblog. @@ -44,8 +44,8 @@ public interface PluginManager { * @param website Website being processed */ public Map getWeblogEntryPlugins(Weblog website); - - + + /** * Apply a set of weblog entry plugins to the specified string and * return the results. This method must *NOT* alter the contents of @@ -57,8 +57,8 @@ public interface PluginManager { * @return the transformed text */ public String applyWeblogEntryPlugins(Map pagePlugins,WeblogEntry entry, String str); - - + + /** * Get the list of WeblogEntryCommentPlugin classes configured. * @@ -68,8 +68,8 @@ public interface PluginManager { * Should return an empty list if no plugins are configured. */ public List getCommentPlugins(); - - + + /** * Apply comment plugins. * @@ -78,11 +78,11 @@ public interface PluginManager { * @return String The transformed comment text. */ public String applyCommentPlugins(WeblogEntryComment comment, String text); - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManagerImpl.java index 7b10dd95a5..264809104e 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/PluginManagerImpl.java @@ -38,34 +38,34 @@ * Plugin management for business layer and more generally applied plugins. */ public class PluginManagerImpl implements PluginManager { - + private static Log log = LogFactory.getLog(PluginManagerImpl.class); - + // Plugin classes keyed by plugin name static Map mPagePlugins = new LinkedHashMap(); - + // Comment plugins private List commentPlugins = new ArrayList(); - - + + /** * Creates a new instance of PluginManagerImpl */ public PluginManagerImpl() { // load weblog entry plugins loadPagePluginClasses(); - + // load weblog entry comment plugins loadCommentPlugins(); } - - + + public boolean hasPagePlugins() { log.debug("mPluginClasses.size(): " + mPagePlugins.size()); return (mPagePlugins != null && mPagePlugins.size() > 0); } - - + + /** * Create and init plugins for processing entries in a specified website. */ @@ -84,8 +84,8 @@ public Map getWeblogEntryPlugins(Weblog website) { } return ret; } - - + + public String applyWeblogEntryPlugins(Map pagePlugins,WeblogEntry entry, String str) { String ret = str; WeblogEntry copy = new WeblogEntry(entry); @@ -104,27 +104,27 @@ public String applyWeblogEntryPlugins(Map pagePlugins,WeblogEntry entry, String } return ret; } - - + + /** * @inheritDoc */ public List getCommentPlugins() { return commentPlugins; } - - + + /** * @inheritDoc */ public String applyCommentPlugins(WeblogEntryComment comment, String text) { - + if(comment == null || text == null) { throw new IllegalArgumentException("comment cannot be null"); } - + String content = text; - + if (commentPlugins.size() > 0) { for( WeblogEntryCommentPlugin plugin : commentPlugins ) { if(comment.getPlugins() != null && @@ -134,11 +134,11 @@ public String applyCommentPlugins(WeblogEntryComment comment, String text) { } } } - + return content; } - - + + /** * Initialize PagePlugins declared in roller.properties. * By using the full class name we also allow for the implementation of @@ -147,7 +147,7 @@ public String applyCommentPlugins(WeblogEntryComment comment, String text) { */ private void loadPagePluginClasses() { log.debug("Initializing page plugins"); - + String pluginStr = WebloggerConfig.getProperty("plugins.page"); if (log.isDebugEnabled()) log.debug(pluginStr); if (pluginStr != null) { @@ -173,31 +173,31 @@ private void loadPagePluginClasses() { } } } - - + + /** * Initialize all comment plugins defined in weblogger config. */ private void loadCommentPlugins() { - + log.debug("Initializing comment plugins"); - + String pluginStr = WebloggerConfig.getProperty("comment.formatter.classnames"); if (pluginStr != null) { String[] plugins = StringUtils.stripAll(StringUtils.split(pluginStr, ",")); for (int i=0; i < plugins.length; i++) { log.debug("trying " + plugins[i]); - + try { Class pluginClass = Class.forName(plugins[i]); - WeblogEntryCommentPlugin plugin = + WeblogEntryCommentPlugin plugin = (WeblogEntryCommentPlugin) pluginClass.newInstance(); - + // make sure and maintain ordering commentPlugins.add(i, plugin); - + log.debug("Configured comment plugin: "+plugins[i]); - + } catch (ClassCastException e) { log.error("ClassCastException for " + plugins[i]); } catch (ClassNotFoundException e) { @@ -209,10 +209,10 @@ private void loadCommentPlugins() { } } } - + } - - + + private static boolean isPagePlugin(Class pluginClass) { Class[] interfaces = pluginClass.getInterfaces(); for (int i=0; i and
      tags. */ public class AutoformatPlugin implements WeblogEntryCommentPlugin { - + private static final Log log = LogFactory.getLog(AutoformatPlugin.class); - - + + public AutoformatPlugin() { // no-op } - - + + /** - * Unique identifier. This should never change. + * Unique identifier. This should never change. */ public String getId() { return "AutoFormat"; } - - + + public String getName() { return "Auto Format"; } - - + + public String getDescription() { return "Converts plain text style paragraphs into html paragraphs."; } - - + + public String render(final WeblogEntryComment comment, String text) { - + log.debug("starting value:\n"+text); - - /* + + /* * setup a buffered reader and iterate through each line * inserting html as needed * @@ -70,11 +70,11 @@ public String render(final WeblogEntryComment comment, String text) { StringBuffer buf = new StringBuffer(); try { BufferedReader br = new BufferedReader(new StringReader(text)); - + String line = null; boolean insidePara = false; while((line = br.readLine()) != null) { - + if(!insidePara && line.trim().length() > 0) { // start of a new paragraph buf.append("\n

      "); @@ -90,19 +90,19 @@ public String render(final WeblogEntryComment comment, String text) { insidePara = false; } } - + // if the text ends without an empty line then we need to // terminate the last paragraph now if(insidePara) buf.append("

      \n\n"); - + } catch(Exception e) { log.warn("trouble rendering text.", e); } - + log.debug("ending value:\n"+buf.toString()); - + return buf.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/HTMLSubsetPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/HTMLSubsetPlugin.java index 58e9d908e3..62c7343074 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/HTMLSubsetPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/HTMLSubsetPlugin.java @@ -29,46 +29,46 @@ */ public class HTMLSubsetPlugin implements WeblogEntryCommentPlugin { private static final Log log = LogFactory.getLog(HTMLSubsetPlugin.class); - - + + public HTMLSubsetPlugin() { log.debug("Instantiating HTMLSubsetPlugin"); } - - + + /** - * Unique identifier. This should never change. + * Unique identifier. This should never change. */ public String getId() { return "HTMLSubset"; } - - + + public String getName() { return "HTML Subset Restriction"; } - - + + public String getDescription() { return "Transforms the given comment body into a subset of HTML"; } - - + + public String render(final WeblogEntryComment comment, String text) { - + log.debug("starting value:\n"+text); - + String output = text; - + // escape html output = Utilities.escapeHTML(output); - + // just use old utilities method output = Utilities.transformToHTMLSubset(output); - + log.debug("ending value:\n"+output); - + return output; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/LinkMarkupPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/LinkMarkupPlugin.java index ae5060b684..3754b9c5c2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/LinkMarkupPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/LinkMarkupPlugin.java @@ -30,39 +30,39 @@ /** * Comment plugin which turns plain text URLs into hyperlinks using * the html anchor (<a>) tag. - * + * * Contributed by Matthew Montgomery. */ public class LinkMarkupPlugin implements WeblogEntryCommentPlugin { private static final Log log = LogFactory.getLog(LinkMarkupPlugin.class); private static final Pattern pattern = Pattern.compile( - "http[s]?://[^/][\\S]+", Pattern.CASE_INSENSITIVE); - + "http[s]?://[^/][\\S]+", Pattern.CASE_INSENSITIVE); + public LinkMarkupPlugin() { log.debug("Instantiating LinkMarkupPlugin"); } - + /** - * Unique identifier. This should never change. + * Unique identifier. This should never change. */ public String getId() { return "LinkMarkup"; } - - + + /** Returns the display name of this Plugin. */ public String getName() { return "Link Markup"; } - - + + /** Briefly describes the function of the Plugin. May contain HTML. */ public String getDescription() { return "Automatically creates hyperlinks out of embedded URLs."; } - - + + /** * Apply plugin to the specified text. * @@ -74,14 +74,14 @@ public String getDescription() { public String render(final WeblogEntryComment comment, String text) { StringBuilder result; result = new StringBuilder(); - + if (text != null) { Matcher matcher; matcher = pattern.matcher(text); int start = 0; int end = text.length(); - + while (start < end) { if (matcher.find()) { // Copy up to the match @@ -113,10 +113,10 @@ public String render(final WeblogEntryComment comment, String text) { } } else { - result.append(text); + result.append(text); } return result.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/WeblogEntryCommentPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/WeblogEntryCommentPlugin.java index 47146f3976..0cbd2e6275 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/WeblogEntryCommentPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/comment/WeblogEntryCommentPlugin.java @@ -27,25 +27,25 @@ * Weblog entry comment plugins are used to make transformations to comment text. */ public interface WeblogEntryCommentPlugin { - + /** * A unique identifier for the plugin. */ public String getId(); - - + + /** * Returns the display name of this Plugin. */ public String getName(); - - + + /** * Briefly describes the function of the Plugin. May contain HTML. */ public String getDescription(); - - + + /** * Apply plugin to the specified text. * @@ -54,5 +54,5 @@ public interface WeblogEntryCommentPlugin { * @return Results of applying plugin to string. */ public String render(final WeblogEntryComment comment, String str); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/AcronymsPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/AcronymsPlugin.java index b7adabbd4c..e763788a33 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/AcronymsPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/AcronymsPlugin.java @@ -45,9 +45,9 @@ * @version $Revision: 1.3 $ */ public class AcronymsPlugin implements WeblogEntryPlugin { - + private static final Log mLogger = LogFactory.getLog(AcronymsPlugin.class); - + protected String name = "Acronyms"; protected String description = "Expands acronyms defined in _acronym page. " + "Example: definition 'HTML=Hyper Text Markup Language' " + @@ -55,34 +55,34 @@ public class AcronymsPlugin implements WeblogEntryPlugin { "You must create an " + "" + "_acronym page to use Acronyms."; - - + + public AcronymsPlugin() { super(); mLogger.debug("AcronymsPlugin instantiated."); } - - + + public String getName() { return name; } - - + + public String getDescription() { return StringEscapeUtils.escapeJavaScript(description); } - - + + public void init(Weblog website) throws WebloggerException {} - - + + public String render(WeblogEntry entry, String str) { String text = str; - + if (mLogger.isDebugEnabled()) { mLogger.debug("render(entry = "+entry.getId()+")"); } - + /* * Get acronyms Properties. */ @@ -91,7 +91,7 @@ public String render(WeblogEntry entry, String str) { if (acronyms.size() == 0) { return text; } - + /* * Compile the user's acronyms into RegEx patterns. */ @@ -110,16 +110,16 @@ public String render(WeblogEntry entry, String str) { + ""; count++; } - + // if there are none, no work to do if (acronymPatterns == null || acronymPatterns.length == 0) { return text; } - + return matchAcronyms(text, acronymPatterns, acronymTags); } - - + + /** * Look for any _acronyms Page and parse it into Properties. * @param website @@ -141,8 +141,8 @@ private Properties loadAcronyms(Weblog website) { } return acronyms; } - - + + /** * Iterates through the acronym properties and replaces matching * acronyms in the entry text with acronym html-tags. @@ -155,7 +155,7 @@ private String matchAcronyms(String text, Pattern[] acronymPatterns, String[] ac if (mLogger.isDebugEnabled()) { mLogger.debug("matchAcronyms("+text+")"); } - + Matcher matcher = null; for (int i=0; iProperties
      collection. @@ -173,14 +173,14 @@ private String matchAcronyms(String text, Pattern[] acronymPatterns, String[] ac */ private Properties parseAcronymPage(WeblogTemplate acronymPage, Properties acronyms) { String rawAcronyms = acronymPage.getContents(); - + if (mLogger.isDebugEnabled()) { mLogger.debug("parsing _acronyms template: \n'"+rawAcronyms+"'"); } - + String regex = "\n"; // end of line String[] lines = rawAcronyms.split(regex); - + if (lines != null) { for (int i = 0; i < lines.length; i++) { int index = lines[i].indexOf('='); @@ -192,8 +192,8 @@ private Properties parseAcronymPage(WeblogTemplate acronymPage, Properties acron } } } - + return acronyms; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/BookmarkPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/BookmarkPlugin.java index 48ff346009..026c1229e9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/BookmarkPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/BookmarkPlugin.java @@ -41,33 +41,33 @@ * Automatically insert links into entry text based on users bookmarks. */ public class BookmarkPlugin implements WeblogEntryPlugin { - + private static Log mLogger = LogFactory.getLog(BookmarkPlugin.class); - + protected String name = "Bookmark Linker"; protected String description = "Automatically uses your Bookmarks to " + "create links. Simply use the Name of a Bookmark and it will be " + "converted into a hyperlink using the Bookmark's URL."; - - + + public BookmarkPlugin() { mLogger.debug("BookmarkPlugin instantiated."); } - - + + public String getName() { return name; } - - + + public String getDescription() { return StringEscapeUtils.escapeJavaScript(description); } - - + + public void init(Weblog website) throws WebloggerException {} - - + + public String render(WeblogEntry entry, String str) { String text = str; try { @@ -82,8 +82,8 @@ public String render(WeblogEntry entry, String str) { } return text; } - - + + /** * Recursively travel down Folder tree, attempting * to match up Bookmarks in each Folder. @@ -93,21 +93,21 @@ public String render(WeblogEntry entry, String str) { * @return */ private String lookInFolders(String text, Collection folders) { - + Iterator it = folders.iterator(); while (it.hasNext()) { WeblogBookmarkFolder folder = (WeblogBookmarkFolder)it.next(); text = matchBookmarks(text, folder); - + if (!folder.getFolders().isEmpty()) { lookInFolders(text, folder.getFolders()); } } - + return text; } - - + + private String matchBookmarks(String text,WeblogBookmarkFolder folder) { Iterator bookmarks = folder.getBookmarks().iterator(); String workingText = text; @@ -154,5 +154,5 @@ private String matchBookmarks(String text,WeblogBookmarkFolder folder) { } return workingText.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ConvertLineBreaksPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ConvertLineBreaksPlugin.java index a994c379e6..0870abfddd 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ConvertLineBreaksPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ConvertLineBreaksPlugin.java @@ -44,46 +44,46 @@ * */ public class ConvertLineBreaksPlugin implements WeblogEntryPlugin { - + private static Log mLogger = LogFactory.getLog(ConvertLineBreaksPlugin.class); - + private static final String name = "Convert Line Breaks"; private static final String description = "Convert plain text paragraphs to html by adding p and br tags"; private static final String version = "0.1"; - - + + public ConvertLineBreaksPlugin() { mLogger.debug("Instantiating ConvertLineBreaksPlugin v"+this.version); } - - + + public String getName() { return name; } - - + + public String getDescription() { return description; } - - + + public void init(Weblog website) throws WebloggerException { // we don't need to do any init. mLogger.debug("initing"); } - - + + /** * Transform the given plain text into html text by inserting p and br * tags around paragraphs and after line breaks. */ public String render(WeblogEntry entry, String str) { - + if(str == null || str.trim().equals("")) return ""; - + mLogger.debug("Rendering string of length "+str.length()); - + /* setup a buffered reader and iterate through each line * inserting html as needed * @@ -92,11 +92,11 @@ public String render(WeblogEntry entry, String str) { StringBuffer buf = new StringBuffer(); try { BufferedReader br = new BufferedReader(new StringReader(str)); - + String line = null; boolean insidePara = false; while((line = br.readLine()) != null) { - + if(!insidePara && line.trim().length() > 0) { // start of a new paragraph buf.append("\n

      "); @@ -112,18 +112,18 @@ public String render(WeblogEntry entry, String str) { insidePara = false; } } - + // if the text ends without an empty line then we need to // terminate the last paragraph now if(insidePara) buf.append("

      \n\n"); - + } catch(Exception e) { mLogger.warn("trouble rendering text.", e); return str; } - + return buf.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ObfuscateEmailPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ObfuscateEmailPlugin.java index 5d3d41ea63..94555fa367 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ObfuscateEmailPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/ObfuscateEmailPlugin.java @@ -33,35 +33,35 @@ * Obfuscate email addresses in entry text. */ public class ObfuscateEmailPlugin implements WeblogEntryPlugin { - + private static Log mLogger = LogFactory.getLog(ObfuscateEmailPlugin.class); - + protected String name = "Email Scrambler"; - + protected String description = "Automatically converts email addresses " + "to me-AT-mail-DOT-com format. Also "scrambles" mailto: links."; - - + + public ObfuscateEmailPlugin() { mLogger.debug("ObfuscateEmailPlugin instantiated."); } - - + + public String getName() { return name; } - - + + public String getDescription() { return StringEscapeUtils.escapeJavaScript(description); } - - + + public void init(Weblog website) throws WebloggerException {} - - + + public String render(WeblogEntry entry, String str) { return RegexUtil.encodeEmail(str); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java index 9c6266a763..1bbf67fac2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java @@ -36,18 +36,18 @@ * Converts ascii emoticons into HTML image tags. */ public class SmileysPlugin implements WeblogEntryPlugin { - + private static Log log = LogFactory.getLog(SmileysPlugin.class); - + public static Pattern[] smileyPatterns = new Pattern[0]; // public for tests static String[] imageTags = new String[0]; private static Properties smileyDefs = new Properties(); - + private String name = "Emoticons"; private String description = "Change ASCII emoticons to graphics. " + ":-) becomes "; - - + + static { try { smileyDefs.load(SmileysPlugin.class.getResourceAsStream("smileys.properties")); @@ -56,22 +56,22 @@ public class SmileysPlugin implements WeblogEntryPlugin { } } - + public SmileysPlugin() { log.debug("SmileysPlugin instantiated."); } - - + + public String getName() { return name; } - - + + public String getDescription() { return StringEscapeUtils.escapeJavaScript(description); } - - + + /* * Convert the SmileyDefs into RegEx patterns and img tags for * later use. Need an HttpServletRequest though so that we can @@ -81,7 +81,7 @@ public synchronized void init(Weblog website) throws WebloggerException { // don't do this work if Smileys already loaded if (SmileysPlugin.smileyPatterns.length < 1) { String baseURL = WebloggerRuntimeConfig.getAbsoluteContextURL(); - + Pattern[] tempP = new Pattern[SmileysPlugin.smileyDefs.size()]; String[] tempS = new String[SmileysPlugin.smileyDefs.size()]; log.debug("# smileys: " + smileyDefs.size()); @@ -104,8 +104,8 @@ public synchronized void init(Weblog website) throws WebloggerException { SmileysPlugin.imageTags = tempS; } } - - + + /** * Find occurences of ascii emoticons and turn them into HTML image pointers. */ @@ -117,8 +117,8 @@ public String render(WeblogEntry entry, String text) { } return text; } - - + + /* * To display the smiley 'glyph' certain characters * must be HTML escaped. @@ -139,7 +139,7 @@ private String htmlEscape(String smiley) { } return buf.toString(); } - + /** * Some characters have to escaped with a backslash before * being compiled into a Regular Expression. @@ -150,7 +150,7 @@ private String htmlEscape(String smiley) { private static char[] escape_regex = new char[] {'-', '(', ')', '\\', '|', ':', '^', '$', '*', '+', '?', '{', '}', '!', '=', '<', '>', '&', '[', ']' }; - + private String regexEscape(String smiley) { char[] chars = smiley.toCharArray(); StringBuffer buf = new StringBuffer(); @@ -165,5 +165,5 @@ private String regexEscape(String smiley) { } return buf.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/TopicTagPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/TopicTagPlugin.java index c487ddcb9f..f87e91b8ef 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/TopicTagPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/TopicTagPlugin.java @@ -126,7 +126,7 @@ public TopicTagPlugin() /** * Initialize the plugin instance. This sets up the configurable properties and default topic site. - * + * * @param rreq Plugins may need to access RollerRequest. * @param ctx Plugins may place objects into the Velocity Context. * @see PagWeblogEntryPluginit(org.apache.roller.weblogger.presentation.RollerRequest, org.apache.velocity.context.Context) @@ -239,7 +239,7 @@ public String render(WeblogEntry entry, String str) return result.toString(); } - + /** * Returns the human-friendly name of this Plugin. This is what users will see. @@ -454,5 +454,5 @@ public void setUserBookmarks(Map userBookmarks) { this.userBookmarks = userBookmarks; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/WeblogEntryPlugin.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/WeblogEntryPlugin.java index 67e86d69a9..82b34c4aa2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/WeblogEntryPlugin.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/plugins/entry/WeblogEntryPlugin.java @@ -31,19 +31,19 @@ * These plugins affect both the entry summary and entry body. */ public interface WeblogEntryPlugin { - + /** * Returns the display name of this Plugin. */ public String getName(); - - + + /** * Briefly describes the function of the Plugin. May contain HTML. */ public String getDescription(); - - + + /** * Give plugin a chance to initialize and add objects the rendering model. * @@ -51,8 +51,8 @@ public interface WeblogEntryPlugin { * @param model Rendering model where objects can be placed */ public void init(Weblog weblog) throws WebloggerException; - - + + /** * Apply plugin to the specified text. * @@ -61,5 +61,5 @@ public interface WeblogEntryPlugin { * @return Results of applying plugin to entry. */ public String render(WeblogEntry entry, String str); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/IncomingReferrer.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/IncomingReferrer.java index 4f01429fc8..c61d1feb5a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/IncomingReferrer.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/IncomingReferrer.java @@ -29,14 +29,14 @@ * @author Allen Gilliland */ public class IncomingReferrer { - + private String referrerUrl = null; private String requestUrl = null; private String weblogHandle = null; private String weblogAnchor = null; private String weblogDateString = null; - - + + public IncomingReferrer() {} public String getReferrerUrl() { @@ -78,5 +78,5 @@ public String getWeblogDateString() { public void setWeblogDateString(String weblogDateString) { this.weblogDateString = weblogDateString; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/QueuedReferrerProcessingJob.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/QueuedReferrerProcessingJob.java index 588ebb8e66..703c97ecaa 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/QueuedReferrerProcessingJob.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/QueuedReferrerProcessingJob.java @@ -33,28 +33,28 @@ * @author Allen Gilliland */ public class QueuedReferrerProcessingJob extends ReferrerProcessingJob { - + public QueuedReferrerProcessingJob() { super(); } - - + + public void execute() { - + ReferrerQueueManager refQueue = WebloggerFactory.getWeblogger().getReferrerQueueManager(); - + // check the queue for any incoming referrers referrer = refQueue.dequeue(); - + // work until the queue is empty while(referrer != null) { super.execute(); - + // check if there are more referrers to process referrer = refQueue.dequeue(); } - + } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/RefererManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/RefererManager.java index 30d7548bfa..3b6a8dc48f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/RefererManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/RefererManager.java @@ -26,47 +26,47 @@ /** * Interface to Referer management. */ -public interface RefererManager { - +public interface RefererManager { + /** * Store the referer. */ - public void saveReferer(WeblogReferrer referer) throws WebloggerException; - + public void saveReferer(WeblogReferrer referer) throws WebloggerException; + /** * Remove a single referer. */ - public void removeReferer(WeblogReferrer referer) throws WebloggerException; - + public void removeReferer(WeblogReferrer referer) throws WebloggerException; + /** * Clear referrer dayhits and remove referrers without excerpts. */ - public void clearReferrers() throws WebloggerException; - + public void clearReferrers() throws WebloggerException; + /** * Clear referrer dayhits and remove referrers without excerpts. */ - public void clearReferrers(Weblog website) throws WebloggerException; - + public void clearReferrers(Weblog website) throws WebloggerException; + /** * Retrieve referer by id. */ - public WeblogReferrer getReferer(String id) throws WebloggerException; - + public WeblogReferrer getReferer(String id) throws WebloggerException; + /** * Get all referers for specified weblog. * @param weblog * @return List of type RefererData */ - public List getReferers(Weblog weblog) throws WebloggerException; - + public List getReferers(Weblog weblog) throws WebloggerException; + /** * Get all referers for specified user that were made today. * @param userName Name of user. * @return List of type RefererData */ - public List getTodaysReferers(Weblog website) throws WebloggerException; - + public List getTodaysReferers(Weblog website) throws WebloggerException; + /** * Get referers for a specified date. * @param userName Name of user. @@ -74,9 +74,9 @@ public interface RefererManager { * @return List of type RefererData. * @throws WebloggerException */ - public List getReferersToDate(Weblog website, String date) - throws WebloggerException; - + public List getReferersToDate(Weblog website, String date) + throws WebloggerException; + /** * Returns hot weblogs as StatCount objects, in descending order by today's hits. * @param sinceDays Restrict to last X days (or -1 for all) @@ -84,8 +84,8 @@ public List getReferersToDate(Weblog website, String date) * @param len Maximum number of results to return (for paging) * @return List of StatCount objects. */ - public List getHotWeblogs(int sinceDays, int offset, int length) - throws WebloggerException; + public List getHotWeblogs(int sinceDays, int offset, int length) + throws WebloggerException; /** * Get referers that refer to a specific weblog entry. @@ -93,28 +93,28 @@ public List getHotWeblogs(int sinceDays, int offset, int length) * @return List of RefererData objects. * @throws WebloggerException */ - public List getReferersToEntry(String entryid) throws WebloggerException; - - /** - * Get user's day hits + public List getReferersToEntry(String entryid) throws WebloggerException; + + /** + * Get user's day hits */ - public int getDayHits(Weblog website) throws WebloggerException; - - /** - * Get user's all-time total hits + public int getDayHits(Weblog website) throws WebloggerException; + + /** + * Get user's all-time total hits */ - public int getTotalHits(Weblog website) throws WebloggerException; - + public int getTotalHits(Weblog website) throws WebloggerException; + /** * Apply ignoreWord/spam filters to all referers in system. */ - public void applyRefererFilters() throws WebloggerException; - + public void applyRefererFilters() throws WebloggerException; + /** * Apply ignoreWord/spam filters to all referers in website. */ - public void applyRefererFilters(Weblog website) throws WebloggerException; - + public void applyRefererFilters(Weblog website) throws WebloggerException; + /** * Process an incoming referer. */ @@ -123,11 +123,11 @@ public void processReferrer( String referrerUrl, String weblogHandle, String weblogAnchor, - String weblogDateString); - + String weblogDateString); + /** * Release all resources held by manager. */ - public void release(); + public void release(); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerProcessingJob.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerProcessingJob.java index 6ed760269b..936087552b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerProcessingJob.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerProcessingJob.java @@ -37,27 +37,27 @@ * @author Allen Gilliland */ public class ReferrerProcessingJob implements Job { - + private static Log mLogger = LogFactory.getLog(ReferrerProcessingJob.class); - + Map inputs = null; IncomingReferrer referrer = null; - + public ReferrerProcessingJob() {} - - + + /** * Execute job. * * We simply pass the referrer into the RefererManager to handle the details. */ public void execute() { - + if(this.referrer == null) return; - + mLogger.debug("PROCESSING: "+referrer.getRequestUrl()); - + // process a referrer try { RefererManager refMgr = WebloggerFactory.getWeblogger().getRefererManager(); @@ -66,36 +66,36 @@ public void execute() { referrer.getWeblogHandle(), referrer.getWeblogAnchor(), referrer.getWeblogDateString()); - + WebloggerFactory.getWeblogger().flush(); } catch(WebloggerException re) { // trouble mLogger.warn("Trouble processing referrer", re); } } - - + + /** * Set input. */ public void input(Map input) { this.inputs = input; - + // we are looking for the "referrer" key Object ref = input.get("referrer"); - + if(ref instanceof IncomingReferrer) { this.referrer = (IncomingReferrer) ref; } } - - + + /** * Get output. */ public Map output() { - + return null; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManager.java index 705e9a4df1..80f9eb3e41 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManager.java @@ -29,7 +29,7 @@ * @author Allen Gilliland */ public interface ReferrerQueueManager { - + /** * Process an incoming referrer. * @@ -37,27 +37,27 @@ public interface ReferrerQueueManager { * It may process them immediately or it may store them for later processing. */ public void processReferrer(IncomingReferrer ref); - - + + /** * Add a referrer to the queue. * * It is almost always preferable to call processReferrer() instead. */ public void enqueue(IncomingReferrer ref); - - + + /** * Get the next item in the queue. * * Returns null if there is nothing in the queue. */ public IncomingReferrer dequeue(); - - + + /** * Called when the system is being shutdown. */ public void shutdown(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManagerImpl.java index 319436c2c2..49564b49a3 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/referrers/ReferrerQueueManagerImpl.java @@ -34,7 +34,7 @@ /** * The base implementation of the ReferrerQueueManager. - * + * * This class is implemented using the singleton pattern to ensure that only * one instance exists at any given time. * @@ -55,57 +55,57 @@ */ @com.google.inject.Singleton public class ReferrerQueueManagerImpl implements ReferrerQueueManager { - + private static Log mLogger = LogFactory.getLog(ReferrerQueueManagerImpl.class); - + private final Weblogger roller; - + private boolean asyncMode = false; private int numWorkers = 1; private int sleepTime = 10000; private List workers = null; private List referrerQueue = null; - + // private because we are a singleton @com.google.inject.Inject protected ReferrerQueueManagerImpl(Weblogger roller) { - + mLogger.info("Instantiating Referrer Queue Manager"); - + this.roller = roller; // lookup config options this.asyncMode = WebloggerConfig.getBooleanProperty("referrers.asyncProcessing.enabled"); - + mLogger.info("Asynchronous referrer processing = "+this.asyncMode); - + if(this.asyncMode) { - - + + String num = WebloggerConfig.getProperty("referrers.queue.numWorkers"); String sleep = WebloggerConfig.getProperty("referrers.queue.sleepTime"); - + try { this.numWorkers = Integer.parseInt(num); - + if(numWorkers < 1) this.numWorkers = 1; - + } catch(NumberFormatException nfe) { mLogger.warn("Invalid num workers ["+num+"], using default"); } - + try { // multiply by 1000 because we expect input in seconds this.sleepTime = Integer.parseInt(sleep) * 1000; } catch(NumberFormatException nfe) { mLogger.warn("Invalid sleep time ["+sleep+"], using default"); } - + // create the processing queue this.referrerQueue = Collections.synchronizedList(new ArrayList()); - + // start up workers this.workers = new ArrayList(); ContinuousWorkerThread worker = null; @@ -118,8 +118,8 @@ protected ReferrerQueueManagerImpl(Weblogger roller) { } } } - - + + /** * Process an incoming referrer. * @@ -128,24 +128,24 @@ protected ReferrerQueueManagerImpl(Weblogger roller) { * now. */ public void processReferrer(IncomingReferrer referrer) { - + if(this.asyncMode) { mLogger.debug("QUEUING: "+referrer.getRequestUrl()); - + // add to queue this.enqueue(referrer); } else { // process now ReferrerProcessingJob job = new ReferrerProcessingJob(); - + // setup input HashMap inputs = new HashMap(); inputs.put("referrer", referrer); job.input(inputs); - + // execute job.execute(); - + try { // flush changes roller.flush(); @@ -153,43 +153,43 @@ public void processReferrer(IncomingReferrer referrer) { mLogger.error("ERROR commiting referrer", ex); } } - + } - - + + /** * Place a referrer in the queue. */ public void enqueue(IncomingReferrer referrer) { this.referrerQueue.add(referrer); - + if(this.referrerQueue.size() > 250) { mLogger.warn("Referrer queue is rather full. queued="+this.referrerQueue.size()); } } - - + + /** * Retrieve the next referrer in the queue. */ public synchronized IncomingReferrer dequeue() { - + if(!this.referrerQueue.isEmpty()) { return (IncomingReferrer) this.referrerQueue.remove(0); } - + return null; } - - + + /** * clean up. */ public void shutdown() { - + if(this.workers != null && this.workers.size() > 0) { mLogger.info("stopping all ReferrerQueue worker threads"); - + // kill all of our threads WorkerThread worker = null; Iterator it = this.workers.iterator(); @@ -198,7 +198,7 @@ public void shutdown() { worker.interrupt(); } } - + } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ContinuousWorkerThread.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ContinuousWorkerThread.java index ca62335b7b..b328f17801 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ContinuousWorkerThread.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ContinuousWorkerThread.java @@ -26,55 +26,55 @@ * A worker that performs a given job continuously. */ public class ContinuousWorkerThread extends WorkerThread { - + private static Log mLogger = LogFactory.getLog(ContinuousWorkerThread.class); - + // default sleep time is 10 seconds long sleepTime = 10000; - - + + public ContinuousWorkerThread(String id) { super(id); } - - + + public ContinuousWorkerThread(String id, long sleep) { super(id); - + this.sleepTime = sleep; } - - + + public ContinuousWorkerThread(String id, Job job) { super(id, job); } - - + + public ContinuousWorkerThread(String id, Job job, long sleep) { super(id, job); - + this.sleepTime = sleep; } - - + + /** * Thread execution. * - * We run forever. Each time a job completes we sleep for + * We run forever. Each time a job completes we sleep for * some amount of time before trying again. * * If we ever get interrupted then we quit. */ public void run() { - + mLogger.info(this.id+" Started."); - + // run forever while(true) { - + // execute our job super.run(); - + // job is done, lets sleep it off for a bit try { mLogger.debug(this.id+" SLEEPING for "+this.sleepTime+" milliseconds ..."); @@ -85,5 +85,5 @@ public void run() { } } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/HitCountProcessingJob.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/HitCountProcessingJob.java index 7b9d955eb3..092e7f892c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/HitCountProcessingJob.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/HitCountProcessingJob.java @@ -38,13 +38,13 @@ * stores them in the database. */ public class HitCountProcessingJob implements Job { - + private static Log log = LogFactory.getLog(HitCountProcessingJob.class); - - + + public HitCountProcessingJob() {} - - + + /** * Execute the job. * @@ -52,25 +52,25 @@ public HitCountProcessingJob() {} * then propogate them to the db for persistent storage. */ public void execute() { - + UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); WeblogEntryManager emgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + HitCountQueue hitCounter = HitCountQueue.getInstance(); - + // first get the current set of hits List currentHits = hitCounter.getHits(); - + // now reset the queued hits hitCounter.resetHits(); - + // tally the counts, grouped by weblog handle Map hitsTally = new HashMap(); String weblogHandle = null; for(int i=0; i < currentHits.size(); i++) { weblogHandle = (String) currentHits.get(i); - + Long count = (Long) hitsTally.get(weblogHandle); if(count == null) { count = new Long(1); @@ -79,17 +79,17 @@ public void execute() { } hitsTally.put(weblogHandle, count); } - + // iterate over the tallied hits and store them in the db try { long startTime = System.currentTimeMillis(); - + Weblog weblog = null; String key = null; Iterator it = hitsTally.keySet().iterator(); while(it.hasNext()) { key = (String) it.next(); - + try { weblog = wmgr.getWeblogByHandle(key); emgr.incrementHitCount(weblog, ((Long)hitsTally.get(key)).intValue()); @@ -97,14 +97,14 @@ public void execute() { log.error(ex); } } - + // flush the results to the db WebloggerFactory.getWeblogger().flush(); - + long endTime = System.currentTimeMillis(); - + log.debug("Completed: "+ (endTime-startTime)/1000 + " secs"); - + } catch (WebloggerException ex) { log.error("Error persisting updated hit counts", ex); } finally { @@ -112,14 +112,14 @@ public void execute() { WebloggerFactory.getWeblogger().release(); } } - - + + public void input(Map input) { // no-op } - + public Map output() { return null; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/Job.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/Job.java index a2eefdca95..9d62c71304 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/Job.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/Job.java @@ -31,22 +31,22 @@ * @author Allen Gilliland */ public interface Job { - + /** * Execute the job. */ public void execute(); - - + + /** * Pass in input to be used for the job. */ public void input(Map input); - - + + /** * Get any output from the job. */ public Map output(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ResetHitCountsTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ResetHitCountsTask.java index 5f13b01111..be19091c45 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ResetHitCountsTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ResetHitCountsTask.java @@ -39,60 +39,60 @@ public class ResetHitCountsTask extends RollerTaskWithLeasing { // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = null; - + // a String description of when to start this task private String startTimeDesc = "startOfDay"; - + // interval at which the task is run, default is 1 day private int interval = 1440; - + // lease time given to task lock, default is 30 minutes private int leaseTime = 30; - - + + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - - + + public void init() throws WebloggerException { this.init(ResetHitCountsTask.NAME); } public void init(String name) throws WebloggerException { super.init(name); - + // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -102,7 +102,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -113,22 +113,22 @@ public void init(String name) throws WebloggerException { } } } - - + + /** * Execute the task. */ public void runTask() { - + try { log.info("task started"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.resetAllHitCounts(); WebloggerFactory.getWeblogger().flush(); - + log.info("task completed"); - + } catch (WebloggerException e) { log.error("Error while checking for referer turnover", e); } catch (Exception ee) { @@ -137,10 +137,10 @@ public void runTask() { // always release WebloggerFactory.getWeblogger().release(); } - + } - - + + /** * Main method so that this task may be run from outside the webapp. */ @@ -155,5 +155,5 @@ public static void main(String[] args) throws Exception { System.exit(-1); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTask.java index f47fc7cf7f..00355a667c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTask.java @@ -35,7 +35,7 @@ public abstract class RollerTask implements Runnable { private String taskName = null; - + /** * Initialization. Run once before the task is started. */ @@ -52,21 +52,21 @@ public void init(String name) throws WebloggerException { public final String getName() { return taskName; } - - + + /** * Get the unique id representing a specific instance of a task. This is - * important for tasks being run in a clustered environment so that a + * important for tasks being run in a clustered environment so that a * lease can be associated with a single cluster member. * * @return The unique client identifier for this task instance. */ public abstract String getClientId(); - - + + /** * When should this task be started? The task is given the current time - * so that it may determine a start time relative to the current time, + * so that it may determine a start time relative to the current time, * such as the end of the day or hour. * * It is acceptable to return the currentTime object passed in or any other @@ -77,18 +77,18 @@ public final String getName() { * @return The Date when this task should be started. */ public abstract Date getStartTime(Date currentTime); - - + + /** * Get a string description of the start time of the given task. - * + * * Should be one of ... 'immediate', 'startOfDay', 'startOfHour' - * + * * @return The start time description. */ public abstract String getStartTimeDesc(); - - + + /** * How often should the task run, in minutes. * @@ -97,8 +97,8 @@ public final String getName() { * @return The interval the task should be run at, in minutes. */ public abstract int getInterval(); - - + + /** * Get the time, in minutes, this task wants to be leased for. * @@ -107,42 +107,42 @@ public final String getName() { * @return The time this task should lease its lock for, in minutes. */ public abstract int getLeaseTime(); - - + + /** * Get the properties from WebloggerConfig which pertain to this task. - * + * * This extracts all properties from the WebloggerConfig of the type * task..=value and returns them in a properties object * where each item is keyed by . */ protected Properties getTaskProperties() { - + String prefix = "tasks."+this.getName()+"."; - + Properties taskProps = new Properties(); - + String key = null; Enumeration keys = WebloggerConfig.keys(); while(keys.hasMoreElements()) { key = (String) keys.nextElement(); - + if(key.startsWith(prefix)) { - taskProps.setProperty(key.substring(prefix.length()), + taskProps.setProperty(key.substring(prefix.length()), WebloggerConfig.getProperty(key)); } } - + // special addition for clientId property that applies to all tasks taskProps.setProperty("clientId", WebloggerConfig.getProperty("tasks.clientId")); - + return taskProps; } - - + + /** * A convenience method for calculating an adjusted time given an initial - * Date to work from and a "changeFactor" which describes how the time + * Date to work from and a "changeFactor" which describes how the time * should be adjusted. * * Allowed change factors are ... @@ -151,20 +151,20 @@ protected Properties getTaskProperties() { * 'startOfDay' - midnight, beginning on the next day */ protected Date getAdjustedTime(Date startTime, String changeFactor) { - + if(startTime == null || changeFactor == null) { return startTime; } - + Date adjustedTime = startTime; - + if("startOfDay".equals(changeFactor)) { adjustedTime = DateUtil.getEndOfDay(startTime); } else if("startOfHour".equals(changeFactor)) { adjustedTime = DateUtil.getEndOfHour(startTime); } - + return adjustedTime; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTaskWithLeasing.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTaskWithLeasing.java index 7af458f0eb..544019fbb7 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTaskWithLeasing.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/RollerTaskWithLeasing.java @@ -30,14 +30,14 @@ */ public abstract class RollerTaskWithLeasing extends RollerTask { private static Log log = LogFactory.getLog(RollerTaskWithLeasing.class); - - + + /** * Run the task. */ public abstract void runTask() throws WebloggerException; - - + + /** * The run() method as called by our thread manager. * @@ -49,15 +49,15 @@ public abstract class RollerTaskWithLeasing extends RollerTask { * Roller tasks should put their logic in the runTask() method. */ public final void run() { - + ThreadManager mgr = WebloggerFactory.getWeblogger().getThreadManager(); - + boolean lockAcquired = false; try { log.debug(getName()+": Attempting to acquire lease"); - + lockAcquired = mgr.registerLease(this); - + // now if we have a lock then run the task if(lockAcquired) { log.debug(getName()+": Lease acquired, running task"); @@ -66,28 +66,28 @@ public final void run() { log.debug(getName()+": Lease NOT acquired, cannot continue"); return; } - + } catch (Exception ex) { log.error(getName()+": Unexpected exception", ex); } finally { - + if(lockAcquired) { - + log.debug(getName()+": Attempting to release lease"); - + boolean lockReleased = mgr.unregisterLease(this); - + if(lockReleased) { log.debug(getName()+": Lease released, task finished"); } else { log.debug(getName()+": Lease NOT released, some kind of problem"); } } - + // always release Roller session WebloggerFactory.getWeblogger().release(); } - + } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ScheduledEntriesTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ScheduledEntriesTask.java index 7ab3d99a7f..43db7b0e38 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ScheduledEntriesTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ScheduledEntriesTask.java @@ -38,45 +38,45 @@ */ public class ScheduledEntriesTask extends RollerTaskWithLeasing { private static Log log = LogFactory.getLog(ScheduledEntriesTask.class); - + public static String NAME = "ScheduledEntriesTask"; - + // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = null; - + // a String description of when to start this task private String startTimeDesc = "immediate"; - + // interval at which the task is run, default is once per minute private int interval = 1; - + // lease time given to task lock, default is 30 minutes private int leaseTime = 30; - + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - - + + public void init() throws WebloggerException { this.init(ScheduledEntriesTask.NAME); } @@ -87,19 +87,19 @@ public void init(String name) throws WebloggerException { // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -109,7 +109,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -120,26 +120,26 @@ public void init(String name) throws WebloggerException { } } } - - + + /** * Execute the task. */ public void runTask() { - + log.debug("task started"); - + try { WeblogEntryManager wMgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); IndexManager searchMgr = WebloggerFactory.getWeblogger().getIndexManager(); - + Date now = new Date(); - + log.debug("looking up scheduled entries older than "+now); - + // get all published entries older than current time List scheduledEntries = wMgr.getWeblogEntries( - + null, // website null, // user null, // startDate @@ -151,35 +151,35 @@ public void runTask() { null, // sortOrder null, // locale 0, -1); // offset, length - + log.debug("promoting "+scheduledEntries.size()+" entries to PUBLISHED state"); - + WeblogEntry entry = null; Iterator it = scheduledEntries.iterator(); while(it.hasNext()) { entry = (WeblogEntry) it.next(); - + // update status to PUBLISHED and save entry.setStatus(WeblogEntry.PUBLISHED); wMgr.saveWeblogEntry(entry); } - + // commit the changes WebloggerFactory.getWeblogger().flush(); - + // take a second pass to trigger reindexing and cache invalidations // this is because we need the updated entries flushed first it = scheduledEntries.iterator(); while(it.hasNext()) { entry = (WeblogEntry) it.next(); - + // trigger a cache invalidation CacheManager.invalidate(entry); - + // trigger search index on entry searchMgr.addEntryReIndexOperation(entry); } - + } catch (WebloggerException e) { log.error("Error getting scheduled entries", e); } catch(Exception e) { @@ -188,12 +188,12 @@ public void runTask() { // always release WebloggerFactory.getWeblogger().release(); } - + log.debug("task completed"); - + } - - + + /** * Main method so that this task may be run from outside the webapp. */ @@ -208,5 +208,5 @@ public static void main(String[] args) throws Exception { System.exit(-1); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskRunner.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskRunner.java index f4dd66bf7f..88eab1a77b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskRunner.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskRunner.java @@ -16,17 +16,17 @@ * directory of this distribution. */ package org.apache.roller.weblogger.business.runnable; - + import java.io.File; import org.apache.roller.weblogger.util.StandaloneWebappClassLoader; /** - * Sets up classpath for running a Roller task outside of the Roller webapp. + * Sets up classpath for running a Roller task outside of the Roller webapp. */ -public class TaskRunner { - - public TaskRunner() {} - +public class TaskRunner { + + public TaskRunner() {} + public static void main(String[] args) throws Exception { if (args.length < 3) { System.err.println("USAGE: java -cp roller-planet.jar TaskRunner WEBAPPDIR JARSDIR CLASSNAME"); @@ -40,19 +40,19 @@ public static void main(String[] args) throws Exception { String webappDir = args[0]; String jarsDir = args[1]; String taskClassName = args[2]; - System.out.println("WEBAPPDIR = " + webappDir); + System.out.println("WEBAPPDIR = " + webappDir); System.out.println("JARSDIR = " + jarsDir); System.out.println("CLASSNAME = " + taskClassName); - + File webappDirFile = new File(webappDir); File jarsDirFile = new File(jarsDir); if (!webappDirFile.isDirectory() || !jarsDirFile.isDirectory()) { System.err.println("ERROR: webapp.dir and jars.dir must specify existing directories"); System.exit(-1); - } - + } + ClassLoader cl = new StandaloneWebappClassLoader(webappDir, jarsDir, null); - + // We're using the new classloader from here on out Thread.currentThread().setContextClassLoader(cl); @@ -65,7 +65,7 @@ public static void main(String[] args) throws Exception { /* for example: - + java \ -Dplanet.custom.config=planet-custom.properties \ -Dcatalina.base=. \ @@ -74,5 +74,5 @@ public static void main(String[] args) throws Exception { ~/roller_trunk/sandbox/planetroller/build/webapp \ /Applications/Java/jakarta-tomcat-5.5.9/common/lib \ org.apache.roller.weblogger.planet.tasks.GeneratePlanetTask - + */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskScheduler.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskScheduler.java index ae17ed9886..086b9aebea 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskScheduler.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TaskScheduler.java @@ -32,47 +32,47 @@ /** * Manages scheduling of periodic tasks. - * + * * This scheduler is meant to be run on a single thread and once started it will * run continuously until the thread is interrupted. The basic logic of the * scheduler is to accept some number of tasks to be run and once per minute - * the scheduler will launch any tasks that need to be executed. - * + * the scheduler will launch any tasks that need to be executed. + * * Tasks are executed each on their own thread, so this scheduler does not run * serially like a TimerTask. The threads used for running tasks are managed * by an instance of a ThreadPoolExecutor. */ public class TaskScheduler implements Runnable { - + private static Log log = LogFactory.getLog(TaskScheduler.class); - + private static final long ONE_MINUTE_MS = (60 * 1000); - + private final ExecutorService pool; private final List tasks; - - + + public TaskScheduler(List webloggerTasks) { - + // store list of tasks available to run tasks = webloggerTasks; - + // use an expanding thread executor pool pool = Executors.newCachedThreadPool(); } - - + + public void run() { - + boolean firstRun = true; - + // run forever, or until we get interrupted while(true) { try { // get current time Date now = new Date(); log.debug("Current time = "+now); - + // run tasks, skip run on first pass if(firstRun) { // add a slight delay to scheduler start @@ -83,7 +83,7 @@ public void run() { cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); now = cal.getTime(); log.debug("Start time = "+now); - + firstRun = false; } else { try { @@ -93,7 +93,7 @@ public void run() { WebloggerFactory.getWeblogger().release(); } } - + // wait 'til next minute // NOTE: we add 50ms of adjustment time to make sure we awaken // during the next minute, and not before. awakening at @@ -111,7 +111,7 @@ public void run() { log.debug("sleeping - "+sleepTime); Thread.sleep(sleepTime); } - + } catch (InterruptedException ex) { // thread interrupted log.debug("Thread interrupted, scheduler is stopping"); @@ -119,43 +119,43 @@ public void run() { break; } } - + } - - + + /** * Run the necessary tasks given a specific currentTime to work from. */ private void runTasks(Date currentTime) { - + log.debug("Started - "+currentTime); - + ThreadManager tmgr = WebloggerFactory.getWeblogger().getThreadManager(); - + for( RollerTask task : tasks ) { try { // get tasklock for the task TaskLock tasklock = tmgr.getTaskLockByName(task.getName()); - + // TODO: check if task is enabled, otherwise skip if(tasklock == null) { log.debug("SKIPPING task : "+tasklock.getName()); continue; } - + // first, calculate the next allowed run time for the task // based on when the task was last run Date nextRunTime = tasklock.getNextAllowedRun(task.getInterval()); log.debug(task.getName()+": next allowed run time = "+nextRunTime); - + // if we missed the last scheduled run time then see when the // most appropriate next run time should be and wait 'til then boolean needToWait = false; if(currentTime.getTime() > (nextRunTime.getTime() + ONE_MINUTE_MS)) { - + log.debug("MISSED last run, checking if waiting is necessary"); if("startOfDay".equals(task.getStartTimeDesc())) { - // for daily tasks we only run during the first + // for daily tasks we only run during the first // couple minutes of the day Date startOfDay = DateUtil.getStartOfDay(currentTime); if(currentTime.getTime() > startOfDay.getTime() + (2 * ONE_MINUTE_MS)) { @@ -174,7 +174,7 @@ private void runTasks(Date currentTime) { // for immediate tasks we just go ahead and run } } - + // if we are within 1 minute of run time then execute, // otherwise we do nothing long differential = currentTime.getTime() - nextRunTime.getTime(); @@ -182,13 +182,13 @@ private void runTasks(Date currentTime) { log.debug(task.getName()+": LAUNCHING task"); pool.submit(task); } - + } catch(Throwable t) { log.warn(task.getName()+": Unhandled exception caught", t); } } - + log.debug("Finished"); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManager.java index abe583c6eb..75d89af0ed 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManager.java @@ -27,18 +27,18 @@ * Thread management for executing scheduled and asynchronous tasks. */ public interface ThreadManager { - + public static final long MIN_RATE_INTERVAL_MINS = 1; - - + + /** * Initialize the thread management system. * * @throws InitializationException If there is a problem during initialization. */ public void initialize() throws InitializationException; - - + + /** * Execute runnable in background (asynchronously). * @param runnable @@ -46,28 +46,28 @@ public interface ThreadManager { */ public void executeInBackground(Runnable runnable) throws InterruptedException; - - + + /** * Execute runnable in foreground (synchronously). */ public void executeInForeground(Runnable runnable) throws InterruptedException; - - + + /** * Lookup a TaskLock by name. - * + * * @param name The name of the task. * @return The TaskLock for the task, or null if not found. * @throws WebloggerException If there is an error looking up the TaskLock. */ public TaskLock getTaskLockByName(String name) throws WebloggerException; - + /** * Save a TaskLock. - * + * * @param tasklock The TaskLock to save. * @throws WebloggerException If there is an error saving the TaskLock. */ @@ -81,8 +81,8 @@ public void executeInForeground(Runnable runnable) * @return boolean True if lease was registered, False otherwise. */ public boolean registerLease(RollerTask task); - - + + /** * Try to unregister the lease for a given RollerTask. * @@ -90,17 +90,17 @@ public void executeInForeground(Runnable runnable) * @return boolean True if lease was unregistered (or was not leased), False otherwise. */ public boolean unregisterLease(RollerTask task); - - + + /** * Shutdown. */ public void shutdown(); - - + + /** * Release all resources associated with Roller session. */ public void release(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManagerImpl.java index d287dd701f..4971ce33fa 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/ThreadManagerImpl.java @@ -38,41 +38,41 @@ */ @com.google.inject.Singleton public abstract class ThreadManagerImpl implements ThreadManager { - + private static final Log log = LogFactory.getLog(ThreadManagerImpl.class); - + // our own scheduler thread private Thread schedulerThread = null; - + // a simple thread executor private final ExecutorService serviceScheduler; - - + + public ThreadManagerImpl() { - + log.info("Instantiating Thread Manager"); - + serviceScheduler = Executors.newCachedThreadPool(); } - - + + public void initialize() throws InitializationException { - + // initialize tasks, making sure that each task has a tasklock record in the db List webloggerTasks = new ArrayList(); String tasksStr = WebloggerConfig.getProperty("tasks.enabled"); String[] tasks = StringUtils.stripAll(StringUtils.split(tasksStr, ",")); for ( String taskName : tasks ) { - + String taskClassName = WebloggerConfig.getProperty("tasks."+taskName+".class"); if(taskClassName != null) { log.info("Initializing task: "+taskName); - + try { Class taskClass = Class.forName(taskClassName); RollerTask task = (RollerTask) taskClass.newInstance(); task.init(taskName); - + // make sure there is a tasklock record in the db TaskLock taskLock = getTaskLockByName(task.getName()); if (taskLock == null) { @@ -88,10 +88,10 @@ public void initialize() throws InitializationException { // save it this.saveTaskLock(taskLock); } - + // add it to the list of configured tasks webloggerTasks.add(task); - + } catch (ClassCastException ex) { log.warn("Task does not extend RollerTask class", ex); } catch (WebloggerException ex) { @@ -101,10 +101,10 @@ public void initialize() throws InitializationException { } } } - + // create scheduler TaskScheduler scheduler = new TaskScheduler(webloggerTasks); - + // start scheduler thread, but only if it's not already running if (schedulerThread == null && scheduler != null) { log.debug("Starting scheduler thread"); @@ -114,66 +114,66 @@ public void initialize() throws InitializationException { schedulerThread.start(); } } - - + + public void executeInBackground(Runnable runnable) throws InterruptedException { Future task = serviceScheduler.submit(runnable); } - - + + public void executeInForeground(Runnable runnable) throws InterruptedException { Future task = serviceScheduler.submit(runnable); - - // since this task is really meant to be executed within this calling - // thread, here we can add a little code here to loop until it realizes + + // since this task is really meant to be executed within this calling + // thread, here we can add a little code here to loop until it realizes // the task is done while(!task.isDone()) { Thread.sleep(500); } } - - + + public void shutdown() { - + log.debug("starting shutdown sequence"); - + // trigger an immediate shutdown of any backgrounded tasks serviceScheduler.shutdownNow(); - + // only stop if we are already running if(schedulerThread != null) { log.debug("Stopping scheduler"); schedulerThread.interrupt(); } } - - + + public void release() { // no-op } - - + + /** * Default implementation of lease registration, always returns true. - * + * * Subclasses should override this method if they plan to run in an * environment that supports clustered deployments. */ public boolean registerLease(RollerTask task) { return true; } - - + + /** * Default implementation of lease unregistration, always returns true. - * + * * Subclasses should override this method if they plan to run in an * environment that supports clustered deployments. */ public boolean unregisterLease(RollerTask task) { return true; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TurnoverReferersTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TurnoverReferersTask.java index 09f4a19d9f..b082528d7c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TurnoverReferersTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/TurnoverReferersTask.java @@ -38,59 +38,59 @@ public class TurnoverReferersTask extends RollerTaskWithLeasing { // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = null; - + // a String description of when to start this task private String startTimeDesc = "startOfDay"; - + // interval at which the task is run, default is 1 day private int interval = 1440; - + // lease time given to task lock, default is 30 minutes private int leaseTime = 30; - + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - + public void init() throws WebloggerException { this.init(TurnoverReferersTask.NAME); } public void init(String name) throws WebloggerException { super.init(name); - + // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -100,7 +100,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -111,22 +111,22 @@ public void init(String name) throws WebloggerException { } } } - - + + /** * Execute the task. */ public void runTask() { - + try { log.info("task started"); - + Weblogger roller = WebloggerFactory.getWeblogger(); roller.getRefererManager().clearReferrers(); roller.flush(); - + log.info("task completed"); - + } catch (WebloggerException e) { log.error("Error while checking for referer turnover", e); } catch (Exception ee) { @@ -135,10 +135,10 @@ public void runTask() { // always release WebloggerFactory.getWeblogger().release(); } - + } - - + + /** * Main method so that this task may be run from outside the webapp. */ @@ -153,5 +153,5 @@ public static void main(String[] args) throws Exception { System.exit(-1); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/WorkerThread.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/WorkerThread.java index efecaf5a70..3658d496c7 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/WorkerThread.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/runnable/WorkerThread.java @@ -28,13 +28,13 @@ * A generic worker thread that knows how execute a Job. */ public class WorkerThread extends Thread { - + private static Log log = LogFactory.getLog(WorkerThread.class); - + String id = null; Job job = null; - - + + /** * A simple worker. */ @@ -42,8 +42,8 @@ public WorkerThread(String id) { super(id); this.id = id; } - - + + /** * Start off with a job to do. */ @@ -52,15 +52,15 @@ public WorkerThread(String id, Job job) { this.id = id; this.job = job; } - - + + /** * Thread execution. * * We just execute the job we were given if it's non-null. */ public void run() { - + // we only run once if (this.job != null) { // process job @@ -72,23 +72,23 @@ public void run() { "Worker = "+this.id+", "+ "Job = "+this.job.getClass().getName(), t); } - + // since this is a thread we have to make sure that we tidy up ourselves Weblogger roller = WebloggerFactory.getWeblogger(); roller.release(); } - + } - - + + /** * Set the job for this worker. */ public void setJob(Job newJob) { log.debug("NEW JOB: "+newJob.getClass().getName()); - + // set the job this.job = newJob; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/FieldConstants.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/FieldConstants.java index 10f2ea2f60..d357b5ab42 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/FieldConstants.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/FieldConstants.java @@ -22,7 +22,7 @@ * Field constants for indexing blog entries and comments. * @author Mindaugas Idzelis (min@idzelis.com) */ -public final class FieldConstants { +public final class FieldConstants { public static final String ANCHOR = "anchor"; public static final String UPDATED = "updated"; public static final String ID = "id"; diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManager.java index d7df4445ed..12d7a8bf03 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManager.java @@ -31,19 +31,19 @@ public interface IndexManager { /** Does index need to be rebuild */ public abstract boolean isInconsistentAtStartup(); - + /** Remove user from index, returns immediately and operates in background */ public void removeWebsiteIndex(Weblog website) throws WebloggerException; - + /** Remove entry from index, returns immediately and operates in background */ public void removeEntryIndexOperation(WeblogEntry entry) throws WebloggerException; - + /** Add entry to index, returns immediately and operates in background */ public void addEntryIndexOperation(WeblogEntry entry) throws WebloggerException; - + /** R-index entry, returns immediately and operates in background */ public void addEntryReIndexOperation(WeblogEntry entry) throws WebloggerException; - + /** Execute operation immediately */ public abstract void executeIndexOperationNow(final IndexOperation op); @@ -51,16 +51,16 @@ public interface IndexManager * Release all resources associated with Roller session. */ public abstract void release(); - - + + /** * Initialize the search system. * * @throws InitializationException If there is a problem during initialization. */ public void initialize() throws InitializationException; - - + + /** Shutdown to be called on application shutdown */ public abstract void shutdown(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManagerImpl.java index f0388b7d75..60eaa2385c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexManagerImpl.java @@ -47,7 +47,7 @@ /** - * Lucene implementation of IndexManager. This is the central entry point + * Lucene implementation of IndexManager. This is the central entry point * into the Lucene searching API. * @author Mindaugas Idzelis (min@idzelis.com) * @author mraible (formatting and making indexDir configurable) @@ -56,33 +56,33 @@ public class IndexManagerImpl implements IndexManager { //~ Static fields/initializers // ============================================= - + private IndexReader reader; private final Weblogger roller; - + static Log mLogger = LogFactory.getFactory().getInstance( IndexManagerImpl.class); - + //~ Instance fields // ======================================================== - + private boolean searchEnabled = true; - + File indexConsistencyMarker; - + private boolean useRAMIndex = false; - + private RAMDirectory fRAMindex; - + private String indexDir = null; - + private boolean inconsistentAtStartup = false; - + private ReadWriteLock rwl = new ReentrantReadWriteLock(); - + //~ Constructors // =========================================================== - + /** * Creates a new lucene index manager. This should only be created once. * Creating the index manager more than once will definately result in @@ -100,29 +100,29 @@ protected IndexManagerImpl(Weblogger roller) { String enabled = WebloggerConfig.getProperty("search.enabled"); if("false".equalsIgnoreCase(enabled)) this.searchEnabled = false; - + // we also need to know what our index directory is // Note: system property expansion is now handled by WebloggerConfig String searchIndexDir = WebloggerConfig.getProperty("search.index.dir"); this.indexDir = searchIndexDir.replace('/', File.separatorChar); - + // a little debugging mLogger.info("search enabled: " + this.searchEnabled); mLogger.info("index dir: " + this.indexDir); - + String test = indexDir + File.separator + ".index-inconsistent"; indexConsistencyMarker = new File(test); } - - + + /** * @inheritDoc */ public void initialize() throws InitializationException { - + // only initialize the index if search is enabled if (this.searchEnabled) { - + // 1. If inconsistency marker exists. // Delete index // 2. if we're using RAM index @@ -145,10 +145,10 @@ public void initialize() throws InitializationException { mLogger.error(e); } } - + if (indexExists()) { if (useRAMIndex) { - Directory filesystem = getFSDirectory(false); + Directory filesystem = getFSDirectory(false); try { fRAMindex = new RAMDirectory(filesystem); } catch (IOException e) { @@ -165,7 +165,7 @@ public void initialize() throws InitializationException { createIndex(getFSDirectory(true)); } } - + if (isInconsistentAtStartup()) { mLogger.info( "Index was inconsistent. Rebuilding index in the background..."); @@ -178,51 +178,51 @@ public void initialize() throws InitializationException { mLogger.info("Index initialized and ready for use."); } } - + } - - + + //~ Methods // ================================================================ - + public void rebuildWebsiteIndex() throws WebloggerException { scheduleIndexOperation( new RebuildWebsiteIndexOperation(roller, this, null)); } - + public void rebuildWebsiteIndex(Weblog website) throws WebloggerException { scheduleIndexOperation( new RebuildWebsiteIndexOperation(roller, this, website)); } - + public void removeWebsiteIndex(Weblog website) throws WebloggerException { scheduleIndexOperation( new RemoveWebsiteIndexOperation(roller, this, website)); } - + public void addEntryIndexOperation(WeblogEntry entry) throws WebloggerException { AddEntryOperation addEntry = new AddEntryOperation(roller, this, entry); scheduleIndexOperation(addEntry); } - + public void addEntryReIndexOperation(WeblogEntry entry) throws WebloggerException { ReIndexEntryOperation reindex = new ReIndexEntryOperation(roller, this, entry); scheduleIndexOperation(reindex); } - + public void removeEntryIndexOperation(WeblogEntry entry) throws WebloggerException { RemoveEntryOperation removeOp = new RemoveEntryOperation(roller, this, entry); executeIndexOperationNow(removeOp); } - + public ReadWriteLock getReadWriteLock() { return rwl; } - + public boolean isInconsistentAtStartup() { return inconsistentAtStartup; } - + /** * This is the analyzer that will be used to tokenize comment text. * @@ -231,7 +231,7 @@ public boolean isInconsistentAtStartup() { public static final Analyzer getAnalyzer() { return new StandardAnalyzer(); } - + private void scheduleIndexOperation(final IndexOperation op) { try { // only if search is enabled @@ -243,7 +243,7 @@ private void scheduleIndexOperation(final IndexOperation op) { mLogger.error("Error executing operation", e); } } - + /** * @param search */ @@ -258,7 +258,7 @@ public void executeIndexOperationNow(final IndexOperation op) { mLogger.error("Error executing operation", e); } } - + public synchronized void resetSharedReader() { reader = null; } @@ -271,7 +271,7 @@ public synchronized IndexReader getSharedIndexReader() { } return reader; } - + /** * Get the directory that is used by the lucene index. This method will * return null if there is no index at the directory location. If we are @@ -286,26 +286,26 @@ public Directory getIndexDirectory() { return getFSDirectory(false); } } - + private boolean indexExists() { return IndexReader.indexExists(indexDir); } - + Directory getFSDirectory(boolean delete) { Directory directory = null; - + try { directory = FSDirectory.getDirectory(indexDir, delete); } catch (IOException e) { mLogger.error("Problem accessing index directory", e); } - + return directory; } - + private void createIndex(Directory dir) { IndexWriter writer = null; - + try { writer = new IndexWriter(dir, IndexManagerImpl.getAnalyzer(), true); } catch (IOException e) { @@ -319,24 +319,24 @@ private void createIndex(Directory dir) { } } } - + private IndexOperation getSaveIndexOperation() { return new WriteToIndexOperation(this) { public void doRun() { Directory dir = getIndexDirectory(); Directory fsdir = getFSDirectory(true); - + IndexWriter writer = null; - + try { writer = new IndexWriter(fsdir, IndexManagerImpl .getAnalyzer(), true); - + writer.addIndexes(new Directory[] { dir }); indexConsistencyMarker.delete(); } catch (IOException e) { mLogger.error("Problem saving index to disk", e); - + // Delete the directory, since there was a problem saving // the RAM contents getFSDirectory(true); @@ -348,22 +348,22 @@ public void doRun() { mLogger.warn("Unable to close IndexWriter."); } } - + } }; } - + public void release() { // no-op } - + public void shutdown() { if (useRAMIndex) { scheduleIndexOperation(getSaveIndexOperation()); } else { indexConsistencyMarker.delete(); } - + try { if (reader != null) reader.close(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexUtil.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexUtil.java index 74232bc731..649555232b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexUtil.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/IndexUtil.java @@ -32,7 +32,7 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class IndexUtil { - + /** * Create a lucene term from the first token of the input string. * @@ -45,7 +45,7 @@ public static final Term getTerm(String field, String input) { Analyzer analyer = IndexManagerImpl.getAnalyzer(); TokenStream tokens = analyer.tokenStream(field, new StringReader(input)); - + Token token = null; Term term = null; try { @@ -57,5 +57,5 @@ public static final Term getTerm(String field, String input) { } return term; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/AddEntryOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/AddEntryOperation.java index cffe34bb1c..72d883f43a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/AddEntryOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/AddEntryOperation.java @@ -34,19 +34,19 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class AddEntryOperation extends WriteToIndexOperation { - + //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(AddEntryOperation.class); - + //~ Instance fields ======================================================== - + private WeblogEntry data; private Weblogger roller; - + //~ Constructors =========================================================== - + /** * Adds a web log entry into the index. */ @@ -55,12 +55,12 @@ public AddEntryOperation(Weblogger roller, IndexManagerImpl mgr,WeblogEntry data this.roller = roller; this.data = data; } - + //~ Methods ================================================================ - + public void doRun() { IndexWriter writer = beginWriting(); - + // since this operation can be run on a separate thread we must treat // the weblog object passed in as a detached object which is proned to // lazy initialization problems, so requery for the object now @@ -71,7 +71,7 @@ public void doRun() { mLogger.error("Error getting weblogentry object", ex); return; } - + try { if (writer != null) { writer.addDocument(getDocument(data)); @@ -82,5 +82,5 @@ public void doRun() { if (roller != null) roller.release(); endWriting(); } - } + } } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/IndexOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/IndexOperation.java index 63344e1444..976416eba2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/IndexOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/IndexOperation.java @@ -37,7 +37,7 @@ import org.apache.roller.weblogger.config.WebloggerConfig; /** - * This is the base class for all index operation. + * This is the base class for all index operation. * These operations include:
      * SearchOperation
      * AddWeblogOperation
      @@ -125,7 +125,7 @@ protected Document getDocument(WeblogEntry data) { // text doc.add(new Field(FieldConstants.TITLE, - data.getTitle(), + data.getTitle(), Field.Store.YES, Field.Index.ANALYZED)); // index the entry text, but don't store it - moved to end of block diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReIndexEntryOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReIndexEntryOperation.java index 4b3b82ab11..39ee94e370 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReIndexEntryOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReIndexEntryOperation.java @@ -37,19 +37,19 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class ReIndexEntryOperation extends WriteToIndexOperation { - + //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(AddEntryOperation.class); - + //~ Instance fields ======================================================== - + private WeblogEntry data; private Weblogger roller; - + //~ Constructors =========================================================== - + /** * Adds a web log entry into the index. */ @@ -58,11 +58,11 @@ public ReIndexEntryOperation(Weblogger roller, IndexManagerImpl mgr,WeblogEntry this.roller = roller; this.data = data; } - + //~ Methods ================================================================ - + public void doRun() { - + // since this operation can be run on a separate thread we must treat // the weblog object passed in as a detached object which is proned to // lazy initialization problems, so requery for the object now @@ -73,7 +73,7 @@ public void doRun() { mLogger.error("Error getting weblogentry object", ex); return; } - + IndexReader reader = beginDeleting(); try { if (reader != null) { @@ -85,7 +85,7 @@ public void doRun() { } finally { endDeleting(); } - + IndexWriter writer = beginWriting(); try { if (writer != null) { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReadFromIndexOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReadFromIndexOperation.java index 787fb4fe13..e3f96a2d97 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReadFromIndexOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/ReadFromIndexOperation.java @@ -28,10 +28,10 @@ public abstract class ReadFromIndexOperation extends IndexOperation { public ReadFromIndexOperation(IndexManagerImpl mgr) { super(mgr); } - + private static Log mLogger = LogFactory.getFactory().getInstance( ReadFromIndexOperation.class); - + public final void run() { try { manager.getReadWriteLock().readLock().lock(); @@ -43,5 +43,5 @@ public final void run() { manager.getReadWriteLock().readLock().unlock(); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RebuildWebsiteIndexOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RebuildWebsiteIndexOperation.java index 0e8ae381ae..bbfbe3b1b1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RebuildWebsiteIndexOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RebuildWebsiteIndexOperation.java @@ -43,19 +43,19 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class RebuildWebsiteIndexOperation extends WriteToIndexOperation { - + //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(RebuildWebsiteIndexOperation.class); - + //~ Instance fields ======================================================== - + private Weblog website; private Weblogger roller; - + //~ Constructors =========================================================== - + /** * Create a new operation that will recreate an index. * @@ -66,13 +66,13 @@ public RebuildWebsiteIndexOperation(Weblogger roller, IndexManagerImpl mgr, Webl this.roller = roller; this.website = website; } - + //~ Methods ================================================================ - + public void doRun() { Date start = new Date(); - + // since this operation can be run on a separate thread we must treat // the weblog object passed in as a detached object which is proned to // lazy initialization problems, so requery for the object now @@ -89,7 +89,7 @@ public void doRun() { } IndexReader reader = beginDeleting(); - + try { if (reader != null) { Term tWebsite = null; @@ -111,14 +111,14 @@ public void doRun() { } finally { endDeleting(); } - + IndexWriter writer = beginWriting(); - + try { if (writer != null) { WeblogEntryManager weblogManager = roller.getWeblogEntryManager(); - List entries = weblogManager .getWeblogEntries( - website, // website + List entries = weblogManager .getWeblogEntries( + website, // website null, null, // startDate null, // endDate @@ -126,7 +126,7 @@ public void doRun() { null,WeblogEntry.PUBLISHED, // status null, // text null, // sortby (null means pubTime) - null, + null, null, 0, -1); // offset, length, locale mLogger.debug("Entries to index: " + entries.size()); @@ -146,10 +146,10 @@ public void doRun() { endWriting(); if (roller != null) roller.release(); } - + Date end = new Date(); double length = (end.getTime() - start.getTime()) / (double) 1000; - + if (website == null) { mLogger.info( "Completed rebuilding index for all users in '" + length + "' secs"); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveEntryOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveEntryOperation.java index 23bce84979..816c33c252 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveEntryOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveEntryOperation.java @@ -37,29 +37,29 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class RemoveEntryOperation extends WriteToIndexOperation { - + //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(RemoveEntryOperation.class); - + //~ Instance fields ======================================================== - + private WeblogEntry data; private Weblogger roller; - + //~ Constructors =========================================================== - + public RemoveEntryOperation(Weblogger roller, IndexManagerImpl mgr,WeblogEntry data) { super(mgr); this.roller = roller; this.data = data; } - + //~ Methods ================================================================ - + public void doRun() { - + // since this operation can be run on a separate thread we must treat // the weblog object passed in as a detached object which is proned to // lazy initialization problems, so requery for the object now @@ -70,7 +70,7 @@ public void doRun() { mLogger.error("Error getting weblogentry object", ex); return; } - + IndexReader reader = beginDeleting(); try { if (reader != null) { @@ -83,6 +83,6 @@ public void doRun() { endDeleting(); } } - - + + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveWebsiteIndexOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveWebsiteIndexOperation.java index 449ee314fc..3bd394a0d9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveWebsiteIndexOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/RemoveWebsiteIndexOperation.java @@ -38,19 +38,19 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public class RemoveWebsiteIndexOperation extends WriteToIndexOperation { - + //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(RemoveWebsiteIndexOperation.class); - + //~ Instance fields ======================================================== - + private Weblog website; private Weblogger roller; - + //~ Constructors =========================================================== - + /** * Create a new operation that will recreate an index. * @param website The website to rebuild the index for, or null for all sites. @@ -60,12 +60,12 @@ public RemoveWebsiteIndexOperation(Weblogger roller, IndexManagerImpl mgr, Weblo this.roller = roller; this.website = website; } - + //~ Methods ================================================================ - + public void doRun() { Date start = new Date(); - + // since this operation can be run on a separate thread we must treat // the weblog object passed in as a detached object which is proned to // lazy initialization problems, so requery for the object now @@ -75,7 +75,7 @@ public void doRun() { mLogger.error("Error getting website object", ex); return; } - + IndexReader reader = beginDeleting(); try { if (reader != null) { @@ -85,7 +85,7 @@ public void doRun() { } Term tHandle = IndexUtil.getTerm(FieldConstants.WEBSITE_HANDLE, handle); - + if (tHandle != null) { reader.deleteDocuments(tHandle); } @@ -95,10 +95,10 @@ public void doRun() { } finally { endDeleting(); } - + Date end = new Date(); double length = (end.getTime() - start.getTime()) / (double) 1000; - + if (website != null) { mLogger.info("Completed deleting indices for website '" + website.getName() + "' in '" + length + "' seconds"); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/SearchOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/SearchOperation.java index 925582bc37..779126f763 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/SearchOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/SearchOperation.java @@ -49,10 +49,10 @@ public class SearchOperation extends ReadFromIndexOperation { //~ Static fields/initializers ============================================= - + private static Log mLogger = LogFactory.getFactory().getInstance(SearchOperation.class); - + private static String[] SEARCH_FIELDS = new String[] { FieldConstants.CONTENT, FieldConstants.TITLE, @@ -63,23 +63,23 @@ public class SearchOperation extends ReadFromIndexOperation { private static BooleanClause.Occur[] SEARCH_FLAGS = new BooleanClause.Occur[] { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, - BooleanClause.Occur.SHOULD, + BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD }; private static Sort SORTER = new Sort( new SortField( FieldConstants.PUBLISHED, SortField.STRING, true) ); - + //~ Instance fields ======================================================== - + private String term; private String websiteHandle; private String category; private Hits searchresults; private String parseError; - + //~ Constructors =========================================================== - + /** * Create a new operation that searches the index. */ @@ -87,21 +87,21 @@ public SearchOperation(IndexManager mgr) { // TODO: finish moving IndexManager to backend, so this cast is not needed super((IndexManagerImpl)mgr); } - + //~ Methods ================================================================ - + public void setTerm(String term) { this.term = term; } - + /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void doRun() { searchresults = null; - + IndexSearcher searcher = null; - + try { IndexReader reader = manager.getSharedIndexReader(); searcher = new IndexSearcher(reader); @@ -109,20 +109,20 @@ public void doRun() { Query query = MultiFieldQueryParser.parse(term, SEARCH_FIELDS, SEARCH_FLAGS, new StandardAnalyzer(Version.LUCENE_CURRENT)); - + Term tUsername = IndexUtil.getTerm(FieldConstants.WEBSITE_HANDLE, websiteHandle); - + if (tUsername != null) { BooleanQuery bQuery = new BooleanQuery(); bQuery.add(query, BooleanClause.Occur.MUST); bQuery.add(new TermQuery(tUsername), BooleanClause.Occur.MUST); query = bQuery; } - + Term tCategory = IndexUtil.getTerm(FieldConstants.CATEGORY, category); - + if (tCategory != null) { BooleanQuery bQuery = new BooleanQuery(); bQuery.add(query, BooleanClause.Occur.MUST); @@ -141,33 +141,33 @@ public void doRun() { } // don't need to close the reader, since we didn't do any writing! } - + public Hits getResults() { return searchresults; } - + public int getResultsCount() { if (searchresults == null) return -1; - + return searchresults.length(); } - + public String getParseError() { return parseError; } - + /** * @param string */ public void setWebsiteHandle(String websiteHandle) { this.websiteHandle = websiteHandle; } - + /** * @param parameter */ public void setCategory(String category) { this.category = category; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/WriteToIndexOperation.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/WriteToIndexOperation.java index e1dce1c70a..e88ea0dbd6 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/WriteToIndexOperation.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/search/operations/WriteToIndexOperation.java @@ -27,14 +27,14 @@ * @author Mindaugas Idzelis (min@idzelis.com) */ public abstract class WriteToIndexOperation extends IndexOperation { - + public WriteToIndexOperation(IndexManagerImpl mgr) { super(mgr); } - + private static Log mLogger = LogFactory.getFactory().getInstance(WriteToIndexOperation.class); - + public void run() { try { manager.getReadWriteLock().writeLock().lock(); @@ -44,7 +44,7 @@ public void run() { } catch (Exception e) { mLogger.error("Error acquiring write lock on index", e); - + } finally { manager.getReadWriteLock().writeLock().unlock(); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/ClasspathDatabaseScriptProvider.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/ClasspathDatabaseScriptProvider.java index f36c4083f2..75ee8f26a8 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/ClasspathDatabaseScriptProvider.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/ClasspathDatabaseScriptProvider.java @@ -25,10 +25,10 @@ * Reads dbscripts from the classpath. */ public class ClasspathDatabaseScriptProvider implements DatabaseScriptProvider { - + public InputStream getDatabaseScript(String path) { String resourcePath = "/dbscripts/" + path; return this.getClass().getResourceAsStream(resourcePath); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseInstaller.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseInstaller.java index 39af3d81d4..32cd762d99 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseInstaller.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseInstaller.java @@ -40,57 +40,57 @@ * has configured their installation type to 'auto'. */ public class DatabaseInstaller { - + private static Log log = LogFactory.getLog(DatabaseInstaller.class); - + private final DatabaseProvider db; private final DatabaseScriptProvider scripts; private final String version; private List messages = new ArrayList(); - + // the name of the property which holds the dbversion value private static final String DBVERSION_PROP = "roller.database.version"; - - + + public DatabaseInstaller(DatabaseProvider dbProvider, DatabaseScriptProvider scriptProvider) { db = dbProvider; scripts = scriptProvider; - + Properties props = new Properties(); try { props.load(getClass().getResourceAsStream("/roller-version.properties")); } catch (IOException e) { log.error("roller-version.properties not found", e); } - + version = props.getProperty("ro.version", "UNKNOWN"); } - - - /** + + + /** * Determine if database schema needs to be upgraded. */ public boolean isCreationRequired() { Connection con = null; - try { + try { con = db.getConnection(); - + // just check for a couple key Roller tables if (tableExists(con, "rolleruser") && tableExists(con, "userrole")) { return false; } - + } catch (Throwable t) { - throw new RuntimeException("Error checking for tables", t); + throw new RuntimeException("Error checking for tables", t); } finally { try { if (con != null) con.close(); } catch (Exception ignored) {} } - + return true; } - - - /** + + + /** * Determine if database schema needs to be upgraded. */ public boolean isUpgradeRequired() { @@ -101,7 +101,7 @@ public boolean isUpgradeRequired() { } catch (StartupException ex) { throw new RuntimeException(ex); } - + // if dbversion is unset then assume a new install, otherwise compare if (databaseVersion < 0) { // if this is a fresh db then we need to set the database version @@ -125,38 +125,38 @@ public boolean isUpgradeRequired() { return databaseVersion < desiredVersion; } } - - + + public List getMessages() { return messages; } - - + + private void errorMessage(String msg) { messages.add(msg); log.error(msg); - } - - + } + + private void errorMessage(String msg, Throwable t) { messages.add(msg); log.error(msg, t); } - - + + private void successMessage(String msg) { messages.add(msg); log.trace(msg); } - - + + /** * Create datatabase tables. */ public void createDatabase() throws StartupException { - + log.info("Creating Roller Weblogger database tables."); - + Connection con = null; SQLScriptRunner create = null; try { @@ -165,15 +165,15 @@ public void createDatabase() throws StartupException { create = new SQLScriptRunner(scripts.getDatabaseScript(handle + "/createdb.sql")); create.runScript(con, true); messages.addAll(create.getMessages()); - + setDatabaseVersion(con, version); - + } catch (SQLException sqle) { log.error("ERROR running SQL in database creation script", sqle); if (create != null) messages.addAll(create.getMessages()); errorMessage("ERROR running SQL in database creation script"); - throw new StartupException("Error running sql script", sqle); - + throw new StartupException("Error running sql script", sqle); + } catch (Exception ioe) { log.error("ERROR running database creation script", ioe); if (create != null) messages.addAll(create.getMessages()); @@ -184,19 +184,19 @@ public void createDatabase() throws StartupException { try { if (con != null) con.close(); } catch (Exception ignored) {} } } - - + + /** * Upgrade database if dbVersion is older than desiredVersion. */ public void upgradeDatabase(boolean runScripts) throws StartupException { - + int myVersion = parseVersionString(version); int dbversion = getDatabaseVersion(); - + log.debug("Database version = "+dbversion); log.debug("Desired version = "+myVersion); - + Connection con = null; try { con = db.getConnection(); @@ -250,19 +250,19 @@ public void upgradeDatabase(boolean runScripts) throws StartupException { upgradeTo500(con, runScripts); dbversion = 500; } - + // make sure the database version is the exact version // we are upgrading too. updateDatabaseVersion(con, myVersion); - + } catch (SQLException e) { throw new StartupException("ERROR obtaining connection"); } finally { try { if (con != null) con.close(); } catch (Exception ignored) {} } } - - + + /** * Upgrade database for Roller 1.3.0 */ @@ -272,12 +272,12 @@ private void upgradeTo130(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/120-to-130-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); } - + /* * The new theme management code is going into place and it uses * the old website.themeEditor attribute to store a users theme. @@ -290,31 +290,31 @@ private void upgradeTo130(Connection con, boolean runScripts) throws StartupExce * would be suprised that their template customizations are no longer * in effect because they are using a shared theme instead. */ - + successMessage("Doing upgrade to 130 ..."); successMessage("Ensuring that all website themes are set to custom"); - + PreparedStatement setCustomThemeStmt = con.prepareStatement( "update website set editortheme = ?"); - + setCustomThemeStmt.setString(1, org.apache.roller.weblogger.pojos.WeblogTheme.CUSTOM); setCustomThemeStmt.executeUpdate(); - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Upgrade to 130 complete."); - + } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - - errorMessage("Problem upgrading database to version 130", e); + + errorMessage("Problem upgrading database to version 130", e); throw new StartupException("Problem upgrading database to version 130", e); } - + updateDatabaseVersion(con, 130); } - + /** * Upgrade database for Roller 2.0.0 */ @@ -324,15 +324,15 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/130-to-200-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); } - + successMessage("Doing upgrade to 200 ..."); successMessage("Populating roller_user_permissions table"); - + PreparedStatement websitesQuery = con.prepareStatement( "select w.id as wid, u.id as uid, u.username as uname from " + "website as w, rolleruser as u where u.id=w.userid"); @@ -346,7 +346,7 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce "insert into roller_permissions " + "(id, username, actions, objectid, objecttype, pending, datecreated) " + "values (?,?,?,?,?,?,?)"); - + // loop through websites, each has a user java.sql.Date now = new java.sql.Date(new Date().getTime()); ResultSet websiteSet = websitesQuery.executeQuery(); @@ -355,13 +355,13 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce String userid = websiteSet.getString("uid"); String username = websiteSet.getString("uname"); successMessage("Processing website: " + username); - + // use website user's username as website handle websiteUpdate.clearParameters(); websiteUpdate.setString(1, username); websiteUpdate.setString(2, websiteid); websiteUpdate.executeUpdate(); - + // update all of pubished entries to include userid and status entryUpdate.clearParameters(); entryUpdate.setString( 1, userid); @@ -369,7 +369,7 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce entryUpdate.setBoolean(3, true); entryUpdate.setString( 4, websiteid); entryUpdate.executeUpdate(); - + // update all of draft entries to include userid and status entryUpdate.clearParameters(); entryUpdate.setString( 1, userid); @@ -377,7 +377,7 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce entryUpdate.setBoolean(3, false); entryUpdate.setString( 4, websiteid); entryUpdate.executeUpdate(); - + // add permission for user in website permsInsert.clearParameters(); permsInsert.setString( 1, websiteid+"p"); @@ -390,23 +390,23 @@ private void upgradeTo200(Connection con, boolean runScripts) throws StartupExce permsInsert.setBoolean(5, false); permsInsert.executeUpdate(); } - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Upgrade to 200 complete."); - + } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 200", e); throw new StartupException("Problem upgrading database to version 200", e); } - + updateDatabaseVersion(con, 200); } - - + + /** * Upgrade database for Roller 2.1.0 */ @@ -416,12 +416,12 @@ private void upgradeTo210(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/200-to-210-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); } - + /* * For Roller 2.1.0 we are going to standardize some of the * weblog templates and make them less editable. To do this @@ -430,34 +430,34 @@ private void upgradeTo210(Connection con, boolean runScripts) throws StartupExce * The goal for this upgrade is to ensure that ALL weblogs now have * the required "Weblog" template as their default template. */ - + successMessage("Doing upgrade to 210 ..."); successMessage("Ensuring that all weblogs use the 'Weblog' template as their default page"); - + // this query will give us all websites that have modified their // default page to link to something other than "Weblog" PreparedStatement selectUpdateWeblogs = con.prepareStatement( "select website.id,template,website.handle from website,webpage "+ "where webpage.id = website.defaultpageid "+ "and webpage.link != 'Weblog'"); - + PreparedStatement selectWeblogTemplate = con.prepareStatement( "select id from webpage where websiteid = ? and link = 'Weblog'"); - + PreparedStatement updateWeblogTemplate = con.prepareStatement( "update webpage set template = ? where id = ?"); - + // insert a new template for a website PreparedStatement insertWeblogTemplate = con.prepareStatement( "insert into webpage"+ "(id, name, description, link, websiteid, template, updatetime) "+ "values(?,?,?,?,?,?,?)"); - + // update the default page for a website PreparedStatement updateDefaultPage = con.prepareStatement( "update website set defaultpageid = ? "+ "where id = ?"); - + String description = "This template is used to render the main "+ "page of your weblog."; ResultSet websiteSet = selectUpdateWeblogs.executeQuery(); @@ -467,9 +467,9 @@ private void upgradeTo210(Connection con, boolean runScripts) throws StartupExce String template = websiteSet.getString(2); String handle = websiteSet.getString(3); successMessage("Processing website: " + handle); - + String defaultpageid = null; - + // it's possible that this weblog has a "Weblog" template, but just // isn't using it as their default. if so we need to fix that. selectWeblogTemplate.clearParameters(); @@ -478,12 +478,12 @@ private void upgradeTo210(Connection con, boolean runScripts) throws StartupExce if(weblogPageSet.next()) { // this person already has a "Weblog" template, so update it String id = weblogPageSet.getString(1); - + updateWeblogTemplate.clearParameters(); updateWeblogTemplate.setString(1, template); updateWeblogTemplate.setString(2, id); updateWeblogTemplate.executeUpdate(); - + // make sure and adjust what default page id we want to use defaultpageid = id; } else { @@ -497,35 +497,35 @@ private void upgradeTo210(Connection con, boolean runScripts) throws StartupExce insertWeblogTemplate.setString( 6, template); insertWeblogTemplate.setDate( 7, new java.sql.Date(now.getTime())); insertWeblogTemplate.executeUpdate(); - + // set the new default page id defaultpageid = websiteid+"q"; } - + // update defaultpageid value updateDefaultPage.clearParameters(); updateDefaultPage.setString( 1, defaultpageid); updateDefaultPage.setString( 2, websiteid); updateDefaultPage.executeUpdate(); } - - + + if (!con.getAutoCommit()) con.commit(); - + successMessage("Upgrade to 210 complete."); - + } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + log.error("Problem upgrading database to version 210", e); throw new StartupException("Problem upgrading database to version 210", e); } - + updateDatabaseVersion(con, 210); } - - + + /** * Upgrade database for Roller 2.3.0 */ @@ -535,7 +535,7 @@ private void upgradeTo230(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/210-to-230-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); @@ -543,15 +543,15 @@ private void upgradeTo230(Connection con, boolean runScripts) throws StartupExce } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 230", e); throw new StartupException("Problem upgrading database to version 230", e); } - + updateDatabaseVersion(con, 230); } - - + + /** * Upgrade database for Roller 2.4.0 */ @@ -561,7 +561,7 @@ private void upgradeTo240(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/230-to-240-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); @@ -569,15 +569,15 @@ private void upgradeTo240(Connection con, boolean runScripts) throws StartupExce } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 240", e); throw new StartupException("Problem upgrading database to version 240", e); } - + updateDatabaseVersion(con, 240); } - - + + /** * Upgrade database for Roller 3.0.0 */ @@ -587,12 +587,12 @@ private void upgradeTo300(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/240-to-300-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); } - + /* * For Roller 3.0.0 we are allowing each weblogentry to track a * locale now so that we can support multi-lingual blogs. As part @@ -601,14 +601,14 @@ private void upgradeTo300(Connection con, boolean runScripts) throws StartupExce * 1. make sure all weblogs have a locale * 2. set the locale on all entries to the locale for the weblog */ - + successMessage("Doing upgrade to 300 ..."); - + // get system default language String locale = java.util.Locale.getDefault().getLanguage(); - + successMessage("Setting website locale to "+locale+" for websites with no locale"); - + // update all weblogs where locale is "null" PreparedStatement updateNullWeblogLocale = con.prepareStatement( "update website set locale = ? where locale is NULL"); @@ -620,48 +620,48 @@ private void upgradeTo300(Connection con, boolean runScripts) throws StartupExce updateNullWeblogLocale.executeUpdate(); updateEmptyWeblogLocale.executeUpdate(); - + successMessage("Setting weblogentry locales to website locale"); - + // get all entries and the locale of its website PreparedStatement selectWeblogsLocale = con.prepareStatement( "select weblogentry.id,website.locale "+ "from weblogentry,website "+ "where weblogentry.websiteid = website.id"); - + // set the locale for an entry PreparedStatement updateWeblogLocale = con.prepareStatement( "update weblogentry set locale = ? where id = ?"); - + ResultSet websiteSet = selectWeblogsLocale.executeQuery(); while (websiteSet.next()) { String entryid = websiteSet.getString(1); String entrylocale = websiteSet.getString(2); - + // update entry locale updateWeblogLocale.clearParameters(); updateWeblogLocale.setString( 1, entrylocale); updateWeblogLocale.setString( 2, entryid); updateWeblogLocale.executeUpdate(); } - - + + if (!con.getAutoCommit()) con.commit(); - + successMessage("Upgrade to 300 complete."); - + } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 300", e); throw new StartupException("Problem upgrading database to version 300", e); } - + updateDatabaseVersion(con, 300); } - - + + /** * Upgrade database for Roller 3.1.0 */ @@ -671,7 +671,7 @@ private void upgradeTo310(Connection con, boolean runScripts) throws StartupExce if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/300-to-310-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); @@ -679,29 +679,29 @@ private void upgradeTo310(Connection con, boolean runScripts) throws StartupExce } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 310", e); throw new StartupException("Problem upgrading database to version 310", e); } - + updateDatabaseVersion(con, 310); } - - + + /** * Upgrade database for Roller 4.0.0 */ private void upgradeTo400(Connection con, boolean runScripts) throws StartupException { - + successMessage("Doing upgrade to 400 ..."); - - // first we need to run upgrade scripts + + // first we need to run upgrade scripts SQLScriptRunner runner = null; - try { + try { if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/310-to-400-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); @@ -709,74 +709,74 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce } catch(Exception ex) { log.error("ERROR running 400 database upgrade script", ex); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 400", ex); throw new StartupException("Problem upgrading database to version 400", ex); } - - + + // now upgrade hierarchical objects data model try { successMessage("Populating parentid columns for weblogcategory and folder tables"); - + // Populate parentid in weblogcategory and folder tables. // - // We'd like to do something like the below, but few databases + // We'd like to do something like the below, but few databases // support multiple table udpates, which are part of SQL-99 // - // update weblogcategory, weblogcategoryassoc - // set weblogcategory.parentid = weblogcategoryassoc.ancestorid - // where - // weblogcategory.id = weblogcategoryassoc.categoryid + // update weblogcategory, weblogcategoryassoc + // set weblogcategory.parentid = weblogcategoryassoc.ancestorid + // where + // weblogcategory.id = weblogcategoryassoc.categoryid // and weblogcategoryassoc.relation = 'PARENT'; // - // update folder,folderassoc - // set folder.parentid = folderassoc.ancestorid - // where - // folder.id = folderassoc.folderid + // update folder,folderassoc + // set folder.parentid = folderassoc.ancestorid + // where + // folder.id = folderassoc.folderid // and folderassoc.relation = 'PARENT'; - + PreparedStatement selectParents = con.prepareStatement( "select categoryid, ancestorid from weblogcategoryassoc where relation='PARENT'"); PreparedStatement updateParent = con.prepareStatement( - "update weblogcategory set parentid=? where id=?"); + "update weblogcategory set parentid=? where id=?"); ResultSet parentSet = selectParents.executeQuery(); while (parentSet.next()) { String categoryid = parentSet.getString(1); - String parentid = parentSet.getString(2); + String parentid = parentSet.getString(2); updateParent.clearParameters(); updateParent.setString( 1, parentid); updateParent.setString( 2, categoryid); updateParent.executeUpdate(); } - + selectParents = con.prepareStatement( "select folderid, ancestorid from folderassoc where relation='PARENT'"); updateParent = con.prepareStatement( - "update folder set parentid=? where id=?"); + "update folder set parentid=? where id=?"); parentSet = selectParents.executeQuery(); while (parentSet.next()) { String folderid = parentSet.getString(1); - String parentid = parentSet.getString(2); + String parentid = parentSet.getString(2); updateParent.clearParameters(); updateParent.setString( 1, parentid); updateParent.setString( 2, folderid); updateParent.executeUpdate(); } - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Done populating parentid columns."); - + } catch (Exception e) { errorMessage("Problem upgrading database to version 320", e); throw new StartupException("Problem upgrading database to version 320", e); } - - + + try { successMessage("Populating path columns for weblogcategory and folder tables."); - + // Populate path in weblogcategory and folder tables. // // It would be nice if there was a simple sql solution for doing @@ -784,13 +784,13 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce // force walking the hierarchical trees. Luckily, it seems that // most people don't create multi-level hierarchies, so hopefully // this won't be too bad - + // set path to '/' for nodes with no parents (aka root nodes) PreparedStatement setRootPaths = con.prepareStatement( "update weblogcategory set path = '/' where parentid is NULL"); setRootPaths.clearParameters(); setRootPaths.executeUpdate(); - + // select all nodes whose parent has no parent (aka 1st level nodes) PreparedStatement selectL1Children = con.prepareStatement( "select f.id, f.name from weblogcategory f, weblogcategory p "+ @@ -801,17 +801,17 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce ResultSet L1Set = selectL1Children.executeQuery(); while (L1Set.next()) { String id = L1Set.getString(1); - String name = L1Set.getString(2); + String name = L1Set.getString(2); updateL1Children.clearParameters(); updateL1Children.setString( 1, "/"+name); updateL1Children.setString( 2, id); updateL1Children.executeUpdate(); } - + // now for the complicated part =( // we need to keep iterating over L2, L3, etc nodes and setting // their path until all nodes have been updated. - + // select all nodes whose parent path has been set, excluding L1 nodes PreparedStatement selectLxChildren = con.prepareStatement( "select f.id, f.name, p.path from weblogcategory f, weblogcategory p "+ @@ -820,17 +820,17 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce // update Lx nodes with their path (/) PreparedStatement updateLxChildren = con.prepareStatement( "update weblogcategory set path=? where id=?"); - + // this loop allows us to run this part of the upgrade process as // long as is necessary based on the depth of the hierarchy, and // we use the do/while construct to ensure it's run at least once int catNumCounted = 0; do { log.debug("Doing pass over Lx children for categories"); - + // reset count for each iteration of outer loop catNumCounted = 0; - + ResultSet LxSet = selectLxChildren.executeQuery(); while (LxSet.next()) { String id = LxSet.getString(1); @@ -840,22 +840,22 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce updateLxChildren.setString( 1, parentPath+"/"+name); updateLxChildren.setString( 2, id); updateLxChildren.executeUpdate(); - + // count the updated rows catNumCounted++; } - + log.debug("Updated "+catNumCounted+" Lx category paths"); } while(catNumCounted > 0); - - - + + + // set path to '/' for nodes with no parents (aka root nodes) setRootPaths = con.prepareStatement( "update folder set path = '/' where parentid is NULL"); setRootPaths.clearParameters(); setRootPaths.executeUpdate(); - + // select all nodes whose parent has no parent (aka 1st level nodes) selectL1Children = con.prepareStatement( "select f.id, f.name from folder f, folder p "+ @@ -866,17 +866,17 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce L1Set = selectL1Children.executeQuery(); while (L1Set.next()) { String id = L1Set.getString(1); - String name = L1Set.getString(2); + String name = L1Set.getString(2); updateL1Children.clearParameters(); updateL1Children.setString( 1, "/"+name); updateL1Children.setString( 2, id); updateL1Children.executeUpdate(); } - + // now for the complicated part =( // we need to keep iterating over L2, L3, etc nodes and setting // their path until all nodes have been updated. - + // select all nodes whose parent path has been set, excluding L1 nodes selectLxChildren = con.prepareStatement( "select f.id, f.name, p.path from folder f, folder p "+ @@ -885,17 +885,17 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce // update Lx nodes with their path (/) updateLxChildren = con.prepareStatement( "update folder set path=? where id=?"); - + // this loop allows us to run this part of the upgrade process as // long as is necessary based on the depth of the hierarchy, and // we use the do/while construct to ensure it's run at least once int folderNumUpdated = 0; do { log.debug("Doing pass over Lx children for folders"); - + // reset count for each iteration of outer loop folderNumUpdated = 0; - + ResultSet LxSet = selectLxChildren.executeQuery(); while (LxSet.next()) { String id = LxSet.getString(1); @@ -905,30 +905,30 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce updateLxChildren.setString( 1, parentPath+"/"+name); updateLxChildren.setString( 2, id); updateLxChildren.executeUpdate(); - + // count the updated rows folderNumUpdated++; } - + log.debug("Updated "+folderNumUpdated+" Lx folder paths"); } while(folderNumUpdated > 0); - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Done populating path columns."); - + } catch (SQLException e) { log.error("Problem upgrading database to version 320", e); throw new StartupException("Problem upgrading database to version 320", e); } - - + + // 4.0 changes the planet data model a bit, so we need to clean that up try { successMessage("Merging planet groups 'all' and 'external'"); - + // Move all subscriptions in the planet group 'external' to group 'all' - + String allGroupId = null; PreparedStatement selectAllGroupId = con.prepareStatement( "select id from rag_group where handle = 'all'"); @@ -936,15 +936,15 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce if (rs.next()) { allGroupId = rs.getString(1); } - + String externalGroupId = null; PreparedStatement selectExternalGroupId = con.prepareStatement( - "select id from rag_group where handle = 'external'"); + "select id from rag_group where handle = 'external'"); rs = selectExternalGroupId.executeQuery(); if (rs.next()) { externalGroupId = rs.getString(1); } - + // we only need to merge if both of those groups already existed if(allGroupId != null && externalGroupId != null) { PreparedStatement updateGroupSubs = con.prepareStatement( @@ -953,57 +953,57 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce updateGroupSubs.setString( 1, allGroupId); updateGroupSubs.setString( 2, externalGroupId); updateGroupSubs.executeUpdate(); - + // we no longer need the group 'external' PreparedStatement deleteExternalGroup = con.prepareStatement( "delete from rag_group where handle = 'external'"); deleteExternalGroup.executeUpdate(); - + // if we only have group 'external' then just rename it to 'all' } else if(allGroupId == null && externalGroupId != null) { - + // rename 'external' to 'all' PreparedStatement renameExternalGroup = con.prepareStatement( "update rag_group set handle = 'all' where handle = 'external'"); renameExternalGroup.executeUpdate(); } - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Planet group 'external' merged into group 'all'."); - + } catch (Exception e) { errorMessage("Problem upgrading database to version 400", e); throw new StartupException("Problem upgrading database to version 400", e); } - - + + // update local planet subscriptions to use new local feed format try { successMessage("Upgrading local planet subscription feeds to new feed url format"); - + // need to start by looking up absolute site url - PreparedStatement selectAbsUrl = + PreparedStatement selectAbsUrl = con.prepareStatement("select value from roller_properties where name = 'site.absoluteurl'"); String absUrl = null; ResultSet rs = selectAbsUrl.executeQuery(); if(rs.next()) { absUrl = rs.getString(1); } - + if(absUrl != null && absUrl.length() > 0) { - PreparedStatement selectSubs = + PreparedStatement selectSubs = con.prepareStatement("select id,feed_url,author from rag_subscription"); - - PreparedStatement updateSubUrl = + + PreparedStatement updateSubUrl = con.prepareStatement("update rag_subscription set last_updated=last_updated, feed_url = ? where id = ?"); - + ResultSet rset = selectSubs.executeQuery(); while (rset.next()) { String id = rset.getString(1); String feed_url = rset.getString(2); String handle = rset.getString(3); - + // only work on local feed urls if (feed_url.startsWith(absUrl)) { // update feed_url to 'weblogger:' @@ -1014,21 +1014,21 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce } } } - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Comments successfully updated to use new comment plugins."); - + } catch (Exception e) { errorMessage("Problem upgrading database to version 400", e); throw new StartupException("Problem upgrading database to version 400", e); } - - + + // upgrade comments to use new plugin mechanism try { successMessage("Upgrading existing comments with content-type & plugins"); - + // look in db and see if comment autoformatting is enabled boolean autoformatEnabled = false; String autoformat = null; @@ -1041,7 +1041,7 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce autoformatEnabled = true; } } - + // look in db and see if comment html escaping is enabled boolean htmlEnabled = false; String escapehtml = null; @@ -1055,7 +1055,7 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce htmlEnabled = true; } } - + // first lets set the new 'users.comments.htmlenabled' property PreparedStatement addCommentHtmlProp = con.prepareStatement("insert into roller_properties(name,value) values(?,?)"); addCommentHtmlProp.clearParameters(); @@ -1066,13 +1066,13 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce addCommentHtmlProp.setString(2, "false"); } addCommentHtmlProp.executeUpdate(); - + // determine content-type for existing comments String contentType = "text/plain"; if(htmlEnabled) { contentType = "text/html"; } - + // determine plugins for existing comments String plugins = ""; if(htmlEnabled && autoformatEnabled) { @@ -1082,55 +1082,55 @@ private void upgradeTo400(Connection con, boolean runScripts) throws StartupExce } else if(autoformatEnabled) { plugins = "AutoFormat"; } - + // set new comment plugins configuration property 'users.comments.plugins' - PreparedStatement addCommentPluginsProp = + PreparedStatement addCommentPluginsProp = con.prepareStatement("insert into roller_properties(name,value) values(?,?)"); addCommentPluginsProp.clearParameters(); addCommentPluginsProp.setString(1, "users.comments.plugins"); addCommentPluginsProp.setString(2, plugins); addCommentPluginsProp.executeUpdate(); - + // set content-type for all existing comments - PreparedStatement updateCommentsContentType = + PreparedStatement updateCommentsContentType = con.prepareStatement("update roller_comment set posttime=posttime, contenttype = ?"); updateCommentsContentType.clearParameters(); updateCommentsContentType.setString(1, contentType); updateCommentsContentType.executeUpdate(); // set plugins for all existing comments - PreparedStatement updateCommentsPlugins = + PreparedStatement updateCommentsPlugins = con.prepareStatement("update roller_comment set posttime=posttime, plugins = ?"); updateCommentsPlugins.clearParameters(); updateCommentsPlugins.setString(1, plugins); updateCommentsPlugins.executeUpdate(); - + if (!con.getAutoCommit()) con.commit(); - + successMessage("Comments successfully updated to use new comment plugins."); - + } catch (Exception e) { errorMessage("Problem upgrading database to version 400", e); throw new StartupException("Problem upgrading database to version 400", e); } - + // finally, upgrade db version string to 400 updateDatabaseVersion(con, 400); } - - + + /** * Upgrade database for Roller 4.1.0 */ private void upgradeTo500(Connection con, boolean runScripts) throws StartupException { - - // first we need to run upgrade scripts + + // first we need to run upgrade scripts SQLScriptRunner runner = null; - try { + try { if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/400-to-500-migration.sql"; - successMessage("Running database upgrade script: "+scriptPath); + successMessage("Running database upgrade script: "+scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); @@ -1138,10 +1138,10 @@ private void upgradeTo500(Connection con, boolean runScripts) throws StartupExce } catch(Exception ex) { log.error("ERROR running 500 database upgrade script", ex); if (runner != null) messages.addAll(runner.getMessages()); - + errorMessage("Problem upgrading database to version 500", ex); throw new StartupException("Problem upgrading database to version 500", ex); - } + } } @@ -1149,7 +1149,7 @@ private void upgradeTo500(Connection con, boolean runScripts) throws StartupExce * Use database product name to get the database script directory name. */ public String getDatabaseHandle(Connection con) throws SQLException { - + String productName = con.getMetaData().getDatabaseProductName(); String handle = "mysql"; if ( productName.toLowerCase().indexOf("mysql") != -1) { @@ -1164,14 +1164,14 @@ public String getDatabaseHandle(Connection con) throws SQLException { handle = "oracle"; } else if (productName.toLowerCase().indexOf("microsoft") != -1) { handle = "mssql"; - } else if (productName.toLowerCase().indexOf("db2") != -1) { + } else if (productName.toLowerCase().indexOf("db2") != -1) { handle = "db2"; } - + return handle; } - + /** * Return true if named table exists in database. */ @@ -1185,24 +1185,24 @@ private boolean tableExists(Connection con, String tableName) throws SQLExceptio } return false; } - - + + private int getDatabaseVersion() throws StartupException { int dbversion = -1; - + // get the current db version Connection con = null; try { con = db.getConnection(); Statement stmt = con.createStatement(); - + // just check in the roller_properties table ResultSet rs = stmt.executeQuery( "select value from roller_properties where name = '"+DBVERSION_PROP+"'"); - + if(rs.next()) { dbversion = Integer.parseInt(rs.getString(1)); - + } else { // tough to know if this is an upgrade with no db version :/ // however, if roller_properties is not empty then we at least @@ -1213,45 +1213,45 @@ private int getDatabaseVersion() throws StartupException { dbversion = 120; } } - + } catch(Exception e) { // that's strange ... hopefully we didn't need to upgrade - log.error("Couldn't lookup current database version", e); + log.error("Couldn't lookup current database version", e); } finally { try { if (con != null) con.close(); } catch (Exception ignored) {} - } + } return dbversion; } - - - private int parseVersionString(String vstring) { + + + private int parseVersionString(String vstring) { int myversion = 0; - + // NOTE: this assumes a maximum of 3 digits for the version number // so if we get to 10.0 then we'll need to upgrade this - + // strip out non-digits vstring = vstring.replaceAll("\\Q.\\E", ""); vstring = vstring.replaceAll("\\D", ""); if(vstring.length() > 3) vstring = vstring.substring(0, 3); - + // parse to an int try { - int parsed = Integer.parseInt(vstring); + int parsed = Integer.parseInt(vstring); if(parsed < 100) myversion = parsed * 10; else myversion = parsed; - } catch(Exception e) {} - + } catch(Exception e) {} + return myversion; } - + /** * Insert a new database.version property. * This should only be called once for new installations */ - private void setDatabaseVersion(Connection con, String version) + private void setDatabaseVersion(Connection con, String version) throws StartupException { setDatabaseVersion(con, parseVersionString(version)); } @@ -1262,35 +1262,35 @@ private void setDatabaseVersion(Connection con, String version) */ private void setDatabaseVersion(Connection con, int version) throws StartupException { - + try { Statement stmt = con.createStatement(); stmt.executeUpdate("insert into roller_properties "+ "values('"+DBVERSION_PROP+"', '"+version+"')"); - + log.debug("Set database verstion to "+version); } catch(SQLException se) { throw new StartupException("Error setting database version.", se); } } - - + + /** * Update the existing database.version property */ private void updateDatabaseVersion(Connection con, int version) throws StartupException { - + try { Statement stmt = con.createStatement(); stmt.executeUpdate("update roller_properties "+ "set value = '"+version+"'"+ "where name = '"+DBVERSION_PROP+"'"); - + log.debug("Updated database verstion to "+version); } catch(SQLException se) { throw new StartupException("Error setting database version.", se); - } + } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseScriptProvider.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseScriptProvider.java index f71e45b935..a35200c7d9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseScriptProvider.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/DatabaseScriptProvider.java @@ -25,10 +25,10 @@ * Interface for retrieving database script. */ public interface DatabaseScriptProvider { - - /** + + /** * Get an InputStream to a database script at the given path. */ public InputStream getDatabaseScript(String path) throws Exception; - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/StartupException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/StartupException.java index 0a3a1f4118..04a6403f76 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/StartupException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/StartupException.java @@ -27,43 +27,43 @@ * Exception generated from Weblogger startup process. */ public class StartupException extends WebloggerException { - + private final List startupLog; - - + + public StartupException(String msg) { super(msg); this.startupLog = Collections.EMPTY_LIST; } - + public StartupException(String msg, Throwable t) { super(msg, t); this.startupLog = Collections.EMPTY_LIST; } - + public StartupException(String msg, List log) { super(msg); - + if(log != null) { this.startupLog = log; } else { this.startupLog = Collections.EMPTY_LIST; } } - + public StartupException(String msg, Throwable t, List log) { super(msg, t); - + if(log != null) { this.startupLog = log; } else { this.startupLog = Collections.EMPTY_LIST; } } - - + + public List getStartupLog() { return startupLog; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/WebloggerStartup.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/WebloggerStartup.java index 61a19924cd..042927f137 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/WebloggerStartup.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/startup/WebloggerStartup.java @@ -30,29 +30,29 @@ * Manages Roller Weblogger startup process. */ public final class WebloggerStartup { - + private static final Log log = LogFactory.getLog(WebloggerStartup.class); - + private static boolean prepared = false; - + private static DatabaseProvider dbProvider = null; private static StartupException dbProviderException = null; - + private static MailProvider mailProvider = null; - - + + // non-instantiable private WebloggerStartup() {} - - + + /** * Is the Roller Weblogger app properly prepared to be bootstrapped? */ public static boolean isPrepared() { return prepared; } - - + + /** * Get a reference to the currently configured DatabaseProvider. * @@ -65,10 +65,10 @@ public static DatabaseProvider getDatabaseProvider() { } return dbProvider; } - - + + /** - * Get a reference to the exception thrown while instantiating the + * Get a reference to the exception thrown while instantiating the * database provider, if any. * * @return StartupException Exception from db provider, or null if no exception thrown. @@ -76,8 +76,8 @@ public static DatabaseProvider getDatabaseProvider() { public static StartupException getDatabaseProviderException() { return dbProviderException; } - - + + /** * Get a reference to the currently configured MailProvider, if available. * @@ -86,65 +86,65 @@ public static StartupException getDatabaseProviderException() { public static MailProvider getMailProvider() { return mailProvider; } - - + + /** * Does the app need to create the database tables? */ public static boolean isDatabaseCreationRequired() { return getDatabaseInstaller().isCreationRequired(); } - - + + /** * Run database creation scripts. */ public static List createDatabase() throws StartupException { - + DatabaseInstaller installer = getDatabaseInstaller(); try { installer.createDatabase(); - + // any time we've successfully installed a db we are prepared prepared = true; - + } catch (StartupException se) { throw new StartupException(se.getMessage(), se.getRootCause(), installer.getMessages()); } - + return installer.getMessages(); } - - + + /** * Does the app require any upgrading? */ public static boolean isDatabaseUpgradeRequired() { return getDatabaseInstaller().isUpgradeRequired(); } - - + + /** * Run database upgrade work, optionally including upgrade scripts. */ - public static List upgradeDatabase(boolean runScripts) + public static List upgradeDatabase(boolean runScripts) throws StartupException { - + DatabaseInstaller installer = getDatabaseInstaller(); try { installer.upgradeDatabase(true); - + // any time we've successfully upgraded a db we are prepared prepared = true; - + } catch (StartupException se) { throw new StartupException(se.getMessage(), se.getRootCause(), installer.getMessages()); } - + return installer.getMessages(); } - - + + /** * Get a database installer. * @@ -154,8 +154,8 @@ public static List upgradeDatabase(boolean runScripts) private static DatabaseInstaller getDatabaseInstaller() { return new DatabaseInstaller(getDatabaseProvider(), new ClasspathDatabaseScriptProvider()); } - - + + /** * Run the Roller Weblogger preparation sequence. * @@ -163,7 +163,7 @@ private static DatabaseInstaller getDatabaseInstaller() { * as setting up the database and mail providers. */ public static void prepare() throws StartupException { - + // setup database provider try { dbProvider = new DatabaseProvider(); @@ -171,7 +171,7 @@ public static void prepare() throws StartupException { dbProviderException = ex; throw ex; } - + // setup mail provider, if configured try { mailProvider = new MailProvider(); @@ -184,29 +184,29 @@ public static void prepare() throws StartupException { + "Reason: " + ex.getMessage()); } } - + // now we need to deal with database install/upgrade logic if("manual".equals(WebloggerConfig.getProperty("installation.type"))) { - + // if we are doing manual install then all that is needed is the // app handled database upgrade work, not the db scripts DatabaseInstaller dbInstaller = getDatabaseInstaller(); if(dbInstaller.isUpgradeRequired()) { dbInstaller.upgradeDatabase(false); } - + prepared = true; - + } else { - + // we are in auto install mode, so see if there is any work to do DatabaseInstaller dbInstaller = getDatabaseInstaller(); - if(!dbInstaller.isCreationRequired() && + if(!dbInstaller.isCreationRequired() && !dbInstaller.isUpgradeRequired()) { prepared = true; } } - + } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedTheme.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedTheme.java index 547fea96d9..e244135e7b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedTheme.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedTheme.java @@ -37,19 +37,19 @@ * multiple weblogs using a common set of resources. */ public abstract class SharedTheme implements Theme, Serializable, Comparable { - + protected String id = null; protected String name = null; protected String description = null; protected String author = null; protected Date lastModified = null; protected boolean enabled = false; - + public abstract List getResources(); - + public abstract ThemeResource getPreviewImage(); - - + + /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @@ -57,8 +57,8 @@ public int compareTo(Object o) { SharedTheme other = (SharedTheme) o; return getName().compareTo(other.getName()); } - - + + public String getId() { return id; } @@ -66,7 +66,7 @@ public String getId() { public void setId(String id) { this.id = id; } - + public String getName() { return name; } @@ -90,7 +90,7 @@ public String getAuthor() { public void setAuthor(String author) { this.author = author; } - + public Date getLastModified() { return lastModified; } @@ -98,7 +98,7 @@ public Date getLastModified() { public void setLastModified(Date lastModified) { this.lastModified = lastModified; } - + public boolean isEnabled() { return enabled; } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeFromDir.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeFromDir.java index ce248354fa..cccdab9d8c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeFromDir.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeFromDir.java @@ -43,61 +43,61 @@ * other theme related attributes such as name, last modifed date, etc. */ public class SharedThemeFromDir extends SharedTheme { - + private static Log log = LogFactory.getLog(SharedThemeFromDir.class); - + // the filesystem directory where we should read this theme from private String themeDir = null; - + // the theme preview image private ThemeResource previewImage = null; - + // the theme stylesheet private ThemeTemplate stylesheet = null; - + // we keep templates in a Map for faster lookups by name // the Map contains ... (template name, ThemeTemplate) private Map templatesByName = new HashMap(); - + // we keep templates in a Map for faster lookups by link // the Map contains ... (template link, ThemeTemplate) private Map templatesByLink = new HashMap(); - + // we keep templates in a Map for faster lookups by action // the Map contains ... (template action, ThemeTemplate) private Map templatesByAction = new HashMap(); - + // we keep resources in a Map for faster lookups by path // the Map contains ... (resource path, ThemeResource) private Map resources = new HashMap(); - - - public SharedThemeFromDir(String themeDirPath) + + + public SharedThemeFromDir(String themeDirPath) throws ThemeInitializationException { - + this.themeDir = themeDirPath; - + // load the theme elements and cache 'em loadThemeFromDisk(); } - + /** * Get a resource representing the preview image for this theme. */ public ThemeResource getPreviewImage() { return this.previewImage; } - - + + /** * Get the collection of all templates associated with this Theme. */ public List getTemplates() { return new ArrayList(this.templatesByName.values()); } - - + + /** * Lookup the stylesheet. * Returns null if no stylesheet defined. @@ -105,8 +105,8 @@ public List getTemplates() { public ThemeTemplate getStylesheet() { return this.stylesheet; } - - + + /** * Looup the default template, action = weblog. * Returns null if the template cannot be found. @@ -114,8 +114,8 @@ public ThemeTemplate getStylesheet() { public ThemeTemplate getDefaultTemplate() { return (ThemeTemplate) this.templatesByAction.get(ThemeTemplate.ACTION_WEBLOG); } - - + + /** * Lookup the specified template by name. * Returns null if the template cannot be found. @@ -123,8 +123,8 @@ public ThemeTemplate getDefaultTemplate() { public ThemeTemplate getTemplateByName(String name) { return (ThemeTemplate) this.templatesByName.get(name); } - - + + /** * Lookup the specified template by link. * Returns null if the template cannot be found. @@ -132,8 +132,8 @@ public ThemeTemplate getTemplateByName(String name) { public ThemeTemplate getTemplateByLink(String link) { return (ThemeTemplate) this.templatesByLink.get(link); } - - + + /** * Lookup the specified template by action. * Returns null if the template cannot be found. @@ -141,23 +141,23 @@ public ThemeTemplate getTemplateByLink(String link) { public ThemeTemplate getTemplateByAction(String action) { return (ThemeTemplate) this.templatesByAction.get(action); } - - + + /** * Get the collection of all resources associated with this Theme. * * It is assured that the resources are returned sorted by pathname. */ public List getResources() { - + // make sure resources are sorted. List myResources = new ArrayList(this.resources.values()); Collections.sort(myResources); - + return myResources; } - - + + /** * Lookup the specified resource by path. * Returns null if the resource cannot be found. @@ -165,31 +165,31 @@ public List getResources() { public ThemeResource getResource(String path) { return (ThemeResource) this.resources.get(path); } - - + + public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append("\n"); - + Iterator it = this.templatesByName.values().iterator(); while(it.hasNext()) { sb.append(it.next()); sb.append("\n"); } - + return sb.toString(); - + } - - + + /** * Load all the elements of this theme from disk and cache them. */ private void loadThemeFromDisk() throws ThemeInitializationException { - + log.debug("Parsing theme descriptor for "+this.themeDir); - + ThemeMetadata themeMetadata = null; try { // lookup theme descriptor and parse it @@ -199,9 +199,9 @@ private void loadThemeFromDisk() throws ThemeInitializationException { } catch (Exception ex) { throw new ThemeInitializationException("Unable to parse theme descriptor for theme "+this.themeDir, ex); } - + log.debug("Loading Theme "+themeMetadata.getName()); - + // use parsed theme descriptor to load Theme data setId(themeMetadata.getId()); setName(themeMetadata.getName()); @@ -209,7 +209,7 @@ private void loadThemeFromDisk() throws ThemeInitializationException { setAuthor(themeMetadata.getAuthor()); setLastModified(null); setEnabled(true); - + // load resource representing preview image File previewFile = new File(this.themeDir + File.separator + themeMetadata.getPreviewImage()); if(!previewFile.exists() || !previewFile.canRead()) { @@ -217,23 +217,23 @@ private void loadThemeFromDisk() throws ThemeInitializationException { } else { this.previewImage = new SharedThemeResourceFromDir(themeMetadata.getPreviewImage(), previewFile); } - + // load stylesheet if possible if(themeMetadata.getStylesheet() != null) { - + ThemeMetadataTemplate stylesheetTmpl = themeMetadata.getStylesheet(); - + // construct File object from path - File templateFile = new File(this.themeDir + File.separator + + File templateFile = new File(this.themeDir + File.separator + stylesheetTmpl.getContentsFile()); - + // read stylesheet contents String contents = loadTemplateFile(templateFile); if(contents == null) { // if we don't have any contents then skip this one log.error("Couldn't load stylesheet theme [" + this.getName() + "] template file ["+templateFile+"]"); } else { - + // construct ThemeTemplate representing this file SharedThemeTemplate theme_template = new SharedThemeTemplate( this, @@ -247,63 +247,63 @@ private void loadThemeFromDisk() throws ThemeInitializationException { stylesheetTmpl.getTemplateLanguage(), false, false); - + // store it this.stylesheet = theme_template; - + // add it to templates list addTemplate(theme_template); } - + // Set Last Modified setLastModified(new Date(templateFile.lastModified())); - + } - + // go through static resources and add them to the theme String resourcePath = null; Iterator resourcesIter = themeMetadata.getResources().iterator(); while (resourcesIter.hasNext()) { resourcePath = (String) resourcesIter.next(); - + // construct ThemeResource object from resource File resourceFile = new File(this.themeDir + File.separator + resourcePath); - + // Continue reading theme even if problem encountered with one file if(!resourceFile.exists() || !resourceFile.canRead()) { log.warn("Couldn't read theme [" + this.getName() + "] resource file ["+resourcePath+"]"); continue; } - + // add it to the theme setResource(resourcePath, new SharedThemeResourceFromDir(resourcePath, resourceFile)); - + // Set Last Modified Date lstModified = new Date(resourceFile.lastModified()); if (getLastModified() == null || lstModified.after(getLastModified())) { setLastModified(lstModified); } - + } - + // go through templates and read in contents to a ThemeTemplate ThemeTemplate theme_template = null; ThemeMetadataTemplate templateMetadata = null; Iterator templatesIter = themeMetadata.getTemplates().iterator(); while (templatesIter.hasNext()) { templateMetadata = (ThemeMetadataTemplate) templatesIter.next(); - + // construct File object from path - File templateFile = new File(this.themeDir + File.separator + + File templateFile = new File(this.themeDir + File.separator + templateMetadata.getContentsFile()); - + String contents = loadTemplateFile(templateFile); if(contents == null) { // if we don't have any contents then skip this one throw new ThemeInitializationException("Couldn't load theme [" + this.getName() + "] template file ["+templateFile+"]"); } - + // construct ThemeTemplate representing this file theme_template = new SharedThemeTemplate( this, @@ -320,7 +320,7 @@ private void loadThemeFromDisk() throws ThemeInitializationException { // add it to the theme addTemplate(theme_template); - + // Set Last Modified Date lstModified = new Date(templateFile.lastModified()); if (getLastModified() == null @@ -329,8 +329,8 @@ private void loadThemeFromDisk() throws ThemeInitializationException { } } } - - + + /** * Load a single template file as a string, returns null if can't read file. */ @@ -339,7 +339,7 @@ private String loadTemplateFile(File templateFile) { if(!templateFile.exists() && !templateFile.canRead()) { return null; } - + char[] chars = null; int length; try { @@ -353,11 +353,11 @@ private String loadTemplateFile(File templateFile) { log.debug(noprob); return null; } - + return new String(chars, 0, length); } - - + + /** * Set the value for a given template name. */ @@ -368,8 +368,8 @@ private void addTemplate(ThemeTemplate template) { this.templatesByAction.put(template.getAction(), template); } } - - + + /** * Set the value for a given resource path. */ @@ -378,5 +378,5 @@ private void setResource(String path, SharedThemeResourceFromDir resource) { String normalizedPath = StringUtils.replace(path, "\\", "/"); this.resources.put(normalizedPath, resource); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeResourceFromDir.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeResourceFromDir.java index cc315a483f..5ca84ef0da 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeResourceFromDir.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeResourceFromDir.java @@ -35,22 +35,22 @@ * not be any external classes which need to construct their own instances * of this class. */ -public class SharedThemeResourceFromDir +public class SharedThemeResourceFromDir implements ThemeResource, Serializable, Comparable { - + // the physical java.io.File backing this resource private File resourceFile = null; - + // the relative path of the resource within the theme private String relativePath = null; - - + + public SharedThemeResourceFromDir(String path, File file) { relativePath = path; resourceFile = file; } - - + + /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @@ -58,37 +58,37 @@ public int compareTo(Object o) { ThemeResource other = (ThemeResource) o; return getPath().compareTo(other.getPath()); } - - + + public ThemeResource[] getChildren() { return null; } - - + + public String getName() { return resourceFile.getName(); } - + public String getPath() { return relativePath; } - + public long getLastModified() { return resourceFile.lastModified(); } - + public long getLength() { return resourceFile.length(); } - + public boolean isDirectory() { return resourceFile.isDirectory(); } - + public boolean isFile() { return resourceFile.isFile(); } - + public InputStream getInputStream() { try { return new FileInputStream(resourceFile); @@ -97,5 +97,5 @@ public InputStream getInputStream() { throw new RuntimeException("Error constructing input stream", ex); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeTemplate.java index 4da605f237..28453add3b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/SharedThemeTemplate.java @@ -29,7 +29,7 @@ * template which is part of a shared Theme. */ public class SharedThemeTemplate implements ThemeTemplate, Serializable { - + private String id = null; private String action = null; private String name = null; @@ -41,16 +41,16 @@ public class SharedThemeTemplate implements ThemeTemplate, Serializable { private boolean hidden = false; private boolean navbar = false; private String outputContentType = null; - + private SharedTheme myTheme = null; - - + + public SharedThemeTemplate() {} - - public SharedThemeTemplate(SharedTheme theme, String id, String action, String name, - String desc, String contents, String link, Date date, + + public SharedThemeTemplate(SharedTheme theme, String id, String action, String name, + String desc, String contents, String link, Date date, String tempLang, boolean hid, boolean navbar) { - + this.myTheme = theme; this.id = id; this.action = action; @@ -63,14 +63,14 @@ public SharedThemeTemplate(SharedTheme theme, String id, String action, String n this.hidden = hid; this.navbar = navbar; } - - + + // NOTE: decorators are deprecated as of 4.0 but we leave this here because // they need to be left in place for backwards compatability public ThemeTemplate getDecorator() { return null; } - + public String getId() { return id; } @@ -158,9 +158,9 @@ public String getOutputContentType() { public void setOutputContentType(String outputContentType) { this.outputContentType = outputContentType; } - + public String toString() { - return (id + "," + name + "," + description + "," + link + "," + + return (id + "," + name + "," + description + "," + link + "," + lastModified + "\n\n" + contents + "\n"); } @@ -171,5 +171,5 @@ public String getAction() { public void setAction(String action) { this.action = action; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeInitializationException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeInitializationException.java index 9057745912..0e15eb21a6 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeInitializationException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeInitializationException.java @@ -25,22 +25,22 @@ * Thrown when there is a problem initalizing a theme object. */ public class ThemeInitializationException extends WebloggerException { - - + + public ThemeInitializationException(String s,Throwable t) { super(s, t); } - + public ThemeInitializationException(Throwable t) { super(t); } - + public ThemeInitializationException(String s) { super(s); } - + public ThemeInitializationException() { super(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManager.java index f7bc6680e1..40124a82d1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManager.java @@ -31,7 +31,7 @@ public interface ThemeManager { /** * Initialize the theme system. - * + * * @throws InitializationException * If there is a problem during initialization. */ @@ -39,7 +39,7 @@ public interface ThemeManager { /** * Get the Theme object with the given id. - * + * * @return Theme The Theme object with the given id. * @throws ThemeNotFoundException * If the named theme cannot be found. @@ -51,7 +51,7 @@ public SharedTheme getTheme(String id) throws ThemeNotFoundException, /** * Get the WeblogTheme for a given weblog. - * + * * @param weblog * The weblog to get the theme for. * @return WeblogTheme The theme to be used for the given weblog. @@ -63,19 +63,19 @@ public SharedTheme getTheme(String id) throws ThemeNotFoundException, /** * Get a list of all theme names that are currently enabled. This list is * ordered alphabetically by default. - * + * * @return List A list of Theme objects which are enabled. */ public List getEnabledThemesList(); /** * Import all the contents for a Theme into a weblog. - * + * * @param weblog * The weblog to import the theme into. * @param theme * The theme that should be imported. - * + * * @throws WebloggerException * If there is some kind of error in saving. */ @@ -85,10 +85,10 @@ public void importTheme(Weblog website, SharedTheme theme) /** * This is a development only method which reloads theme data from themes * stored on the filesystem in the webapp /themes/ directory. - * + * * @param reloadTheme * the reload theme - * + * * @return true, if reloaded theme from disk */ public boolean reLoadThemeFromDisk(String reloadTheme); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManagerImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManagerImpl.java index 76b5bf4d5d..0340139f1f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManagerImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeManagerImpl.java @@ -52,8 +52,8 @@ /** * Base implementation of a ThemeManager. - * - * This particular implementation reads theme data off the filesystem + * + * This particular implementation reads theme data off the filesystem * and assumes that those themes are not changable at runtime. */ @com.google.inject.Singleton @@ -314,7 +314,7 @@ public void importTheme(Weblog website, SharedTheme theme) MediaFile oldmf = fileMgr.getMediaFileByOriginalPath(website, justPath + "/" + justName); if (oldmf != null) { - fileMgr.removeMediaFile(website, oldmf); + fileMgr.removeMediaFile(website, oldmf); } // save file without file-type, quota checks, etc. @@ -324,7 +324,7 @@ public void importTheme(Weblog website, SharedTheme theme) mf.setWeblog(website); mf.setName(justName); mf.setOriginalPath(justPath + "/" + justName); - mf.setContentType(map.getContentType(justName)); + mf.setContentType(map.getContentType(justName)); mf.setInputStream(is); mf.setLength(resource.getLength()); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadata.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadata.java index ae830d45c3..7423a0acbb 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadata.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadata.java @@ -26,7 +26,7 @@ * Represents a parsed version of a theme xml metadata descriptor. */ public class ThemeMetadata { - + private String id = null; private String name = null; private String author = null; @@ -34,20 +34,20 @@ public class ThemeMetadata { private ThemeMetadataTemplate stylesheet = null; private Set templates = new HashSet(); private Set resources = new HashSet(); - - + + public ThemeMetadata() {} - + public void addTemplate(ThemeMetadataTemplate template) { this.templates.add(template); } - + public void addResource(String resource) { this.resources.add(resource); } - - + + public String getId() { return id; } @@ -55,7 +55,7 @@ public String getId() { public void setId(String id) { this.id = id; } - + public String getName() { return name; } @@ -103,5 +103,5 @@ public ThemeMetadataTemplate getStylesheet() { public void setStylesheet(ThemeMetadataTemplate stylesheet) { this.stylesheet = stylesheet; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataParser.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataParser.java index 80b79fd366..2a1bd14502 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataParser.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataParser.java @@ -36,34 +36,34 @@ * This class unmarshalls a theme descriptor into a set of objects. */ public class ThemeMetadataParser { - - + + /** * Unmarshall the given input stream into our defined * set of Java objects. **/ - public ThemeMetadata unmarshall(InputStream instream) + public ThemeMetadata unmarshall(InputStream instream) throws ThemeParsingException, IOException, JDOMException { - + if(instream == null) throw new IOException("InputStream is null!"); - + ThemeMetadata theme = new ThemeMetadata(); - + SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(instream); - + // start at root and get theme id, name, and author Element root = doc.getRootElement(); theme.setId(root.getChildText("id")); theme.setName(root.getChildText("name")); theme.setAuthor(root.getChildText("author")); - + // if either id or name is null then throw a parsing exception if(StringUtils.isEmpty(theme.getId()) || StringUtils.isEmpty(theme.getName())) { throw new ThemeParsingException("'id' and 'name' are required theme elements"); } - + // now grab the preview image path Element previewImage = root.getChild("preview-image"); if(previewImage != null) { @@ -71,13 +71,13 @@ public ThemeMetadata unmarshall(InputStream instream) } else { throw new ThemeParsingException("No preview image specified"); } - + // grab the stylesheet if it exists Element stylesheet = root.getChild("stylesheet"); if(stylesheet != null) { theme.setStylesheet(elementToStylesheet(stylesheet)); } - + // now grab the static resources List resources = root.getChildren("resource"); Iterator resourcesIter = resources.iterator(); @@ -85,7 +85,7 @@ public ThemeMetadata unmarshall(InputStream instream) Element resource = (Element) resourcesIter.next(); theme.addResource(resource.getAttributeValue("path")); } - + // now grab the templates boolean weblogActionTemplate = false; List templates = root.getChildren("template"); @@ -94,27 +94,27 @@ public ThemeMetadata unmarshall(InputStream instream) Element template = (Element) templatesIter.next(); ThemeMetadataTemplate tmpl = elementToTemplateMetadata(template); theme.addTemplate(tmpl); - + if(WeblogTemplate.ACTION_WEBLOG.equals(tmpl.getAction())) { weblogActionTemplate = true; } } - + // make sure all required elements are present and values are valid // check that there is a template with action='weblog' if(!weblogActionTemplate) { throw new ThemeParsingException("did not find a template of action = 'weblog'"); } - + return theme; } - - - private ThemeMetadataTemplate elementToTemplateMetadata(Element element) + + + private ThemeMetadataTemplate elementToTemplateMetadata(Element element) throws ThemeParsingException { - + ThemeMetadataTemplate template = new ThemeMetadataTemplate(); - + template.setAction(element.getAttributeValue("action")); template.setName(element.getChildText("name")); template.setDescription(element.getChildText("description")); @@ -122,17 +122,17 @@ private ThemeMetadataTemplate elementToTemplateMetadata(Element element) template.setTemplateLanguage(element.getChildText("templateLanguage")); template.setContentType(element.getChildText("contentType")); template.setContentsFile(element.getChildText("contentsFile")); - + String navbar = element.getChildText("navbar"); if("true".equalsIgnoreCase(navbar)) { template.setNavbar(true); } - + String hidden = element.getChildText("hidden"); if("true".equalsIgnoreCase(hidden)) { template.setHidden(true); } - + // validate template if(StringUtils.isEmpty(template.getAction())) { throw new ThemeParsingException("templates must contain an 'action' attribute"); @@ -146,22 +146,22 @@ private ThemeMetadataTemplate elementToTemplateMetadata(Element element) if(StringUtils.isEmpty(template.getContentsFile())) { throw new ThemeParsingException("templates must contain a 'contentsFile' element"); } - + return template; } - - - private ThemeMetadataTemplate elementToStylesheet(Element element) + + + private ThemeMetadataTemplate elementToStylesheet(Element element) throws ThemeParsingException { - + ThemeMetadataTemplate template = new ThemeMetadataTemplate(); - + template.setName(element.getChildText("name")); template.setDescription(element.getChildText("description")); template.setLink(element.getChildText("link")); template.setTemplateLanguage(element.getChildText("templateLanguage")); template.setContentsFile(element.getChildText("contentsFile")); - + // validate template if(StringUtils.isEmpty(template.getName())) { throw new ThemeParsingException("stylesheet must contain a 'name' element"); @@ -175,8 +175,8 @@ private ThemeMetadataTemplate elementToStylesheet(Element element) if(StringUtils.isEmpty(template.getContentsFile())) { throw new ThemeParsingException("stylesheet must contain a 'contentsFile' element"); } - + return template; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataTemplate.java index 749180011e..1adbd7b6ed 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeMetadataTemplate.java @@ -23,7 +23,7 @@ * A parsed 'template' element of a theme metadata descriptor. */ public class ThemeMetadataTemplate { - + private String action = null; private String name = null; private String description = null; @@ -105,5 +105,5 @@ public String getContentsFile() { public void setContentsFile(String contentsFile) { this.contentsFile = contentsFile; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeNotFoundException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeNotFoundException.java index a29ec8b353..9ed4607f08 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeNotFoundException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeNotFoundException.java @@ -25,22 +25,22 @@ * Thrown when the ThemeManager has a problem finding a named theme. */ public class ThemeNotFoundException extends WebloggerException { - - + + public ThemeNotFoundException(String s,Throwable t) { super(s, t); } - + public ThemeNotFoundException(Throwable t) { super(t); } - + public ThemeNotFoundException(String s) { super(s); } - + public ThemeNotFoundException() { super(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeParsingException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeParsingException.java index 12f6b9e916..ad93510366 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeParsingException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/ThemeParsingException.java @@ -25,22 +25,22 @@ * Thrown when there is a problem parsing a given theme xml descriptor. */ public class ThemeParsingException extends WebloggerException { - - + + public ThemeParsingException(String s,Throwable t) { super(s, t); } - + public ThemeParsingException(Throwable t) { super(t); } - + public ThemeParsingException(String s) { super(s); } - + public ThemeParsingException() { super(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogCustomTheme.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogCustomTheme.java index e8f0bac627..ae1b3f2884 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogCustomTheme.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogCustomTheme.java @@ -34,21 +34,21 @@ * A WeblogTheme custom defined by the weblog owner. */ public class WeblogCustomTheme extends WeblogTheme { - - + + public WeblogCustomTheme(Weblog weblog) { super(weblog); } - - + + public String getId() { return CUSTOM; } - + public String getName() { return CUSTOM; } - + public String getDescription() { return CUSTOM; } @@ -56,24 +56,24 @@ public String getDescription() { public String getAuthor() { return "N/A"; } - + public Date getLastModified() { return this.weblog.getLastModified(); } - + public boolean isEnabled() { return true; } - - + + /** * Get the collection of all templates associated with this Theme. */ public List getTemplates() throws WebloggerException { return WebloggerFactory.getWeblogger().getWeblogManager().getPages(this.weblog); } - - + + /** * Lookup the stylesheet template for this theme. * Returns null if no stylesheet can be found. @@ -81,8 +81,8 @@ public List getTemplates() throws WebloggerException { public ThemeTemplate getStylesheet() throws WebloggerException { return getTemplateByLink(this.weblog.getCustomStylesheetPath()); } - - + + /** * Lookup the default template. * Returns null if the template cannot be found. @@ -91,8 +91,8 @@ public ThemeTemplate getDefaultTemplate() throws WebloggerException { return WebloggerFactory.getWeblogger().getWeblogManager() .getPageByAction(this.weblog, ThemeTemplate.ACTION_WEBLOG); } - - + + /** * Lookup the specified template by action. * Returns null if the template cannot be found. @@ -100,11 +100,11 @@ public ThemeTemplate getDefaultTemplate() throws WebloggerException { public ThemeTemplate getTemplateByAction(String action) throws WebloggerException { if(action == null) return null; - + return WebloggerFactory.getWeblogger().getWeblogManager().getPageByAction(this.weblog, action); } - - + + /** * Lookup the specified template by name. * Returns null if the template cannot be found. @@ -112,11 +112,11 @@ public ThemeTemplate getTemplateByAction(String action) throws WebloggerExceptio public ThemeTemplate getTemplateByName(String name) throws WebloggerException { if(name == null) return null; - + return WebloggerFactory.getWeblogger().getWeblogManager().getPageByName(this.weblog, name); } - - + + /** * Lookup the specified template by link. * Returns null if the template cannot be found. @@ -124,19 +124,19 @@ public ThemeTemplate getTemplateByName(String name) throws WebloggerException { public ThemeTemplate getTemplateByLink(String link) throws WebloggerException { if(link == null) return null; - + return WebloggerFactory.getWeblogger().getWeblogManager().getPageByLink(this.weblog, link); } - - + + /** * Lookup the specified resource by path. * Returns null if the resource cannot be found. */ public ThemeResource getResource(String path) { - + ThemeResource resource = null; - + try { MediaFileManager mmgr = WebloggerFactory.getWeblogger().getMediaFileManager(); @@ -146,8 +146,8 @@ public ThemeResource getResource(String path) { } catch (WebloggerException ex) { // ignored, resource considered not found } - + return resource; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogSharedTheme.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogSharedTheme.java index d7ea54deff..a3a88a2f73 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogSharedTheme.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/business/themes/WeblogSharedTheme.java @@ -40,46 +40,46 @@ * A WeblogTheme shared by many weblogs and backed by a SharedTheme. */ public class WeblogSharedTheme extends WeblogTheme { - + private static Log log = LogFactory.getLog(WeblogSharedTheme.class); - + private SharedTheme theme = null; - - + + public WeblogSharedTheme(Weblog weblog, SharedTheme theme) { super(weblog); this.theme = theme; } - - + + public String getId() { return this.theme.getId(); } - + public String getName() { return this.theme.getName(); } - + public String getDescription() { return this.theme.getDescription(); } - + public Date getLastModified() { return this.theme.getLastModified(); } - + public boolean isEnabled() { return this.theme.isEnabled(); } - - + + /** * Get the collection of all templates associated with this Theme. */ public List getTemplates() throws WebloggerException { - + Map pages = new TreeMap(); - + // first get the pages from the db try { ThemeTemplate template = null; @@ -93,15 +93,15 @@ public List getTemplates() throws WebloggerException { // db error log.error(e); } - - + + // now get theme pages if needed and put them in place of db pages try { ThemeTemplate template = null; Iterator themePages = this.theme.getTemplates().iterator(); while(themePages.hasNext()) { template = (ThemeTemplate) themePages.next(); - + // note that this will put theme pages over custom // pages in the pages list, which is what we want pages.put(template.getName(), template); @@ -110,11 +110,11 @@ public List getTemplates() throws WebloggerException { // how?? log.error(e); } - + return new ArrayList(pages.values()); } - - + + /** * Lookup the stylesheet template for this theme. * Returns null if no stylesheet can be found. @@ -123,7 +123,7 @@ public ThemeTemplate getStylesheet() throws WebloggerException { // stylesheet is handled differently than other templates because with // the stylesheet we want to return the weblog custom version if it // exists, otherwise we return the shared theme version - + // load from theme first to see if we even support a stylesheet ThemeTemplate stylesheet = this.theme.getStylesheet(); if(stylesheet != null) { @@ -134,110 +134,110 @@ public ThemeTemplate getStylesheet() throws WebloggerException { stylesheet = override; } } - + return stylesheet; } - - + + /** * Lookup the default template. */ public ThemeTemplate getDefaultTemplate() throws WebloggerException { return this.theme.getDefaultTemplate(); } - - + + /** * Lookup the specified template by action. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByAction(String action) throws WebloggerException { - + if(action == null) return null; - + // NOTE: we specifically do *NOT* return templates by action from the // weblog's custom templates if the weblog is using a theme because we // don't want old templates to take effect when using a specific theme return this.theme.getTemplateByAction(action); } - - + + /** * Lookup the specified template by name. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByName(String name) throws WebloggerException { - + if(name == null) return null; - + ThemeTemplate template = null; - + // if name refers to the stylesheet then return result of getStylesheet() ThemeTemplate stylesheet = getStylesheet(); if(stylesheet != null && name.equals(stylesheet.getName())) { return stylesheet; } - + // first check if this user has selected a theme // if so then return the proper theme template template = this.theme.getTemplateByName(name); - + // if we didn't get the Template from a theme then look in the db if(template == null) { template = WebloggerFactory.getWeblogger().getWeblogManager().getPageByName(this.weblog, name); } - + return template; } - - + + /** * Lookup the specified template by link. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByLink(String link) throws WebloggerException { - + if(link == null) return null; - + ThemeTemplate template = null; - + // if name refers to the stylesheet then return result of getStylesheet() ThemeTemplate stylesheet = getStylesheet(); if(stylesheet != null && link.equals(stylesheet.getLink())) { return stylesheet; } - + // first check if this user has selected a theme // if so then return the proper theme template template = this.theme.getTemplateByLink(link); - + // if we didn't get the Template from a theme then look in the db if(template == null) { template = WebloggerFactory.getWeblogger() .getWeblogManager().getPageByLink(this.weblog, link); } - + return template; } - - + + /** * Lookup the specified resource by path. * Returns null if the resource cannot be found. */ public ThemeResource getResource(String path) { - + if(path == null) return null; - + ThemeResource resource = null; - + // first check in our shared theme resource = this.theme.getResource(path); - + // if we didn't find it in our theme then look in weblog uploads if(resource == null) { try { @@ -250,8 +250,8 @@ public ThemeResource getResource(String path) { // ignored, resource considered not found } } - + return resource; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/PingConfig.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/PingConfig.java index 74fefc7108..6be6375115 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/PingConfig.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/PingConfig.java @@ -36,8 +36,8 @@ /** * Thin wrapper around WebloggerConfig and WebloggerRuntimeConfig for centralizing access to the many configurable * settings for pings. - * - * + * + * * @author Anil Gangolli */ public class PingConfig { @@ -99,7 +99,7 @@ public class PingConfig { // targets that implement minor variants of the WeblogUpdates.ping call. // This is initialized once at startup, and referenced when pings are made. private static final Map configuredVariants = new HashMap(); - + // Pattern used to parse common ping targets as well as ping variants. // Each initial commmon ping target is specified in the format {{name}{url}} // Ping variants are also specified in a nested brace format {{url}{options}} diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerConfig.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerConfig.java index 9701f4996c..f3f8bddf68 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerConfig.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerConfig.java @@ -33,7 +33,7 @@ * This is the single entry point for accessing configuration properties in Roller. */ public class WebloggerConfig { - + private static String default_config = "/org/apache/roller/weblogger/config/roller.properties"; private static String custom_config = "/roller-custom.properties"; private static String custom_jvm_param = "roller.custom.config"; @@ -42,7 +42,7 @@ public class WebloggerConfig { private static Properties config; private static Log log = LogFactory.getLog(WebloggerConfig.class); - + /* * Static block run once at class loading @@ -85,7 +85,7 @@ public class WebloggerConfig { custom_config_file.getAbsolutePath()); } - } + } // Now expand system properties for properties in the config.expandedProperties list, // replacing them by their expanded values. @@ -101,11 +101,11 @@ public class WebloggerConfig { } } } - + // initialize logging subsystem via WebloggerConfig Properties log4jprops = new Properties(); PropertyConfigurator.configure(WebloggerConfig.getPropertiesStartingWith("log4j.")); - + // finally we can start logging... // some debugging for those that want it @@ -141,11 +141,11 @@ public static String getProperty(String key) { String value = config.getProperty(key); return value == null ? value : value.trim(); } - + /** * Retrieve a property value * @param key Name of the property - * @param defaultValue Default value of property if not found + * @param defaultValue Default value of property if not found * @return String Value of property requested or defaultValue */ public static String getProperty(String key, String defaultValue) { @@ -153,7 +153,7 @@ public static String getProperty(String key, String defaultValue) { String value = config.getProperty(key); if(value == null) return defaultValue; - + return value.trim(); } @@ -204,8 +204,8 @@ public static int getIntProperty(String name, int defaultValue) { public static Enumeration keys() { return config.keys(); } - - + + /** * Get properties starting with a specified string. */ @@ -217,13 +217,13 @@ public static Properties getPropertiesStartingWith(String startingWith) { } return props; } - + /** * Set the "uploads.dir" property at runtime. *

      - * Properties are meant to be read-only, but we make this exception because - * we know that some people are still writing their uploads to the webapp + * Properties are meant to be read-only, but we make this exception because + * we know that some people are still writing their uploads to the webapp * context and we can only get that path at runtime (and for unit testing). *

      * This property is *not* persisted in any way. @@ -233,12 +233,12 @@ public static void setUploadsDir(String path) { if("${webapp.context}".equals(config.getProperty("uploads.dir"))) config.setProperty("uploads.dir", path); } - + /** * Set the "themes.dir" property at runtime. *

      - * Properties are meant to be read-only, but we make this exception because - * we know that some people are still using their themes in the webapp + * Properties are meant to be read-only, but we make this exception because + * we know that some people are still using their themes in the webapp * context and we can only get that path at runtime (and for unit testing). *

      * This property is *not* persisted in any way. @@ -248,5 +248,5 @@ public static void setThemesDir(String path) { if("${webapp.context}".equals(config.getProperty("themes.dir"))) config.setProperty("themes.dir", path); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 87a11a6302..51e66fbb9a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -35,33 +35,33 @@ * via the PropertiesManager. We do this because most calls to the * PropertiesManager are just to get the value of a specific property and * thus the caller doesn't need the full RuntimeConfigProperty object. - * + * * We also provide some methods for converting to different data types. */ public class WebloggerRuntimeConfig { - + private static Log log = LogFactory.getLog(WebloggerRuntimeConfig.class); - + private static String runtime_config = "/org/apache/roller/weblogger/config/runtimeConfigDefs.xml"; private static RuntimeConfigDefs configDefs = null; - + // special case for our context urls private static String relativeContextURL = null; private static String absoluteContextURL = null; - - + + // prevent instantiations private WebloggerRuntimeConfig() {} - - + + /** * Retrieve a single property from the PropertiesManager ... returns null * if there is an error **/ public static String getProperty(String name) { - + String value = null; - + try { PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager(); RuntimeConfigProperty prop = pmgr.getProperty(name); @@ -71,73 +71,73 @@ public static String getProperty(String name) { } catch(Exception e) { log.warn("Trouble accessing property: "+name, e); } - + log.debug("fetched property ["+name+"="+value+"]"); return value; } - - + + /** * Retrieve a property as a boolean ... defaults to false if there is an error **/ public static boolean getBooleanProperty(String name) { - + // get the value first, then convert String value = WebloggerRuntimeConfig.getProperty(name); - + if(value == null) return false; - + return (new Boolean(value)).booleanValue(); } - - + + /** * Retrieve a property as an int ... defaults to -1 if there is an error **/ public static int getIntProperty(String name) { - + // get the value first, then convert String value = WebloggerRuntimeConfig.getProperty(name); - + if(value == null) return -1; - + int intval = -1; try { intval = Integer.parseInt(value); } catch(Exception e) { log.warn("Trouble converting to int: "+name, e); } - + return intval; } - - + + public static RuntimeConfigDefs getRuntimeConfigDefs() { - + if(configDefs == null) { - + // unmarshall the config defs file try { - InputStream is = + InputStream is = WebloggerRuntimeConfig.class.getResourceAsStream(runtime_config); - + RuntimeConfigDefsParser parser = new RuntimeConfigDefsParser(); configDefs = parser.unmarshall(is); - + } catch(Exception e) { // error while parsing :( log.error("Error parsing runtime config defs", e); } - + } - + return configDefs; } - - + + /** * Get the runtime configuration definitions XML file as a string. * @@ -147,30 +147,30 @@ public static RuntimeConfigDefs getRuntimeConfigDefs() { * the display for editing those properties. */ public static String getRuntimeConfigDefsAsString() { - + log.debug("Trying to load runtime config defs file"); - + try { InputStreamReader reader = new InputStreamReader(WebloggerConfig.class.getResourceAsStream(runtime_config)); StringWriter configString = new StringWriter(); - + char[] buf = new char[8196]; int length = 0; while((length = reader.read(buf)) > 0) configString.write(buf, 0, length); - + reader.close(); - + return configString.toString(); } catch(Exception e) { log.error("Error loading runtime config defs file", e); } - + return ""; } - - + + /** * Special method which sets the non-persisted absolute url to this site. * @@ -179,8 +179,8 @@ public static String getRuntimeConfigDefsAsString() { public static void setAbsoluteContextURL(String url) { absoluteContextURL = url; } - - + + /** * Get the absolute url to this site. * @@ -189,17 +189,17 @@ public static void setAbsoluteContextURL(String url) { * value which is set by the InitFilter. */ public static String getAbsoluteContextURL() { - + // db prop takes priority if it exists String absURL = getProperty("site.absoluteurl"); if(absURL != null && absURL.trim().length() > 0) { return absURL; } - + return absoluteContextURL; } - - + + /** * Special method which sets the non-persisted relative url to this site. * @@ -208,35 +208,35 @@ public static String getAbsoluteContextURL() { public static void setRelativeContextURL(String url) { relativeContextURL = url; } - - + + public static String getRelativeContextURL() { return relativeContextURL; } - - + + /** * Convenience method for Roller classes trying to determine if a given * weblog handle represents the front page blog. */ public static boolean isFrontPageWeblog(String weblogHandle) { - + String frontPageHandle = getProperty("site.frontpage.weblog.handle"); - + return (frontPageHandle.equals(weblogHandle)); } - - + + /** * Convenience method for Roller classes trying to determine if a given * weblog handle represents the front page blog configured to render * site-wide data. */ public static boolean isSiteWideWeblog(String weblogHandle) { - + boolean siteWide = getBooleanProperty("site.frontpage.weblog.aggregated"); - + return (isFrontPageWeblog(weblogHandle) && siteWide); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/ConfigDef.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/ConfigDef.java index 0124a2c079..98daae274e 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/ConfigDef.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/ConfigDef.java @@ -33,11 +33,11 @@ * @author Allen Gilliland */ public class ConfigDef { - + private List displayGroups = null; private String name = null; - - + + public ConfigDef() { this.displayGroups = new ArrayList(); } @@ -46,20 +46,20 @@ public ConfigDef(List displaygroups) { this.displayGroups = displaygroups; } - + public boolean addDisplayGroup(DisplayGroup group) { return this.displayGroups.add(group); } - + public boolean removeDisplayGroup(DisplayGroup group) { return this.displayGroups.remove(group); } - - + + public String toString() { return name; } - + public List getDisplayGroups() { return displayGroups; } @@ -75,5 +75,5 @@ public String getName() { public void setName(String name) { this.name = name; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/DisplayGroup.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/DisplayGroup.java index 34139caf13..6dfd617816 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/DisplayGroup.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/DisplayGroup.java @@ -33,34 +33,34 @@ * @author Allen Gilliland */ public class DisplayGroup { - + private List propertyDefs = null; private String name = null; private String key = null; - - + + public DisplayGroup() { this.propertyDefs = new ArrayList(); } - + public DisplayGroup(List propdefs) { this.propertyDefs = propdefs; } - - + + public boolean addPropertyDef(PropertyDef prop) { return this.propertyDefs.add(prop); } - + public boolean removePropertyDef(PropertyDef prop) { return this.propertyDefs.remove(prop); } - + public String toString() { return name+","+key; } - + public List getPropertyDefs() { return propertyDefs; } @@ -84,6 +84,6 @@ public String getKey() { public void setKey(String key) { this.key = key; } - - + + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/PropertyDef.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/PropertyDef.java index 636d754536..ed6772af02 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/PropertyDef.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/PropertyDef.java @@ -37,22 +37,22 @@ * @author Allen Gilliland */ public class PropertyDef { - + private String name = null; private String key = null; private String type = null; private String defaultValue = null; private int rows = 5; private int cols = 25; - - + + /** Creates a new instance of PropertyDef */ public PropertyDef() {} public String toString() { return "["+name+","+key+","+type+","+defaultValue+","+rows+","+cols+"]"; } - + public String getName() { return name; } @@ -109,7 +109,7 @@ public int getCols() { public void setCols(int cols) { this.cols = cols; } - + public void setCols(String cols) { //convert to int try { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefs.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefs.java index 813700d664..9a2ef397fd 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefs.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefs.java @@ -33,10 +33,10 @@ * @author Allen Gilliland */ public class RuntimeConfigDefs { - + private List configDefs = null; - - + + public RuntimeConfigDefs() { this.configDefs = new ArrayList(); } @@ -44,17 +44,17 @@ public RuntimeConfigDefs() { public RuntimeConfigDefs(List configs) { this.configDefs = configs; } - - + + public boolean addConfigDef(ConfigDef config) { return this.configDefs.add(config); } - + public boolean removeConfigDef(ConfigDef config) { return this.configDefs.remove(config); } - - + + public List getConfigDefs() { return configDefs; } @@ -62,5 +62,5 @@ public List getConfigDefs() { public void setConfigDefs(List configDefs) { this.configDefs = configDefs; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefsParser.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefsParser.java index a3de5b963f..1bf8972bf9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefsParser.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/config/runtime/RuntimeConfigDefsParser.java @@ -40,26 +40,26 @@ * @author Allen Gilliland */ public class RuntimeConfigDefsParser { - + /** Creates a new instance of RuntimeConfigDefsParser */ public RuntimeConfigDefsParser() {} - - + + /** * Unmarshall the given input stream into our defined * set of Java objects. **/ - public RuntimeConfigDefs unmarshall(InputStream instream) + public RuntimeConfigDefs unmarshall(InputStream instream) throws IOException, JDOMException { - + if(instream == null) throw new IOException("InputStream is null!"); - + RuntimeConfigDefs configs = new RuntimeConfigDefs(); - + SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(instream); - + Element root = doc.getRootElement(); List configdefs = root.getChildren("config-def"); Iterator iter = configdefs.iterator(); @@ -67,17 +67,17 @@ public RuntimeConfigDefs unmarshall(InputStream instream) Element e = (Element) iter.next(); configs.addConfigDef(this.elementToConfigDef(e)); } - + return configs; } - - + + private ConfigDef elementToConfigDef(Element element) { - + ConfigDef configdef = new ConfigDef(); - + configdef.setName(element.getAttributeValue("name")); - + List displaygroups = element.getChildren("display-group"); Iterator iter = displaygroups.iterator(); while (iter.hasNext()) @@ -85,18 +85,18 @@ private ConfigDef elementToConfigDef(Element element) { Element e = (Element) iter.next(); configdef.addDisplayGroup(this.elementToDisplayGroup(e)); } - + return configdef; } - - + + private DisplayGroup elementToDisplayGroup(Element element) { - + DisplayGroup displaygroup = new DisplayGroup(); - + displaygroup.setName(element.getAttributeValue("name")); displaygroup.setKey(element.getAttributeValue("key")); - + List displaygroups = element.getChildren("property-def"); Iterator iter = displaygroups.iterator(); while (iter.hasNext()) @@ -104,28 +104,28 @@ private DisplayGroup elementToDisplayGroup(Element element) { Element e = (Element) iter.next(); displaygroup.addPropertyDef(this.elementToPropertyDef(e)); } - + return displaygroup; } - - + + private PropertyDef elementToPropertyDef(Element element) { - + PropertyDef prop = new PropertyDef(); - + prop.setName(element.getAttributeValue("name")); prop.setKey(element.getAttributeValue("key")); prop.setType(element.getChildText("type")); prop.setDefaultValue(element.getChildText("default-value")); - + // optional elements if(element.getChild("rows") != null) prop.setRows(element.getChildText("rows")); - + if(element.getChild("cols") != null) prop.setCols(element.getChildText("cols")); - + return prop; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java index 7f48abda7f..f31da8024a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java @@ -28,25 +28,25 @@ /** * Override Planet's URL strategy for use within Roller. */ -public class PlanetURLStrategy extends MultiPlanetURLStrategy { - - +public class PlanetURLStrategy extends MultiPlanetURLStrategy { + + /** * Get URL configured for Planet. * @param planet There's only one planet in Roller, so this is ignored. */ public String getPlanetURL(String planet) { - + StringBuffer url = new StringBuffer(); - + PlanetManager mgr = PlanetFactory.getPlanet().getPlanetManager(); - + url.append(PlanetRuntimeConfig.getProperty("site.absoluteurl")); - + return url.toString(); } - - + + /** * Get URL configured for Planet. * @param planet There's only one planet in Roller, so this is ignored. @@ -57,25 +57,25 @@ public String getPlanetGroupURL(String planet, String group, int pageNum) { StringBuffer url = new StringBuffer(); String sep = "?"; - + url.append(getPlanetURL(planet)); if (group != null) { url.append(sep); url.append("group=").append(group); sep = "&"; } - + if (pageNum > 0) { url.append(sep); url.append("page="); url.append(pageNum); sep = "&"; } - + return url.toString(); } - - + + /** * Get URL of planet group's newsfeed. * @param planet There's only one planet in Roller, so this is ignored. @@ -83,10 +83,10 @@ public String getPlanetGroupURL(String planet, String group, int pageNum) { * @param feed Feed format to be returned (ignored, currently only RSS is supported). */ public String getPlanetGroupFeedURL(String planet, String group, String format) { - + StringBuffer url = new StringBuffer(); String sep = "?"; - + url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); url.append("planetrss"); @@ -95,11 +95,11 @@ public String getPlanetGroupFeedURL(String planet, String group, String format) url.append("group=").append(group); sep = "&"; } - + return url.toString(); } - - + + /** * Currently, Roller doesn't support OPML so this returns null. * @param planet There's only one planet in Roller, so this is ignored. diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java index 77c60eced2..46f9ca5b24 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java @@ -39,48 +39,48 @@ /** - * Extends Roller Planet's feed fetcher to fetch local feeds directly from + * Extends Roller Planet's feed fetcher to fetch local feeds directly from * Weblogger so we don't waste time with lots of feed processing. * * We expect local feeds to have urls of the style ... weblogger: */ public class WebloggerRomeFeedFetcher extends RomeFeedFetcher { - - private static Log log = LogFactory.getLog(WebloggerRomeFeedFetcher.class); - - + + private static Log log = LogFactory.getLog(WebloggerRomeFeedFetcher.class); + + /** * Creates a new instance of WebloggerRomeFeedFetcher */ public WebloggerRomeFeedFetcher() { super(); } - - + + @Override public Subscription fetchSubscription(String feedURL, Date lastModified) throws FetcherException { - + if(feedURL == null) { throw new IllegalArgumentException("feed url cannot be null"); } - + // we handle special weblogger planet integrated subscriptions which have // feedURLs defined as ... weblogger: if(!feedURL.startsWith("weblogger:")) { - log.debug("Feed is remote, letting parent handle it - "+feedURL); + log.debug("Feed is remote, letting parent handle it - "+feedURL); return super.fetchSubscription(feedURL, lastModified); } - + // extract blog handle from our special feed url String weblogHandle = null; String[] items = feedURL.split(":", 2); if(items != null && items.length > 1) { weblogHandle = items[1]; } - + log.debug("Handling LOCAL feed - "+feedURL); - + Weblog localWeblog; try { localWeblog = WebloggerFactory.getWeblogger().getWeblogManager() @@ -88,17 +88,17 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) if (localWeblog == null) { throw new FetcherException("Local feed - "+feedURL+" no longer exists in weblogger"); } - + } catch (WebloggerException ex) { throw new FetcherException("Problem looking up local weblog - "+weblogHandle, ex); } - + // if weblog hasn't changed since last fetch then bail if(lastModified != null && !localWeblog.getLastModified().after(lastModified)) { log.debug("Skipping unmodified LOCAL weblog"); return null; } - + // build planet subscription from weblog Subscription newSub = new Subscription(); newSub.setFeedURL(feedURL); @@ -106,12 +106,12 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) newSub.setTitle(localWeblog.getName()); newSub.setAuthor(localWeblog.getName()); newSub.setLastUpdated(localWeblog.getLastModified()); - + // must have a last updated time if(newSub.getLastUpdated() == null) { newSub.setLastUpdated(new Date()); } - + // lookup recent entries from weblog and add them to the subscription try { int entryCount = WebloggerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries"); @@ -119,7 +119,7 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) if (log.isDebugEnabled()) { log.debug("Seeking up to " + entryCount + " entries from " + localWeblog.getHandle()); } - + // grab recent entries for this weblog WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); List entries = wmgr.getWeblogEntries( @@ -136,7 +136,7 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) null, // locale 0, // offset entryCount); // range - + log.debug("Found " + entries.size()); // Populate subscription object with new entries @@ -151,23 +151,23 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) content = rollerEntry.getSummary(); } content = ppmgr.applyWeblogEntryPlugins(pagePlugins, rollerEntry, content); - + entry.setAuthor(rollerEntry.getCreator().getScreenName()); entry.setTitle(rollerEntry.getTitle()); entry.setPubTime(rollerEntry.getPubTime()); entry.setText(content); entry.setPermalink(rollerEntry.getPermalink()); entry.setCategoriesString(rollerEntry.getCategory().getPath()); - + newSub.addEntry(entry); } - + } catch (WebloggerException ex) { throw new FetcherException("Error processing entries for local weblog - "+weblogHandle, ex); } - + // all done return newSub; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetPersistenceStrategy.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetPersistenceStrategy.java index 1dfbebde7f..e1776ffdbc 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetPersistenceStrategy.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetPersistenceStrategy.java @@ -36,20 +36,20 @@ */ @com.google.inject.Singleton public class JPARollerPlanetPersistenceStrategy extends JPAPersistenceStrategy { - - private static Log logger = - LogFactory.getFactory().getInstance(JPARollerPlanetPersistenceStrategy.class); - - + + private static Log logger = + LogFactory.getFactory().getInstance(JPARollerPlanetPersistenceStrategy.class); + + /** * Construct by finding using DatabaseProvider and WebloggerConfig. - * + * * @throws org.apache.roller.PlanetException on any error */ - protected JPARollerPlanetPersistenceStrategy() throws PlanetException { + protected JPARollerPlanetPersistenceStrategy() throws PlanetException { DatabaseProvider dbProvider = WebloggerStartup.getDatabaseProvider(); - + // Add all OpenJPA and Toplinks properties found in WebloggerConfig Properties emfProps = new Properties(); Enumeration keys = WebloggerConfig.keys(); @@ -61,12 +61,12 @@ protected JPARollerPlanetPersistenceStrategy() throws PlanetException { emfProps.setProperty(key, value); } } - + if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) { // We're doing JNDI, so set OpenJPA JNDI name property String jndiName = "java:comp/env/" + dbProvider.getJndiName(); emfProps.setProperty("openjpa.ConnectionFactoryName", jndiName); - + } else { emfProps.setProperty("javax.persistence.jdbc.driver", dbProvider.getJdbcDriverClass()); emfProps.setProperty("javax.persistence.jdbc.url", dbProvider.getJdbcConnectionURL()); @@ -77,9 +77,9 @@ protected JPARollerPlanetPersistenceStrategy() throws PlanetException { emfProps.setProperty("hibernate.connection.driver_class",dbProvider.getJdbcDriverClass()); emfProps.setProperty("hibernate.connection.url", dbProvider.getJdbcConnectionURL()); emfProps.setProperty("hibernate.connection.username", dbProvider.getJdbcUsername()); - emfProps.setProperty("hibernate.connection.password", dbProvider.getJdbcPassword()); + emfProps.setProperty("hibernate.connection.password", dbProvider.getJdbcPassword()); } - + try { emf = Persistence.createEntityManagerFactory("PlanetPU", emfProps); } catch (PersistenceException pe) { @@ -87,5 +87,5 @@ protected JPARollerPlanetPersistenceStrategy() throws PlanetException { throw new PlanetException(pe); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/RollerPlanetModule.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/RollerPlanetModule.java index 25244c01c8..7061f94396 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/RollerPlanetModule.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/business/jpa/RollerPlanetModule.java @@ -39,16 +39,16 @@ public class RollerPlanetModule implements Module { public void configure(Binder binder) { - + binder.bind(Planet.class).to(JPAPlanetImpl.class); // Use special Planet persistence strategy that works against RollerConfig - binder.bind(JPAPersistenceStrategy.class).to(JPARollerPlanetPersistenceStrategy.class); - - binder.bind(PlanetManager.class).to( JPAPlanetManagerImpl.class); - binder.bind(PropertiesManager.class).to( JPAPropertiesManagerImpl.class); + binder.bind(JPAPersistenceStrategy.class).to(JPARollerPlanetPersistenceStrategy.class); + + binder.bind(PlanetManager.class).to( JPAPlanetManagerImpl.class); + binder.bind(PropertiesManager.class).to( JPAPropertiesManagerImpl.class); binder.bind(URLStrategy.class).to( PlanetURLStrategy.class); binder.bind(FeedFetcher.class).to( WebloggerRomeFeedFetcher.class); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/RefreshRollerPlanetTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/RefreshRollerPlanetTask.java index 9633426c36..6b60ae7d30 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/RefreshRollerPlanetTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/RefreshRollerPlanetTask.java @@ -41,45 +41,45 @@ * - Calls Planet business layer to refresh entries * */ -public class RefreshRollerPlanetTask extends RollerTaskWithLeasing { +public class RefreshRollerPlanetTask extends RollerTaskWithLeasing { private static Log log = LogFactory.getLog(RefreshRollerPlanetTask.class); - + public static String NAME = "RefreshRollerPlanetTask"; - + // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = "unspecifiedClientId"; - + // a String description of when to start this task private String startTimeDesc = "immediate"; - + // interval at which the task is run, default is 60 minutes private int interval = 60; - + // lease time given to task, default is 10 minutes private int leaseTime = 10; - + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - + public void init() throws WebloggerException { this.init(RefreshRollerPlanetTask.NAME); } @@ -90,19 +90,19 @@ public void init(String name) throws WebloggerException { // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -112,7 +112,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -123,15 +123,15 @@ public void init(String name) throws WebloggerException { } } } - - + + public void runTask() { try { log.info("Refreshing Planet subscriptions"); - + FeedUpdater updater = new SingleThreadedFeedUpdater(); updater.updateSubscriptions(); - + } catch (Throwable t) { log.error("ERROR refreshing planet", t); } finally { @@ -140,21 +140,21 @@ public void runTask() { PlanetFactory.getPlanet().release(); } } - - + + public static void main(String[] args) throws Exception { - + // before we can do anything we need to bootstrap the planet backend PlanetStartup.prepare(); - + // we need to use our own planet provider for integration String guiceModule = WebloggerConfig.getProperty("planet.aggregator.guice.module"); PlanetProvider provider = new GuicePlanetProvider(guiceModule); PlanetFactory.bootstrap(provider); - + RefreshRollerPlanetTask task = new RefreshRollerPlanetTask(); task.init(); task.run(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java index 32a0bc9a15..562c2820f7 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java @@ -44,7 +44,7 @@ /** * This tasks is responsible for ensuring that the planet group 'all' contains - * a subscription for every weblogs in the Roller system. It also takes care + * a subscription for every weblogs in the Roller system. It also takes care * of deleting subsctiptions for weblogs that no longer exist. */ public class SyncWebsitesTask extends RollerTaskWithLeasing { @@ -55,37 +55,37 @@ public class SyncWebsitesTask extends RollerTaskWithLeasing { // a unique id for this specific task instance // this is meant to be unique for each client in a clustered environment private String clientId = "unspecifiedClientId"; - + // a String description of when to start this task private String startTimeDesc = "startOfDay"; - + // interval at which the task is run, default is 1 day private int interval = 1440; - + // lease time given to ping task lock, default is 30 minutes private int leaseTime = 30; - + public String getClientId() { return clientId; } - + public Date getStartTime(Date currentTime) { return getAdjustedTime(currentTime, startTimeDesc); } - + public String getStartTimeDesc() { return startTimeDesc; } - + public int getInterval() { return this.interval; } - + public int getLeaseTime() { return this.leaseTime; } - - + + public void init() throws WebloggerException { this.init(RefreshRollerPlanetTask.NAME); } @@ -95,19 +95,19 @@ public void init(String name) throws WebloggerException { // get relevant props Properties props = this.getTaskProperties(); - + // extract clientId String client = props.getProperty("clientId"); if(client != null) { this.clientId = client; } - + // extract start time String startTimeStr = props.getProperty("startTime"); if(startTimeStr != null) { this.startTimeDesc = startTimeStr; } - + // extract interval String intervalStr = props.getProperty("interval"); if(intervalStr != null) { @@ -117,7 +117,7 @@ public void init(String name) throws WebloggerException { log.warn("Invalid interval: "+intervalStr); } } - + // extract lease time String leaseTimeStr = props.getProperty("leaseTime"); if(leaseTimeStr != null) { @@ -128,18 +128,18 @@ public void init(String name) throws WebloggerException { } } } - - + + /** * Ensure there's a subscription in the "all" group for every Roller weblog. */ public void runTask() { - + log.info("Syncing local weblogs with planet subscriptions list"); - + try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + // first, make sure there is an "all" pmgr group Planet planetObject = pmgr.getPlanetById("zzz_default_planet_zzz"); PlanetGroup group = pmgr.getGroup(planetObject, "all"); @@ -151,24 +151,24 @@ public void runTask() { pmgr.saveGroup(group); PlanetFactory.getPlanet().flush(); } - + // walk through all enable weblogs and add/update subs as needed List liveUserFeeds = new ArrayList(); List websites = WebloggerFactory.getWeblogger() .getWeblogManager().getWeblogs(Boolean.TRUE, Boolean.TRUE, null, null, 0, -1); for ( Weblog weblog : websites ) { - + log.debug("processing weblog - "+weblog.getHandle()); String feedUrl = "weblogger:"+weblog.getHandle(); - + // add feed url to the "live" list liveUserFeeds.add(feedUrl); - + // if sub already exists then update it, otherwise add it Subscription sub = pmgr.getSubscription(feedUrl); if (sub == null) { log.debug("ADDING feed: "+feedUrl); - + sub = new Subscription(); sub.setTitle(weblog.getName()); sub.setFeedURL(feedUrl); @@ -177,7 +177,7 @@ public void runTask() { sub.setAuthor(weblog.getName()); sub.setLastUpdated(new Date(0)); pmgr.saveSubscription(sub); - + sub.getGroups().add(group); group.getSubscriptions().add(sub); @@ -185,46 +185,46 @@ public void runTask() { } else { log.debug("UPDATING feed: "+feedUrl); - + sub.setTitle(weblog.getName()); sub.setAuthor(weblog.getName()); - + pmgr.saveSubscription(sub); } - + // save as we go PlanetFactory.getPlanet().flush(); } - + // new subs added, existing subs updated, now delete old subs Set deleteSubs = new HashSet(); Set subs = group.getSubscriptions(); for( Subscription sub : subs ) { - + // only delete subs from the group if ... // 1. they are local - // 2. they are no longer listed as a weblog - if (sub.getFeedURL().startsWith("weblogger:") && + // 2. they are no longer listed as a weblog + if (sub.getFeedURL().startsWith("weblogger:") && !liveUserFeeds.contains(sub.getFeedURL())) { deleteSubs.add(sub); } } - + // now go back through deleteSubs and do actual delete // this is required because deleting a sub in the loop above // causes a ConcurrentModificationException because we can't // modify a collection while we iterate over it for( Subscription deleteSub : deleteSubs ) { - + log.debug("DELETING feed: "+deleteSub.getFeedURL()); pmgr.deleteSubscription(deleteSub); group.getSubscriptions().remove(deleteSub); } - + // all done, lets save pmgr.saveGroup(group); PlanetFactory.getPlanet().flush(); - + } catch (RollerException e) { log.error("ERROR refreshing entries", e); } finally { @@ -233,24 +233,24 @@ public void runTask() { PlanetFactory.getPlanet().release(); } } - - - /** - * Task may be run from the command line + + + /** + * Task may be run from the command line */ public static void main(String[] args) throws Exception { - + // before we can do anything we need to bootstrap the planet backend PlanetStartup.prepare(); - + // we need to use our own planet provider for integration String guiceModule = WebloggerConfig.getProperty("planet.aggregator.guice.module"); PlanetProvider provider = new GuicePlanetProvider(guiceModule); PlanetFactory.bootstrap(provider); - + SyncWebsitesTask task = new SyncWebsitesTask(); task.init(); // use default name task.run(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/AutoPing.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/AutoPing.java index 312e473fd2..582e01697d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/AutoPing.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/AutoPing.java @@ -33,7 +33,7 @@ /** - * Automatic ping configuration. An instance of this class relates a website + * Automatic ping configuration. An instance of this class relates a website * and ping target; it indicates that the specified ping target should be pinged * when the corresponding website is changed. Pinging can be restricted to * changes to specific categories on the website by instances of the @@ -70,8 +70,8 @@ public class AutoPing implements Serializable { private Weblog website = null; public static final long serialVersionUID = -9105985454111986435L; - - + + /** * Default constructor leaves all fields null. Required for bean compliance. */ @@ -92,7 +92,7 @@ public AutoPing(String id, PingTarget pingtarget, Weblog website) { /** * Get the unique id (primary key) of this object. - * @return the unique id of this object. + * @return the unique id of this object. */ @Id @Column(nullable=false,updatable=false) @@ -106,12 +106,12 @@ public String getId() { */ public void setId(String id) { // Form bean workaround: empty string is never a valid id - if (id != null && id.trim().length() == 0) return; + if (id != null && id.trim().length() == 0) return; this.id = id; } /** - * Get the website. Get the website whose changes should result in a ping + * Get the website. Get the website whose changes should result in a ping * to the ping target specified by this object. * @return the website. */ @@ -122,7 +122,7 @@ public Weblog getWebsite() { } /** - * Set the website. Set the website whose changes should result in a ping + * Set the website. Set the website whose changes should result in a ping * to the ping target specified by this object. * @param website the website. */ @@ -159,20 +159,20 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof AutoPing != true) return false; AutoPing o = (AutoPing)other; return new EqualsBuilder() .append(getId(), o.getId()) - .append(getPingTarget(), o.getPingTarget()) - .append(getWebsite(), o.getWebsite()) + .append(getPingTarget(), o.getPingTarget()) + .append(getWebsite(), o.getWebsite()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder().append(getId()).toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/BookmarkComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/BookmarkComparator.java index 3538dfa9ea..4913199a7f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/BookmarkComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/BookmarkComparator.java @@ -23,7 +23,7 @@ public class BookmarkComparator implements Comparator, Serializable { static final long serialVersionUID = 4009699640952161148L; - + public int compare(Object val1, Object val2) throws ClassCastException { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/FileContent.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/FileContent.java index b0e0629ff4..41d1b4c1b8 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/FileContent.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/FileContent.java @@ -28,43 +28,43 @@ * */ public class FileContent { - + // the physical java.io.File backing this resource private File resourceFile = null; - + // the file Id of the resource private String fileId = null; - + // the weblog the resource is attached to private Weblog weblog = null; - - + + public FileContent(Weblog weblog, String fileId, File file) { this.weblog = weblog; this.fileId = fileId; this.resourceFile = file; } - + public Weblog getWeblog() { return weblog; } - + public String getName() { return resourceFile.getName(); } - + public String getFileId() { return fileId; } - + public long getLastModified() { return resourceFile.lastModified(); } - + public long getLength() { return resourceFile.length(); } - + /** * Returns the input stream for the underlying file. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/GlobalPermission.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/GlobalPermission.java index f2b3ffa126..ef57e0ed9f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/GlobalPermission.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/GlobalPermission.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.weblogger.pojos; +package org.apache.roller.weblogger.pojos; import java.security.Permission; import java.util.ArrayList; @@ -35,25 +35,25 @@ public class GlobalPermission extends RollerPermission { /** Allowed to login and edit profile */ public static final String LOGIN = "login"; - + /** Allowed to login and do weblogging */ public static final String WEBLOG = "weblog"; /** Allowed to login and do everything, including site-wide admin */ public static final String ADMIN = "admin"; - + /** - * Create global permission for one specific user initialized with the + * Create global permission for one specific user initialized with the * actions that are implied by the user's roles. * @param user User of permission. * @throws org.apache.roller.weblogger.WebloggerException */ public GlobalPermission(User user) throws WebloggerException { super("GlobalPermission user: " + user.getUserName()); - + // loop through user's roles, adding actions implied by each List roles = WebloggerFactory.getWeblogger().getUserManager().getRoles(user); - List actionsList = new ArrayList(); + List actionsList = new ArrayList(); for (String role : roles) { String impliedActions = WebloggerConfig.getProperty("role.action." + role); if (impliedActions != null) { @@ -67,8 +67,8 @@ public GlobalPermission(User user) throws WebloggerException { } setActionsAsList(actionsList); } - - /** + + /** * Create global permission with the actions specified by array. * @param user User of permission. * @throws org.apache.roller.weblogger.WebloggerException @@ -77,9 +77,9 @@ public GlobalPermission(List actions) throws WebloggerException { super("GlobalPermission user: N/A"); setActionsAsList(actions); } - - /** - * Create global permission for one specific user initialized with the + + /** + * Create global permission for one specific user initialized with the * actions specified by array. * @param user User of permission. * @throws org.apache.roller.weblogger.WebloggerException @@ -88,25 +88,25 @@ public GlobalPermission(User user, List actions) throws WebloggerExcepti super("GlobalPermission user: " + user.getUserName()); setActionsAsList(actions); } - + public boolean implies(Permission perm) { if (perm instanceof WeblogPermission) { if (hasAction(ADMIN)) { // admin implies all other permissions - return true; - } + return true; + } } else if (perm instanceof RollerPermission) { - RollerPermission rperm = (RollerPermission)perm; + RollerPermission rperm = (RollerPermission)perm; if (hasAction(ADMIN)) { // admin implies all other permissions return true; - + } else if (hasAction(WEBLOG)) { // Best we've got is WEBLOG, so make sure perm doesn't specify ADMIN for (String action : rperm.getActionsAsList()) { if (action.equals(ADMIN)) return false; } - + } else if (hasAction(LOGIN)) { // Best we've got is LOGIN, so make sure perm doesn't specify anything else for (String action : rperm.getActionsAsList()) { @@ -118,13 +118,13 @@ public boolean implies(Permission perm) { } return false; } - + private boolean actionImplies(String action1, String action2) { if (action1.equals(ADMIN)) return true; if (action1.equals(WEBLOG) && action2.equals(LOGIN)) return true; return false; } - + public boolean equals(Object arg0) { throw new UnsupportedOperationException("Not supported yet."); } @@ -132,11 +132,11 @@ public boolean equals(Object arg0) { public int hashCode() { throw new UnsupportedOperationException("Not supported yet."); } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("GlobalPermission: "); - for (String action : getActionsAsList()) { + for (String action : getActionsAsList()) { sb.append(" ").append(action).append(" "); } return sb.toString(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java index 2fa1e0f72b..2a2d8b9752 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java @@ -62,7 +62,7 @@ public class MediaFile { private FileContent content; private FileContent thumbnail; - + // TODO: anchor to be populated private String anchor; @@ -133,7 +133,7 @@ public void setLength(long length) { /** * Date uploaded - * + * */ public Timestamp getDateUploaded() { return dateUploaded; diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileDirectory.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileDirectory.java index bc9757cbbf..de3ba18599 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileDirectory.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileDirectory.java @@ -137,7 +137,7 @@ public void setPath(String path) { /** * The collection of files in this directory - * + * */ public Set getMediaFiles() { return mediaFiles; @@ -161,7 +161,7 @@ public void setChildDirectories(Set folders) { /** * Indicates whether this directory contains the specified file. - * + * * @param name file name * @return true if the file is present in the directory, false otherwise. */ @@ -180,7 +180,7 @@ public boolean hasMediaFile(String name) { /** * Returns file with the given name, if present in this directory - * + * * @param name file name * @return media file object */ @@ -199,7 +199,7 @@ public MediaFile getMediaFile(String name) { /** * Indicates whether this directory contains the specified sub-directory. - * + * * @param name directory name * @return true if the sub-directory is present, false otherwise. */ @@ -225,7 +225,7 @@ public MediaFileDirectory getChildDirectory(String name) { /** * Creates a new sub-directory - * + * * @param name new directory name * @return reference to the newly created directory. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileTag.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileTag.java index bc88816295..ca05fd3c01 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileTag.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/MediaFileTag.java @@ -25,11 +25,11 @@ * */ public class MediaFileTag { - + private String id = UUIDGenerator.generateUUID(); String name; MediaFile mediaFile; - + public MediaFileTag() { } @@ -49,7 +49,7 @@ public void setId(String id) { public String getName() { return name; } - + public void setName(String name) { this.name = name; } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.java index cd90f802aa..8a46385f88 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.java @@ -62,7 +62,7 @@ public String getConsumerSecret() { public void setConsumerSecret(String consumerSecret) { this.consumerSecret = consumerSecret; } - + /** * @return the username */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ObjectPermission.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ObjectPermission.java index 002ffc2267..9fa7cc0987 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ObjectPermission.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ObjectPermission.java @@ -25,7 +25,7 @@ /** - * Base permission class for Roller. + * Base permission class for Roller. */ public abstract class ObjectPermission extends RollerPermission { private static Log log = LogFactory.getLog(ObjectPermission.class); @@ -37,12 +37,12 @@ public abstract class ObjectPermission extends RollerPermission { protected boolean pending = false; protected Date dateCreated = new Date(); protected String actions; - - + + public ObjectPermission() { super(""); } - + public ObjectPermission(String name) { super(name); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingQueueEntry.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingQueueEntry.java index de4d5560d5..024a9a6874 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingQueueEntry.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingQueueEntry.java @@ -29,11 +29,11 @@ * Ping queue entry. Each instance of this class represents an entry on the ping queue. The entry indicates when it was * added to the queue, which configuration to apply for the ping, and the number of ping attempts that have been made * for this entry so far. - * + * * @author Anil Gangolli */ public class PingQueueEntry implements Serializable { - + private String id = UUIDGenerator.generateUUID(); private Timestamp entryTime = null; private PingTarget pingTarget = null; @@ -42,7 +42,7 @@ public class PingQueueEntry implements Serializable { public static final long serialVersionUID = -1468021030819538243L; - + /** * Default constructor. Leaves all fields at Java-specified default values. */ @@ -176,22 +176,22 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof PingQueueEntry != true) return false; PingQueueEntry o = (PingQueueEntry)other; return new EqualsBuilder() - .append(getEntryTime(), o.getEntryTime()) - .append(getWebsite(), o.getWebsite()) + .append(getEntryTime(), o.getEntryTime()) + .append(getWebsite(), o.getWebsite()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getEntryTime()) .append(getWebsite()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingTarget.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingTarget.java index 76ed95b669..c275488739 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingTarget.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/PingTarget.java @@ -29,7 +29,7 @@ * Ping target. Each instance represents a possible target of a weblog update ping that we send. Ping targets are * either common (defined centrally by an administrator and used by any website), or custom (defined by the user of a * specific website) for update pings issued for that website. - * + * * @author Anil Gangolli */ public class PingTarget implements Serializable { @@ -242,11 +242,11 @@ public boolean equals(Object other) { if (other instanceof PingTarget != true) return false; PingTarget o = (PingTarget)other; return new EqualsBuilder() - .append(getId(), o.getId()) + .append(getId(), o.getId()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(id) .toHashCode(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Resource.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Resource.java index fe13ef13d3..b9df198cb5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Resource.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Resource.java @@ -25,8 +25,8 @@ * Represents a static resource of some kind. */ public interface Resource { - - + + /** * The short name of this resource. * i.e. "some.jpg" @@ -34,8 +34,8 @@ public interface Resource { * @return The short name for the resource. */ public String getName(); - - + + /** * The path to this resource, relative to its container. * i.e. "images/some.jpg" @@ -43,29 +43,29 @@ public interface Resource { * @return The path to the resource, relative to its container. */ public String getPath(); - - + + /** * The last-modified time for this resource. * * @return The last time the resource changed, as a long value. */ public long getLastModified(); - - + + /** * The length of this resource, in bytes. * * @return The length of the resource in bytes. */ public long getLength(); - - + + /** * An InputStream that the resource can be read from. * * @return an InputStream for the resource. */ public InputStream getInputStream(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RollerPermission.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RollerPermission.java index 9f6ec02e5f..e7afd43c9f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RollerPermission.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RollerPermission.java @@ -25,24 +25,24 @@ /** - * Base permission class for Roller. + * Base permission class for Roller. */ public abstract class RollerPermission extends java.security.Permission { private static Log log = LogFactory.getLog(RollerPermission.class); - + public RollerPermission(String name) { super(name); } - - public abstract void setActions(String actions); + + public abstract void setActions(String actions); public abstract String getActions(); public List getActionsAsList() { return Utilities.stringToStringList(getActions(), ","); } - + public void setActionsAsList(List actionsList) { setActions(Utilities.stringListToString(actionsList, ",")); } @@ -51,7 +51,7 @@ public boolean hasAction(String action) { List actionList = getActionsAsList(); return actionList.contains(action); } - + public boolean hasActions(List actionsToCheck) { List actionList = getActionsAsList(); for (String actionToCheck : actionsToCheck) { @@ -59,7 +59,7 @@ public boolean hasActions(List actionsToCheck) { } return true; } - + /** * Merge actions into this permission. */ @@ -73,7 +73,7 @@ public void addActions(ObjectPermission perm) { } setActionsAsList(updatedActions); } - + /** * Merge actions into this permission. */ @@ -86,7 +86,7 @@ public void addActions(List newActions) { } setActionsAsList(updatedActions); } - + /** * Merge actions into this permission. */ @@ -98,7 +98,7 @@ public void removeActions(List actionsToRemove) { log.debug("updatedActions2: " + updatedActions); setActionsAsList(updatedActions); } - + /** * True if permission specifies no actions */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.java index 6c0a34e234..4f84913d95 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.java @@ -27,22 +27,22 @@ * This POJO represents a single property of the roller system. */ public class RuntimeConfigProperty implements Serializable { - + public static final long serialVersionUID = 6913562779484028899L; - + private String name; private String value; - - + + public RuntimeConfigProperty() {} - - + + public RuntimeConfigProperty(String name, String value) { this.name = name; this.value = value; } - - + + /** * Getter for property name. * @@ -51,7 +51,7 @@ public RuntimeConfigProperty(String name, String value) { public String getName() { return this.name; } - + /** * Setter for property name. * @@ -60,7 +60,7 @@ public String getName() { public void setName(String name) { this.name = name; } - + /** * Getter for property value. * @@ -69,7 +69,7 @@ public void setName(String name) { public String getValue() { return this.value; } - + /** * Setter for property value. * @@ -78,13 +78,13 @@ public String getValue() { public void setValue(String value) { this.value = value; } - + //------------------------------------------------------- Good citizenship - + public String toString() { return (this.name + "=" + this.value); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof RuntimeConfigProperty != true) return false; @@ -93,11 +93,11 @@ public boolean equals(Object other) { .append(getName(), o.getName()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCount.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCount.java index 1a15a72822..d6663b906d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCount.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCount.java @@ -23,23 +23,23 @@ /** * Represents a statistical count. */ -public class StatCount { - +public class StatCount { + /** Id of the subject of the statistic */ private String subjectId; - + /** Short name of the subject of the statistic */ private String subjectNameShort; - + /** Long name of the subject of the statistic */ - private String subjectNameLong; - + private String subjectNameLong; + /** I18N key that describes the type of statistic */ private String typeKey; - - /** The statistical count */ + + /** The statistical count */ private long count; - + /** Weblog handle of weblog that stat is associated with, or null if none */ private String weblogHandle = null; @@ -49,44 +49,44 @@ public StatCount(String subjectId, String subjectNameShort, String subjectNameLo this.setSubjectNameLong(subjectNameLong); this.setTypeKey(typeKey); this.setCount(count); - } - + } + public String getTypeKey() { return typeKey; } - + public void setTypeKey(String typeKey) { this.typeKey = typeKey; } - + public long getCount() { return count; } - + public void setCount(long count) { this.count = count; } - + public String getSubjectId() { return subjectId; } - + public void setSubjectId(String subjectId) { this.subjectId = subjectId; } - + public String getSubjectNameShort() { return subjectNameShort; } - + public void setSubjectNameShort(String subjectNameShort) { this.subjectNameShort = subjectNameShort; } - + public String getSubjectNameLong() { return subjectNameLong; } - + public void setSubjectNameLong(String subjectNameLong) { this.subjectNameLong = subjectNameLong; } @@ -98,7 +98,7 @@ public String getWeblogHandle() { public void setWeblogHandle(String weblogHandle) { this.weblogHandle = weblogHandle; } - + //------------------------------------------------------- Good citizenship public String toString() { @@ -115,12 +115,12 @@ public boolean equals(Object other) { if (other instanceof StatCount != true) return false; StatCount o = (StatCount)other; return new EqualsBuilder() - .append(getSubjectId(), o.getSubjectId()) - .append(getTypeKey(), o.getTypeKey()) + .append(getSubjectId(), o.getSubjectId()) + .append(getTypeKey(), o.getTypeKey()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getSubjectId()) .append(getTypeKey()) diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCountCountComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCountCountComparator.java index 416813e4ff..bfae16bc24 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCountCountComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StatCountCountComparator.java @@ -27,19 +27,19 @@ public class StatCountCountComparator implements Comparator, Serializable { private static final long serialVersionUID = 4811314286365625712L; - + private static StatCountCountComparator instance = new StatCountCountComparator(); /** - * + * */ private StatCountCountComparator() { } - /** + /** * Compares two StatCount instances according to their count values. - * + * * @throws ClassCastException if arguments are not instances of StatCount * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @@ -48,11 +48,11 @@ public int compare(Object obj1, Object obj2) throws ClassCastException { StatCount sc2 = (StatCount) obj2; int compVal = sc1.getCount() < sc2.getCount() ? -1 : (sc1.getCount() == sc2.getCount() ? 0 : 1); - + if (compVal == 0) { compVal = sc1.getSubjectId().compareTo(sc2.getSubjectId()); if (compVal == 0) { - compVal = sc1.getTypeKey().compareTo(sc2.getTypeKey()); + compVal = sc1.getTypeKey().compareTo(sc2.getTypeKey()); } } return compVal; diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticTemplate.java index 47c1f8453a..b2c102d58b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticTemplate.java @@ -30,23 +30,23 @@ * an object. */ public class StaticTemplate implements Template, Serializable { - + private String id = null; private String name = null; private String description = null; private Date lastModified = new Date(); private String templateLanguage = null; private String outputContentType = null; - - + + public StaticTemplate(String id, String lang) { this.id = id; this.name = id; this.description = id; this.templateLanguage = lang; } - - + + public String getId() { return id; } @@ -86,7 +86,7 @@ public String getTemplateLanguage() { public void setTemplateLanguage(String templateLanguage) { this.templateLanguage = templateLanguage; } - + public String getOutputContentType() { return outputContentType; } @@ -94,5 +94,5 @@ public String getOutputContentType() { public void setOutputContentType(String outputContentType) { this.outputContentType = outputContentType; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticThemeTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticThemeTemplate.java index b911b2c8b2..5ab42ae333 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticThemeTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/StaticThemeTemplate.java @@ -30,7 +30,7 @@ * an object. */ public class StaticThemeTemplate implements ThemeTemplate, Serializable { - + private String id = null; private String name = null; private String description = null; @@ -44,8 +44,8 @@ public class StaticThemeTemplate implements ThemeTemplate, Serializable { private String outputContentType = null; private String decoratorName = null; private ThemeTemplate decorator = null; - - + + public StaticThemeTemplate(String id, String lang) { this.id = id; this.name = id; @@ -53,8 +53,8 @@ public StaticThemeTemplate(String id, String lang) { this.link = id; this.templateLanguage = lang; } - - + + public String getId() { return id; } @@ -94,7 +94,7 @@ public String getTemplateLanguage() { public void setTemplateLanguage(String templateLanguage) { this.templateLanguage = templateLanguage; } - + public String getOutputContentType() { return outputContentType; } @@ -158,5 +158,5 @@ public String getDecoratorName() { public void setDecoratorName(String decoratorName) { this.decoratorName = decoratorName; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStat.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStat.java index 54c825e8cf..26bb03f809 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStat.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStat.java @@ -20,9 +20,9 @@ /** * Tag bean. - * + * * @author Elias Torres - * + * */ public class TagStat implements java.io.Serializable { @@ -31,7 +31,7 @@ public class TagStat implements java.io.Serializable { private String name; private int count; - + private int intensity; public TagStat() { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatComparator.java index a9f19c35c5..33689b7570 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatComparator.java @@ -29,7 +29,7 @@ public class TagStatComparator implements Comparator, Serializable { private static final long serialVersionUID = -3272396777374523757L; /** - * + * */ public TagStatComparator() { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatCountComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatCountComparator.java index d3447b3b67..fb04fbd55f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatCountComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TagStatCountComparator.java @@ -29,17 +29,17 @@ public class TagStatCountComparator implements Comparator, Serializable { private static final long serialVersionUID = 1155112837815739929L; private static TagStatCountComparator instance = new TagStatCountComparator(); - + /** - * + * */ public TagStatCountComparator() { } - /** + /** * Compares two TagStat instances according to their count values. - * + * * @throws ClassCastException if arguments are not instances of TagStat * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @@ -48,7 +48,7 @@ public int compare(Object obj1, Object obj2) throws ClassCastException { TagStat st2 = (TagStat) obj2; int compVal = st1.getCount() < st2.getCount() ? -1 : (st1.getCount() == st2.getCount() ? 0 : 1); - + if (compVal == 0) { compVal = st1.getName().compareTo(st2.getName()); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TaskLock.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TaskLock.java index 32d9e0d068..f4bddeb365 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TaskLock.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/TaskLock.java @@ -28,56 +28,56 @@ * Represents locking information about a specific RollerTask. */ public class TaskLock implements Serializable { - + private String id = UUIDGenerator.generateUUID(); private String name = null; private Date timeAquired = null; private int timeLeased = 0; private Date lastRun = null; private String clientId = null; - - + + public TaskLock() {} - - + + /** - * Calculate the next allowed time this task is allowed to run allowed to run. + * Calculate the next allowed time this task is allowed to run allowed to run. * i.e. lastRun + interval */ public Date getNextAllowedRun(int interval) { - + Date previousRun = getLastRun(); if(previousRun == null) { return new Date(0); } - + // calculate next run time Calendar cal = Calendar.getInstance(); cal.setTime(previousRun); cal.add(Calendar.MINUTE, interval); - + return cal.getTime(); } - - + + /** * Get the time the last/current lease for this lock expires. - * + * * expireTime = timeAcquired + (timeLeased * 60sec/min) - 1 sec * we remove 1 second to adjust for precision differences */ public Date getLeaseExpiration() { - + Date leaseAcquisitionTime = new Date(0); if(getTimeAquired() != null) { leaseAcquisitionTime = getTimeAquired(); } - + // calculate lease expiration time Calendar cal = Calendar.getInstance(); cal.setTime(leaseAcquisitionTime); cal.add(Calendar.MINUTE, timeLeased); - + return cal.getTime(); } @@ -97,22 +97,22 @@ public String toString() { @Override public boolean equals(Object other) { - + if(this == other) return true; if( !(other instanceof TaskLock) ) return false; - + // our natural key, or business key, is our name final TaskLock that = (TaskLock) other; return this.getName().equals(that.getName()); } - + @Override public int hashCode() { // our natrual key, or business key, is our name return this.getName().hashCode(); } - - + + public String getId() { return id; } @@ -121,7 +121,7 @@ public void setId(String id) { this.id = id; } - + public String getName() { return name; } @@ -130,7 +130,7 @@ public void setName(String name) { this.name = name; } - + public Date getTimeAquired() { return timeAquired; } @@ -139,7 +139,7 @@ public void setTimeAquired(Date timeAquired) { this.timeAquired = timeAquired; } - + public Date getLastRun() { return lastRun; } @@ -147,8 +147,8 @@ public Date getLastRun() { public void setLastRun(Date lastRun) { this.lastRun = lastRun; } - - + + public int getTimeLeased() { return timeLeased; } @@ -157,7 +157,7 @@ public void setTimeLeased(int timeLeased) { this.timeLeased = timeLeased; } - + public String getClientId() { return clientId; } @@ -165,5 +165,5 @@ public String getClientId() { public void setClientId(String clientId) { this.clientId = clientId; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Template.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Template.java index a8965df14d..c730ddd23e 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Template.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Template.java @@ -28,40 +28,40 @@ * Velocity rendering engine. */ public interface Template { - + /** * The unique identifier for this Template. */ public String getId(); - - + + /** * A simple name for this Template. */ public String getName(); - - + + /** * A description of the contents of this Template. */ public String getDescription(); - - + + /** * The last time the template was modified. */ public Date getLastModified(); - - + + /** * The templating language used by this template. */ public String getTemplateLanguage(); - - + + /** * Content-type of output or null if none defined. */ public String getOutputContentType(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Theme.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Theme.java index 30c6f3e477..108e4480bf 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Theme.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Theme.java @@ -28,80 +28,80 @@ * web design for a weblog along with some metadata like a name, etc. */ public interface Theme { - + /** * A unique identifier for this Theme. */ public String getId(); - - + + /** * A common or display name for this Theme. */ public String getName(); - - + + /** * A description of the Theme. */ public String getDescription(); - - + + /** * The last modification date of the Theme. */ public Date getLastModified(); - - + + /** * Is the Theme enable for use? */ public boolean isEnabled(); - - + + /** * Get the list of all templates associated with this Theme. */ public List getTemplates() throws WebloggerException; - - + + /** * Lookup the stylesheet template for the Theme. */ public ThemeTemplate getStylesheet() throws WebloggerException; - - + + /** * Lookup the default template for the Theme. */ public ThemeTemplate getDefaultTemplate() throws WebloggerException; - - + + /** * Lookup a template by action. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByAction(String action) throws WebloggerException; - - + + /** * Lookup a template by name. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByName(String name) throws WebloggerException; - - + + /** * Lookup a template by link. * Returns null if the template cannot be found. */ public ThemeTemplate getTemplateByLink(String link) throws WebloggerException; - - + + /** * Lookup a resource by path. * Returns null if the resource cannot be found. */ public ThemeResource getResource(String path); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeResource.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeResource.java index 4c32ec417a..3348967580 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeResource.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeResource.java @@ -23,7 +23,7 @@ * A Resource that is attached to a Theme. */ public interface ThemeResource extends Resource { - + /** * Does this resource represent a directory? True if yes, False otherwise. * diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeTemplate.java index 1d5579774c..3fb73a4eaa 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/ThemeTemplate.java @@ -21,68 +21,68 @@ /** * A Theme specific implementation of a Template. - * + * * A ThemeTemplate represents a template which is part of a Theme. */ public interface ThemeTemplate extends Template { - + public static final String ACTION_WEBLOG = "weblog"; public static final String ACTION_PERMALINK = "permalink"; public static final String ACTION_SEARCH = "search"; public static final String ACTION_TAGSINDEX = "tagsIndex"; public static final String ACTION_CUSTOM = "custom"; - + // the full list of supported special actions, which purposely does not // contain an entry for the 'custom' action public static final String[] ACTIONS = { - ACTION_WEBLOG, - ACTION_PERMALINK, - ACTION_SEARCH, + ACTION_WEBLOG, + ACTION_PERMALINK, + ACTION_SEARCH, ACTION_TAGSINDEX }; - - + + /** * The action this template is defined for. */ public String getAction(); - - + + /** * The contents or body of the Template. */ public String getContents(); - - + + /** * The url link value for this Template. If this template is not * private this is the url that it can be accessed at. */ public String getLink(); - - + + /** * Is the Template hidden? A hidden template cannot be accessed directly. */ public boolean isHidden(); - - + + /** * Is the Template to be included in the navbar? */ public boolean isNavbar(); - - + + /** * The name of the decorator template to apply. */ public String getDecoratorName(); - - + + /** * The decorator Template to apply. This returns null if no decorator * should be applied. */ public ThemeTemplate getDecorator(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/User.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/User.java index 46d9378521..79f557750c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/User.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/User.java @@ -41,9 +41,9 @@ * @hibernate.class lazy="true" table="rolleruser" */ public class User implements Serializable { - + public static final long serialVersionUID = -6354583200913127874L; - + private String id = UUIDGenerator.generateUUID(); private String userName; private String password; @@ -55,14 +55,14 @@ public class User implements Serializable { private String timeZone; private Boolean enabled = Boolean.TRUE; private String activationCode; - + private Set roles = new HashSet(); private List permissions = new ArrayList(); - - + + public User() { } - + public User( String id, String userName, String password, String fullName, String emailAddress, @@ -79,8 +79,8 @@ public User( String id, String userName, this.timeZone = timeZone; this.enabled = isEnabled; } - - + + /** * Id of the User. * @@ -89,12 +89,12 @@ public User( String id, String userName, public String getId() { return this.id; } - + public void setId( String id ) { this.id = id; } - - + + /** * User name of the user. * @hibernate.property column="username" non-null="true" unique="true" @@ -102,11 +102,11 @@ public void setId( String id ) { public String getUserName() { return this.userName; } - + public void setUserName( String userName ) { this.userName = userName; } - + /** * Get password. * If password encryption is enabled, will return encrypted password. @@ -116,7 +116,7 @@ public void setUserName( String userName ) { public String getPassword() { return this.password; } - + /** * Set password. * If password encryption is turned on, then pass in an encrypted password. @@ -124,14 +124,14 @@ public String getPassword() { public void setPassword( String password ) { this.password = password; } - + /** * Reset this user's password, handles encryption if configured. * * @param newPassword The new password to be set. */ public void resetPassword(String newPassword) throws WebloggerException { - + String encrypt = WebloggerConfig.getProperty("passwds.encryption.enabled"); String algorithm = WebloggerConfig.getProperty("passwds.encryption.algorithm"); if (new Boolean(encrypt).booleanValue()) { @@ -140,8 +140,8 @@ public void resetPassword(String newPassword) throws WebloggerException { setPassword(newPassword); } } - - + + /** * Screen name of the user. * @@ -150,12 +150,12 @@ public void resetPassword(String newPassword) throws WebloggerException { public String getScreenName() { return this.screenName; } - + public void setScreenName( String screenName ) { this.screenName = screenName; } - - + + /** * Full name of the user. * @@ -164,12 +164,12 @@ public void setScreenName( String screenName ) { public String getFullName() { return this.fullName; } - + public void setFullName( String fullName ) { this.fullName = fullName; } - - + + /** * E-mail address of the user. * @@ -178,12 +178,12 @@ public void setFullName( String fullName ) { public String getEmailAddress() { return this.emailAddress; } - + public void setEmailAddress( String emailAddress ) { this.emailAddress = emailAddress; } - - + + /** * The date the user was created. * @@ -196,7 +196,7 @@ public Date getDateCreated() { return (Date)dateCreated.clone(); } } - + public void setDateCreated(final Date date) { if (date != null) { dateCreated = (Date)date.clone(); @@ -204,8 +204,8 @@ public void setDateCreated(final Date date) { dateCreated = null; } } - - + + /** * Locale of the user. * @@ -214,12 +214,12 @@ public void setDateCreated(final Date date) { public String getLocale() { return this.locale; } - + public void setLocale(String locale) { this.locale = locale; } - - + + /** * Timezone of the user. * @@ -228,12 +228,12 @@ public void setLocale(String locale) { public String getTimeZone() { return this.timeZone; } - + public void setTimeZone(String timeZone) { this.timeZone = timeZone; } - - + + /** * Is this user account enabled? Disabled accounts cannot login. * @@ -242,13 +242,13 @@ public void setTimeZone(String timeZone) { public Boolean getEnabled() { return this.enabled; } - + public void setEnabled(Boolean enabled) { this.enabled = enabled; } - - - /** + + + /** * Activation code. * * @hibernate.property column="activationcode" non-null="false" @@ -256,16 +256,16 @@ public void setEnabled(Boolean enabled) { public String getActivationCode() { return activationCode; } - + public void setActivationCode(String activationCode) { this.activationCode = activationCode; } - - + + public boolean hasGlobalPermission(String action) { return hasGlobalPermissions(Collections.singletonList(action)); } - + public boolean hasGlobalPermissions(List actions) { try { GlobalPermission perm = new GlobalPermission(actions); @@ -274,9 +274,9 @@ public boolean hasGlobalPermissions(List actions) { return false; } } - + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -289,16 +289,16 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof User != true) return false; User o = (User)other; return new EqualsBuilder().append(getUserName(), o.getUserName()).isEquals(); } - + public int hashCode() { return new HashCodeBuilder().append(getUserName()).toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserAttribute.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserAttribute.java index 58d9ea88ef..af2a3b6891 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserAttribute.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserAttribute.java @@ -29,26 +29,26 @@ * @author Tatyana Tokareva */ public class UserAttribute implements Serializable { - - public static final long serialVersionUID = -6354583200913127874L; - + + public static final long serialVersionUID = -6354583200913127874L; + private String id = UUIDGenerator.generateUUID(); private String userName; private String attrName; private String attrValue; - - + + public static enum Attributes { OPENID_URL("openid.url"); - + private Attributes(String name) { this.name = name; - } + } private final String name; @Override public String toString() { return name; - } + } public String get() { return name.toString(); } @@ -62,8 +62,8 @@ public UserAttribute(String userName, String attrName, String attrValue) { this.userName = userName; this.attrName = attrName; this.attrValue = attrValue; - } - + } + public String getId() { return id; } @@ -79,7 +79,7 @@ public String getUserName() { public void setUserName(String userId) { this.userName = userId; } - + public String getName() { return attrName; } @@ -106,7 +106,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof UserRole != true) return false; @@ -114,10 +114,10 @@ public boolean equals(Object other) { return new EqualsBuilder() .append(getUserName(), o.getUserName()) .append(getName(), o.getName()) - .append(getValue(), o.getValue()) + .append(getValue(), o.getValue()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder().append(getUserName()).append(getName()).append(getValue()).toHashCode(); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserRole.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserRole.java index f99ab21718..6e51b1361f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserRole.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/UserRole.java @@ -28,52 +28,52 @@ * Role bean. */ public class UserRole implements Serializable { - + public static final long serialVersionUID = -4254083071697970972L; - + private String id = UUIDGenerator.generateUUID(); private String userName; private String role; - - + + public UserRole() { } - + public UserRole(String username, String role) { this.userName = username; this.role = role; } - - + + public String getId() { return this.id; } - + public void setId( String id ) { this.id = id; } - - + + public String getUserName() { return this.userName; } - + public void setUserName( String userName ) { this.userName = userName; - } - - + } + + public String getRole() { return this.role; } - + public void setRole( String role ) { this.role = role; } - - + + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -83,7 +83,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof UserRole != true) return false; @@ -93,9 +93,9 @@ public boolean equals(Object other) { .append(getUserName(), o.getUserName()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder().append(getUserName()).append(getRole()).toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Weblog.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Weblog.java index 2ef175e6f0..aa34f1f82d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Weblog.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/Weblog.java @@ -56,11 +56,11 @@ * @author David M Johnson */ public class Weblog implements Serializable { - + public static final long serialVersionUID = 206437645033737127L; - + private static Log log = LogFactory.getLog(Weblog.class); - + // Simple properties private String id = UUIDGenerator.generateUUID(); private String handle = null; @@ -94,17 +94,17 @@ public class Weblog implements Serializable { private String iconPath = null; private String about = null; private String creator = null; - + // Associated objects private List permissions = new ArrayList(); private WeblogCategory bloggerCategory = null; private WeblogCategory defaultCategory = null; - + private Map initializedPlugins = null; - - public Weblog() { + + public Weblog() { } - + public Weblog( String handle, String creator, @@ -115,7 +115,7 @@ public Weblog( String editorTheme, String locale, String timeZone) { - + this.handle = handle; this.creator = creator; this.name = name; @@ -126,7 +126,7 @@ public Weblog( this.locale = locale; this.timeZone = timeZone; } - + //------------------------------------------------------- Good citizenship public String toString() { @@ -147,16 +147,16 @@ public boolean equals(Object other) { if (other instanceof Weblog != true) return false; Weblog o = (Weblog)other; return new EqualsBuilder() - .append(getHandle(), o.getHandle()) + .append(getHandle(), o.getHandle()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getHandle()) .toHashCode(); - } - + } + /** * @hibernate.bag lazy="true" inverse="true" cascade="delete" * @hibernate.collection-key column="website_id" @@ -169,8 +169,8 @@ public int hashCode() { public void setPermissions(List perms) { permissions = perms; }*/ - - + + /** * Get the Theme object in use by this weblog, or null if no theme selected. */ @@ -182,44 +182,44 @@ public WeblogTheme getTheme() { } catch (WebloggerException ex) { log.error("Error getting theme for weblog - "+getHandle(), ex); } - + // TODO: maybe we should return a default theme in this case? return null; } - - + + /** * Lookup the default page for this website. */ public ThemeTemplate getDefaultPage() throws WebloggerException { - + // look for the page in our Theme Theme weblogTheme = getTheme(); if(weblogTheme != null) { return weblogTheme.getDefaultTemplate(); } - + return null; } - - + + /** * Id of the Website. * * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field * @hibernate.id column="id" - * generator-class="assigned" + * generator-class="assigned" */ public String getId() { return this.id; } - + /** @ejb:persistent-field */ public void setId(String id) { this.id = id; } - + /** * Short URL safe string that uniquely identifies the website. * @ejb:persistent-field @@ -229,12 +229,12 @@ public void setId(String id) { public String getHandle() { return this.handle; } - + /** @ejb:persistent-field */ public void setHandle(String handle) { this.handle = handle; } - + /** * Name of the Website. * @@ -245,12 +245,12 @@ public void setHandle(String handle) { public String getName() { return this.name; } - + /** @ejb:persistent-field */ public void setName(String name) { this.name = name; } - + /** * Description * @@ -261,12 +261,12 @@ public void setName(String name) { public String getDescription() { return this.description; } - + /** @ejb:persistent-field */ public void setDescription(String description) { this.description = description; } - + /** * Original creator of website. * @roller.wrapPojoMethod type="pojo" @@ -279,7 +279,7 @@ public org.apache.roller.weblogger.pojos.User getCreator() { } return null; } - + /** * Username of original creator of website. * @roller.wrapPojoMethod type="pojo" @@ -287,11 +287,11 @@ public org.apache.roller.weblogger.pojos.User getCreator() { public String getCreatorUserName() { return creator; } - + public void setCreatorUserName(String creatorUserName) { creator = creatorUserName; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -300,14 +300,14 @@ public void setCreatorUserName(String creatorUserName) { public String getDefaultPageId() { return this.defaultPageId; } - + /** * @ejb:persistent-field */ public void setDefaultPageId(String defaultPageId) { this.defaultPageId = defaultPageId; } - + /** * @roller.wrapPojoMethod type="simple" * @deprecated @@ -317,7 +317,7 @@ public void setDefaultPageId(String defaultPageId) { public String getWeblogDayPageId() { return this.weblogDayPageId; } - + /** * @deprecated * @ejb:persistent-field @@ -325,7 +325,7 @@ public String getWeblogDayPageId() { public void setWeblogDayPageId(String weblogDayPageId) { this.weblogDayPageId = weblogDayPageId; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -334,12 +334,12 @@ public void setWeblogDayPageId(String weblogDayPageId) { public Boolean getEnableBloggerApi() { return this.enableBloggerApi; } - + /** @ejb:persistent-field */ public void setEnableBloggerApi(Boolean enableBloggerApi) { this.enableBloggerApi = enableBloggerApi; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -348,12 +348,12 @@ public void setEnableBloggerApi(Boolean enableBloggerApi) { public WeblogCategory getBloggerCategory() { return bloggerCategory; } - + /** @ejb:persistent-field */ public void setBloggerCategory(WeblogCategory bloggerCategory) { this.bloggerCategory = bloggerCategory; } - + /** * By default,the default category for a weblog is the root and all macros * work with the top level categories that are immediately under the root. @@ -366,12 +366,12 @@ public void setBloggerCategory(WeblogCategory bloggerCategory) { public WeblogCategory getDefaultCategory() { return defaultCategory; } - + /** @ejb:persistent-field */ public void setDefaultCategory(WeblogCategory defaultCategory) { this.defaultCategory = defaultCategory; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -380,12 +380,12 @@ public void setDefaultCategory(WeblogCategory defaultCategory) { public String getEditorPage() { return this.editorPage; } - + /** @ejb:persistent-field */ public void setEditorPage(String editorPage) { this.editorPage = editorPage; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -394,12 +394,12 @@ public void setEditorPage(String editorPage) { public String getBlacklist() { return this.blacklist; } - + /** @ejb:persistent-field */ public void setBlacklist(String blacklist) { this.blacklist = blacklist; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -408,12 +408,12 @@ public void setBlacklist(String blacklist) { public Boolean getAllowComments() { return this.allowComments; } - + /** @ejb:persistent-field */ public void setAllowComments(Boolean allowComments) { this.allowComments = allowComments; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -422,12 +422,12 @@ public void setAllowComments(Boolean allowComments) { public Boolean getDefaultAllowComments() { return defaultAllowComments; } - + /** @ejb:persistent-field */ public void setDefaultAllowComments(Boolean defaultAllowComments) { this.defaultAllowComments = defaultAllowComments; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -436,12 +436,12 @@ public void setDefaultAllowComments(Boolean defaultAllowComments) { public int getDefaultCommentDays() { return defaultCommentDays; } - + /** @ejb:persistent-field */ public void setDefaultCommentDays(int defaultCommentDays) { this.defaultCommentDays = defaultCommentDays; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -450,12 +450,12 @@ public void setDefaultCommentDays(int defaultCommentDays) { public Boolean getModerateComments() { return moderateComments; } - + /** @ejb:persistent-field */ public void setModerateComments(Boolean moderateComments) { this.moderateComments = moderateComments; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -464,12 +464,12 @@ public void setModerateComments(Boolean moderateComments) { public Boolean getEmailComments() { return this.emailComments; } - + /** @ejb:persistent-field */ public void setEmailComments(Boolean emailComments) { this.emailComments = emailComments; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -478,12 +478,12 @@ public void setEmailComments(Boolean emailComments) { public String getEmailFromAddress() { return this.emailFromAddress; } - + /** @ejb:persistent-field */ public void setEmailFromAddress(String emailFromAddress) { this.emailFromAddress = emailFromAddress; } - + /** * @ejb:persistent-field * @roller.wrapPojoMethod type="simple" @@ -492,12 +492,12 @@ public void setEmailFromAddress(String emailFromAddress) { public String getEmailAddress() { return this.emailAddress; } - + /** @ejb:persistent-field */ public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } - + /** * EditorTheme of the Website. * @@ -508,12 +508,12 @@ public void setEmailAddress(String emailAddress) { public String getEditorTheme() { return this.editorTheme; } - + /** @ejb:persistent-field */ public void setEditorTheme(String editorTheme) { this.editorTheme = editorTheme; } - + /** * Locale of the Website. * @@ -524,12 +524,12 @@ public void setEditorTheme(String editorTheme) { public String getLocale() { return this.locale; } - + /** @ejb:persistent-field */ public void setLocale(String locale) { this.locale = locale; } - + /** * Timezone of the Website. * @@ -540,12 +540,12 @@ public void setLocale(String locale) { public String getTimeZone() { return this.timeZone; } - + /** @ejb:persistent-field */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } - + /** * @ejb:persistent-field * @hibernate.property column="datecreated" non-null="true" unique="false" @@ -566,7 +566,7 @@ public void setDateCreated(final Date date) { dateCreated = null; } } - + /** * Comma-delimited list of user's default Plugins. * @@ -577,18 +577,18 @@ public void setDateCreated(final Date date) { public String getDefaultPlugins() { return defaultPlugins; } - + /** @ejb:persistent-field */ public void setDefaultPlugins(String string) { defaultPlugins = string; } - - + + /** * Set bean properties based on other bean. */ public void setData(Weblog other) { - + this.setId(other.getId()); this.setName(other.getName()); this.setHandle(other.getHandle()); @@ -615,8 +615,8 @@ public void setData(Weblog other) { this.setActive(other.getActive()); this.setLastModified(other.getLastModified()); } - - + + /** * Parse locale value and instantiate a Locale object, * otherwise return default Locale. @@ -626,8 +626,8 @@ public void setData(Weblog other) { public Locale getLocaleInstance() { return I18nUtils.toLocale(getLocale()); } - - + + /** * Return TimeZone instance for value of timeZone, * otherwise return system default instance. @@ -645,16 +645,16 @@ public TimeZone getTimeZoneInstance() { } return TimeZone.getTimeZone(timeZone); } - - + + /** * Returns true if user has all permission action specified. */ public boolean hasUserPermission(User user, String action) { return hasUserPermissions(user, Collections.singletonList(action)); } - - + + /** * Returns true if user has all permissions actions specified in the weblog. */ @@ -664,14 +664,14 @@ public boolean hasUserPermissions(User user, List actions) { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); WeblogPermission userPerms = new WeblogPermission(this, user, actions); return umgr.checkPermission(userPerms, user); - + } catch (WebloggerException ex) { // something is going seriously wrong, not much we can do here log.error("ERROR checking user permssion", ex); } return false; } - + /** Get number of users associated with website */ public int getUserCount() { int count = 0; @@ -682,20 +682,20 @@ public int getUserCount() { WeblogPermission perm = (WeblogPermission) iter.next(); count++; } - + } catch (WebloggerException ex) { // something is seriously wrong, not me we can do here log.error("ERROR error getting admin user count", ex); } return count; } - + /** No-op needed to please XDoclet generated code */ private int userCount = 0; public void setUserCount(int userCount) { // no-op } - + public int getAdminUserCount() { int count = 0; try { @@ -707,21 +707,21 @@ public int getAdminUserCount() { count++; } } - + } catch (WebloggerException ex) { // something is seriously wrong, not me we can do here log.error("ERROR error getting admin user count", ex); } return count; } - + /** No-op needed to please XDoclet generated code */ private int adminUserCount = 0; public void setAdminUserCount(int adminUserCount) { // no-op } - - + + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -730,14 +730,14 @@ public void setAdminUserCount(int adminUserCount) { public int getEntryDisplayCount() { return entryDisplayCount; } - + /** * @ejb:persistent-field */ public void setEntryDisplayCount(int entryDisplayCount) { this.entryDisplayCount = entryDisplayCount; } - + /** * Set to FALSE to completely disable and hide this weblog from public view. * @@ -748,12 +748,12 @@ public void setEntryDisplayCount(int entryDisplayCount) { public Boolean getEnabled() { return this.enabled; } - + /** @ejb:persistent-field */ public void setEnabled(Boolean enabled) { this.enabled = enabled; } - + /** * Set to FALSE to exclude this weblog from community areas such as the * front page and the planet page. @@ -765,26 +765,26 @@ public void setEnabled(Boolean enabled) { public Boolean getActive() { return active; } - + public void setActive(Boolean active) { this.active = active; } - + /** * Returns true if comment moderation is required by website or config. - */ - public boolean getCommentModerationRequired() { + */ + public boolean getCommentModerationRequired() { return (getModerateComments().booleanValue() || WebloggerRuntimeConfig.getBooleanProperty("users.moderation.required")); } - + /** No-op */ - public void setCommentModerationRequired(boolean modRequired) {} + public void setCommentModerationRequired(boolean modRequired) {} + - /** * The last time any visible part of this weblog was modified. - * This includes a change to weblog settings, entries, themes, templates, + * This includes a change to weblog settings, entries, themes, templates, * comments, categories, bookmarks, folders, etc. * * Pings and Referrers are explicitly not included because pings to not @@ -802,8 +802,8 @@ public Date getLastModified() { public void setLastModified(Date lastModified) { this.lastModified = lastModified; } - - + + /** * Is multi-language blog support enabled for this weblog? * @@ -820,8 +820,8 @@ public boolean isEnableMultiLang() { public void setEnableMultiLang(boolean enableMultiLang) { this.enableMultiLang = enableMultiLang; } - - + + /** * Should the default weblog view show entries from all languages? * @@ -839,9 +839,9 @@ public boolean isShowAllLangs() { public void setShowAllLangs(boolean showAllLangs) { this.showAllLangs = showAllLangs; } - - - /** + + + /** * @roller.wrapPojoMethod type="simple" */ public String getURL() { @@ -851,16 +851,16 @@ public String getURL() { public void setURL(String url) { // noop } - - + + /** * @roller.wrapPojoMethod type="simple" */ public String getAbsoluteURL() { return WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogURL(this, null, true); } - - + + /** * Comma-separated list of additional page models to be created when this * weblog is rendered. @@ -875,7 +875,7 @@ public void setPageModels(String pageModels) { this.pageModels = pageModels; } - + /** * The path under the weblog's resources to a stylesheet override. * @@ -888,8 +888,8 @@ public String getCustomStylesheetPath() { public void setCustomStylesheetPath(String customStylesheetPath) { this.customStylesheetPath = customStylesheetPath; } - - + + /** * The path under the weblog's resources to an icon image. * @@ -903,7 +903,7 @@ public void setIconPath(String iconPath) { this.iconPath = iconPath; } - + /** * A short description about the weblog. * @@ -920,8 +920,8 @@ public String getAbout() { public void setAbout(String about) { this.about = about; } - - + + /** * Get initialized plugins for use during rendering process. */ @@ -930,15 +930,15 @@ public Map getInitializedPlugins() { try { Weblogger roller = WebloggerFactory.getWeblogger(); PluginManager ppmgr = roller.getPluginManager(); - initializedPlugins = ppmgr.getWeblogEntryPlugins(this); + initializedPlugins = ppmgr.getWeblogEntryPlugins(this); } catch (Exception e) { this.log.error("ERROR: initializing plugins"); } } return initializedPlugins; } - - /** + + /** * Get weblog entry specified by anchor or null if no such entry exists. * @param anchor Weblog entry anchor * @return Weblog entry specified by anchor @@ -955,15 +955,15 @@ public WeblogEntry getWeblogEntry(String anchor) { } return entry; } - + /** * Returns categories under the default category of the weblog. - * + * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogCategory" */ public Set getWeblogCategories() { Set ret = new HashSet(); -// try { +// try { WeblogCategory category = this.getDefaultCategory(); ret = category.getWeblogCategories(); // } catch (WebloggerException e) { @@ -971,18 +971,18 @@ public Set getWeblogCategories() { // } return ret; } - - + + /** - * - * + * + * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojosWeblogCategorya" */ public Set getWeblogCategories(String categoryPath) { Set ret = new HashSet(); try { Weblogger roller = WebloggerFactory.getWeblogger(); - WeblogEntryManager wmgr = roller.getWeblogEntryManager(); + WeblogEntryManager wmgr = roller.getWeblogEntryManager(); WeblogCategory category = null; if (categoryPath != null && !categoryPath.equals("nil")) { category = wmgr.getWeblogCategoryByPath(this, categoryPath); @@ -996,10 +996,10 @@ public Set getWeblogCategories(String categoryPath) { return ret; } - + /** - * - * + * + * * @roller.wrapPojoMethod type="pojo" class="org.apache.roller.weblogger.pojosWeblogCategorya" */ public WeblogCategory getWeblogCategory(String categoryPath) { @@ -1017,8 +1017,8 @@ public WeblogCategory getWeblogCategory(String categoryPath) { } return category; } - - + + /** * Get up to 100 most recent published entries in weblog. * @param cat Category path or null for no category restriction @@ -1027,7 +1027,7 @@ public WeblogCategory getWeblogCategory(String categoryPath) { * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogEntryData" */ - public List getRecentWeblogEntries(String cat, int length) { + public List getRecentWeblogEntries(String cat, int length) { if (cat != null && "nil".equals(cat)) cat = null; if (length > 100) length = 100; List recentEntries = new ArrayList(); @@ -1035,25 +1035,25 @@ public List getRecentWeblogEntries(String cat, int length) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); recentEntries = wmgr.getWeblogEntries( - - this, + + this, null, // user null, // startDate null, // endDate cat, // cat or null - null,WeblogEntry.PUBLISHED, + null,WeblogEntry.PUBLISHED, null, // text "pubTime", // sortby null, - null, + null, 0, - length); + length); } catch (WebloggerException e) { log.error("ERROR: getting recent entries", e); } return recentEntries; } - + /** * Get up to 100 most recent published entries in weblog. * @param cat Category path or null for no category restriction @@ -1062,7 +1062,7 @@ public List getRecentWeblogEntries(String cat, int length) { * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogEntryData" */ - public List getRecentWeblogEntriesByTag(String tag, int length) { + public List getRecentWeblogEntriesByTag(String tag, int length) { if (tag != null && "nil".equals(tag)) tag = null; if (length > 100) length = 100; List recentEntries = new ArrayList(); @@ -1074,25 +1074,25 @@ public List getRecentWeblogEntriesByTag(String tag, int length) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); recentEntries = wmgr.getWeblogEntries( - - this, + + this, null, // user null, // startDate null, // endDate null, // cat or null - tags,WeblogEntry.PUBLISHED, + tags,WeblogEntry.PUBLISHED, null, // text "pubTime", // sortby null, - null, + null, 0, - length); + length); } catch (WebloggerException e) { log.error("ERROR: getting recent entries", e); } return recentEntries; - } - + } + /** * Get up to 100 most recent approved and non-spam comments in weblog. * @param length Max entries to return (1-100) @@ -1100,14 +1100,14 @@ public List getRecentWeblogEntriesByTag(String tag, int length) { * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogEntryComment" */ - public List getRecentComments(int length) { + public List getRecentComments(int length) { if (length > 100) length = 100; List recentComments = new ArrayList(); if (length < 1) return recentComments; try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); recentComments = wmgr.getComments( - + this, null, // weblog entry null, // search String @@ -1122,7 +1122,7 @@ public List getRecentComments(int length) { return recentComments; } - + /** * Get bookmark folder by name. * @param folderName Name or path of bookmark folder to be returned (null for root) @@ -1146,8 +1146,8 @@ public WeblogBookmarkFolder getBookmarkFolder(String folderName) { return ret; } - - /** + + /** * Return collection of referrers for current day. * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogReferrer" */ @@ -1157,16 +1157,16 @@ public List getTodaysReferrers() { Weblogger roller = WebloggerFactory.getWeblogger(); RefererManager rmgr = roller.getRefererManager(); return rmgr.getTodaysReferers(this); - + } catch (WebloggerException e) { log.error("PageModel getTodaysReferers()", e); } - return (referers == null ? Collections.EMPTY_LIST : referers); + return (referers == null ? Collections.EMPTY_LIST : referers); } - + /** No-op method to please XDoclet */ public void setTodaysReferrers(List ignored) {} - + /** * Get number of hits counted today. * @roller.wrapPojoMethod type="simple" @@ -1176,19 +1176,19 @@ public int getTodaysHits() { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager mgr = roller.getWeblogEntryManager(); WeblogHitCount hitCount = mgr.getHitCountByWeblog(this); - + return (hitCount != null) ? hitCount.getDailyHits() : 0; - + } catch (WebloggerException e) { log.error("Error getting weblog hit count", e); } return 0; } - + /** No-op method to please XDoclet */ public void setTodaysHits(int ignored) {} - + /** * Get a list of TagStats objects for the most popular tags * @@ -1204,10 +1204,10 @@ public List getPopularTags(int sinceDays, int length) { if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); - cal.add(Calendar.DATE, -1 * sinceDays); - startDate = cal.getTime(); - } - try { + cal.add(Calendar.DATE, -1 * sinceDays); + startDate = cal.getTime(); + } + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); results = wmgr.getPopularTags(this, startDate, 0, length); @@ -1215,7 +1215,7 @@ public List getPopularTags(int sinceDays, int length) { log.error("ERROR: fetching popular tags for weblog " + this.getName(), e); } return results; - } + } /** * @roller.wrapPojoMethod type="simple" @@ -1225,16 +1225,16 @@ public long getCommentCount() { try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager mgr = roller.getWeblogEntryManager(); - count = mgr.getCommentCount(this); + count = mgr.getCommentCount(this); } catch (WebloggerException e) { log.error("Error getting comment count for weblog " + this.getName(), e); } return count; } - + /** No-op method to please XDoclet */ public void setCommentCount(int ignored) {} - + /** * @roller.wrapPojoMethod type="simple" */ @@ -1243,7 +1243,7 @@ public long getEntryCount() { try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager mgr = roller.getWeblogEntryManager(); - count = mgr.getEntryCount(this); + count = mgr.getEntryCount(this); } catch (WebloggerException e) { log.error("Error getting entry count for weblog " + this.getName(), e); } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmark.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmark.java index 9ca5684860..f0c8577cf1 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmark.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmark.java @@ -32,11 +32,11 @@ * the your BookmarkManager implementation.

      */ public class WeblogBookmark implements Serializable, Comparable { - + public static final long serialVersionUID = 2315131256728236003L; - + private WeblogBookmarkFolder folder; - + private String id = UUIDGenerator.generateUUID(); private String name; private String description; @@ -45,13 +45,13 @@ public class WeblogBookmark implements Serializable, Comparable { private Integer priority; private String image; private String feedUrl; - + //----------------------------------------------------------- Constructors - + /** Default constructor, for use in form beans only. */ public WeblogBookmark() { } - + public WeblogBookmark( WeblogBookmarkFolder parent, String name, @@ -70,9 +70,9 @@ public WeblogBookmark( this.priority = priority; this.image = image; } - + //------------------------------------------------------------- Attributes - + /** * @roller.wrapPojoMethod type="simple" * @@ -84,12 +84,12 @@ public WeblogBookmark( public String getId() { return this.id; } - + /** @ejb:persistent-field */ public void setId(String id) { this.id = id; } - + /** * Name of bookmark. * @@ -105,12 +105,12 @@ public void setId(String id) { public String getName() { return this.name; } - + /** @ejb:persistent-field */ public void setName(String name) { this.name = name; } - + /** * Description of bookmark. * @@ -123,12 +123,12 @@ public void setName(String name) { public String getDescription() { return this.description; } - + /** @ejb:persistent-field */ public void setDescription(String description) { this.description = description; } - + /** * URL of bookmark. * @@ -141,12 +141,12 @@ public void setDescription(String description) { public String getUrl() { return this.url; } - + /** @ejb:persistent-field */ public void setUrl(String url) { this.url = url; } - + /** * Weight indicates prominence of link * @@ -163,12 +163,12 @@ public void setUrl(String url) { public java.lang.Integer getWeight() { return this.weight; } - + /** @ejb:persistent-field */ public void setWeight(java.lang.Integer weight) { this.weight = weight; } - + /** * Priority determines order of display * @@ -185,12 +185,12 @@ public void setWeight(java.lang.Integer weight) { public java.lang.Integer getPriority() { return this.priority; } - + /** @ejb:persistent-field */ public void setPriority(java.lang.Integer priority) { this.priority = priority; } - + /** * @ejb:persistent-field * @@ -201,12 +201,12 @@ public void setPriority(java.lang.Integer priority) { public String getImage() { return this.image; } - + /** @ejb:persistent-field */ public void setImage(String image) { this.image = image; } - + /** * @ejb:persistent-field * @@ -217,14 +217,14 @@ public void setImage(String image) { public String getFeedUrl() { return this.feedUrl; } - + /** @ejb:persistent-field */ public void setFeedUrl(String feedUrl) { this.feedUrl = feedUrl; } - + //---------------------------------------------------------- Relationships - + /** * @roller.wrapPojoMethod type="pojo" * @ejb:persistent-field @@ -233,14 +233,14 @@ public void setFeedUrl(String feedUrl) { public org.apache.roller.weblogger.pojos.WeblogBookmarkFolder getFolder() { return this.folder; } - + /** @ejb:persistent-field */ public void setFolder(org.apache.roller.weblogger.pojos.WeblogBookmarkFolder folder) { this.folder = folder; } - + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -249,7 +249,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof WeblogBookmark != true) return false; @@ -259,26 +259,26 @@ public boolean equals(Object other) { .append(getFolder(), o.getFolder()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) .append(getFolder()) .toHashCode(); } - - + + /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { return bookmarkComparator.compare(this, o); } - + private BookmarkComparator bookmarkComparator = new BookmarkComparator(); - + public Weblog getWebsite() { return this.folder.getWebsite(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.java index fd8f330d9a..f15f8f807a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.java @@ -41,40 +41,40 @@ * the create method in your BookmarkManager implementation.

      */ public class WeblogBookmarkFolder implements Serializable, Comparable { - + public static final long serialVersionUID = -6272468884763861944L; - + private static Log log = LogFactory.getLog(WeblogBookmarkFolder.class); - - + + // attributes private String id = UUIDGenerator.generateUUID(); private String name = null; private String description = null; private String path = null; - + // associations private Weblog website = null; private WeblogBookmarkFolder parentFolder = null; private Set childFolders = new TreeSet(); private Set bookmarks = new TreeSet(); - - + + public WeblogBookmarkFolder() { } - + public WeblogBookmarkFolder( WeblogBookmarkFolder parent, String name, String desc, Weblog website) { - + this.name = name; this.description = desc; - + this.website = website; this.parentFolder = parent; - + // calculate path if(parent == null) { this.path = "/"; @@ -84,8 +84,8 @@ public WeblogBookmarkFolder( this.path = parent.getPath() + "/" + name; } } - - + + //------------------------------------------------------- Good citizenship public String toString() { @@ -96,30 +96,30 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { - + if (other == null) return false; - + if (other instanceof WeblogBookmarkFolder) { WeblogBookmarkFolder o = (WeblogBookmarkFolder) other; return new EqualsBuilder() - .append(getPath(), o.getPath()) - //.append(getWebsite(), o.getWebsite()) + .append(getPath(), o.getPath()) + //.append(getWebsite(), o.getWebsite()) .isEquals(); } - + return false; - } - - + } + + public int hashCode() { return new HashCodeBuilder() .append(getPath()) //.append(getWebsite()) .toHashCode(); } - + /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @@ -127,27 +127,27 @@ public int compareTo(Object o) { WeblogBookmarkFolder other = (WeblogBookmarkFolder)o; return getName().compareTo(other.getName()); } - - + + /** * Database surrogate key. * * @roller.wrapPojoMethod type="simple" * * @hibernate.id column="id" - * generator-class="assigned" + * generator-class="assigned" */ public String getId() { return this.id; } - + public void setId(String id) { // Form bean workaround: empty string is never a valid id - if (id != null && id.trim().length() == 0) return; + if (id != null && id.trim().length() == 0) return; this.id = id; } - - + + /** * The short name for this folder. * @@ -163,12 +163,12 @@ public void setId(String id) { public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - - + + /** * A full description for this folder. * @@ -179,12 +179,12 @@ public void setName(String name) { public String getDescription() { return this.description; } - + public void setDescription(String description) { this.description = description; } - - + + /** * The full path to this folder in the hierarchy. * @@ -195,12 +195,12 @@ public void setDescription(String description) { public String getPath() { return this.path; } - + public void setPath(String path) { this.path = path; } - - + + /** * Get the weblog which owns this folder. * @@ -211,12 +211,12 @@ public void setPath(String path) { public Weblog getWebsite() { return website; } - + public void setWebsite( Weblog website ) { this.website = website; } - - + + /** * Return parent folder, or null if folder is root of hierarchy. * @@ -227,30 +227,30 @@ public void setWebsite( Weblog website ) { public WeblogBookmarkFolder getParent() { return this.parentFolder; } - + public void setParent(WeblogBookmarkFolder parent) { this.parentFolder = parent; } - - + + /** * Get child folders of this folder. * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogBookmarkFolder" * - * @hibernate.set lazy="true" inverse="true" cascade="delete" + * @hibernate.set lazy="true" inverse="true" cascade="delete" * @hibernate.collection-key column="parentid" * @hibernate.collection-one-to-many class="org.apache.roller.weblogger.pojos.WeblogBookmarkFolder" */ public Set getFolders() { return this.childFolders; } - + private void setFolders(Set folders) { this.childFolders = folders; } - - + + /** * Get bookmarks contained in this folder. * @@ -263,45 +263,45 @@ private void setFolders(Set folders) { public Set getBookmarks() { return this.bookmarks; } - + // this is private to force the use of add/remove bookmark methods. private void setBookmarks(Set bookmarks) { this.bookmarks = bookmarks; } - - + + /** * Add a folder as a child of this folder. */ public void addFolder(WeblogBookmarkFolder folder) { - + // make sure folder is not null if(folder == null || folder.getName() == null) { throw new IllegalArgumentException("Folder cannot be null and must have a valid name"); } - + // make sure we don't already have a folder with that name if(this.hasFolder(folder.getName())) { throw new IllegalArgumentException("Duplicate folder name '"+folder.getName()+"'"); } - + // set ourselves as the parent of the folder folder.setParent(this); - + // add it to our list of child folder getFolders().add(folder); } - - - /** + + + /** * Add a bookmark to this folder. */ public void addBookmark(WeblogBookmark bookmark) throws WebloggerException { bookmark.setFolder(this); getBookmarks().add(bookmark); } - - + + /** * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogBookmark" * @@ -311,8 +311,8 @@ public List retrieveBookmarks(boolean subfolders) throws WebloggerException { BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); return bmgr.getBookmarks(this, subfolders); } - - + + /** * Does this folder have a child folder with the specified name? * @@ -330,15 +330,15 @@ public boolean hasFolder(String name) { } return false; } - - + + /** * Is this folder a descendent of the other folder? * * @roller.wrapPojoMethod type="simple" */ public boolean descendentOf(WeblogBookmarkFolder ancestor) { - + // if this is a root node then we can't be a descendent if(getParent() == null) { return false; @@ -347,14 +347,14 @@ public boolean descendentOf(WeblogBookmarkFolder ancestor) { return this.path.startsWith(ancestor.getPath()); } } - - + + // convenience method for updating the folder name, which triggers a path tree rebuild public void updateName(String newName) throws WebloggerException { - + // update name setName(newName); - + // calculate path if(getParent() == null) { setPath("/"); @@ -363,25 +363,25 @@ public void updateName(String newName) throws WebloggerException { } else { setPath(getParent().getPath() + "/" + getName()); } - + // update path tree for all children updatePathTree(this); } - - + + // update the path tree for a given folder - public static void updatePathTree(WeblogBookmarkFolder folder) + public static void updatePathTree(WeblogBookmarkFolder folder) throws WebloggerException { - + log.debug("Updating path tree for folder "+folder.getPath()); - + WeblogBookmarkFolder childFolder = null; Iterator childFolders = folder.getFolders().iterator(); while(childFolders.hasNext()) { childFolder = (WeblogBookmarkFolder) childFolders.next(); - + log.debug("OLD child folder path was "+childFolder.getPath()); - + // update path and save if("/".equals(folder.getPath())) { childFolder.setPath("/" + childFolder.getName()); @@ -389,12 +389,12 @@ public static void updatePathTree(WeblogBookmarkFolder folder) childFolder.setPath(folder.getPath() + "/" + childFolder.getName()); } WebloggerFactory.getWeblogger().getBookmarkManager().saveFolder(childFolder); - + log.debug("NEW child folder path is "+ childFolder.getPath()); - + // then make recursive call to update this folders children updatePathTree(childFolder); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategory.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategory.java index 4c3aa04992..892a3ba768 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategory.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategory.java @@ -35,43 +35,43 @@ /** * Weblog Category. - * + * * @hibernate.cache usage="read-write" * @hibernate.class lazy="true" table="weblogcategory" */ public class WeblogCategory implements Serializable, Comparable { - + public static final long serialVersionUID = 1435782148712018954L; - + private static Log log = LogFactory.getLog(WeblogCategory.class); - + // attributes private String id = UUIDGenerator.generateUUID(); private String name = null; private String description = null; private String image = null; private String path = null; - + // associations private Weblog website = null; private WeblogCategory parentCategory = null; private Set childCategories = new HashSet(); - - + + public WeblogCategory() { } - + public WeblogCategory( Weblog website, WeblogCategory parent, String name, String description, String image) { - + this.name = name; this.description = description; this.image = image; - + this.website = website; this.parentCategory = parent; @@ -84,8 +84,8 @@ public WeblogCategory( this.path = parent.getPath() + "/" + name; } } - - + + //------------------------------------------------------- Good citizenship public String toString() { @@ -96,28 +96,28 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { - + if (other == null) return false; - + if (other instanceof WeblogCategory) { WeblogCategory o = (WeblogCategory)other; return new EqualsBuilder() - .append(getPath(), o.getPath()) - //.append(getWebsite(), o.getWebsite()) + .append(getPath(), o.getPath()) + //.append(getWebsite(), o.getWebsite()) .isEquals(); - } + } return false; } - + public int hashCode() { return new HashCodeBuilder() .append(getPath()) //.append(getWebsite()) .toHashCode(); } - + /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @@ -125,22 +125,22 @@ public int compareTo(Object o) { WeblogCategory other = (WeblogCategory)o; return getName().compareTo(other.getName()); } - - + + /** * Database surrogate key. * - * @hibernate.id column="id" generator-class="assigned" + * @hibernate.id column="id" generator-class="assigned" */ public String getId() { return this.id; } - + public void setId(String id) { this.id = id; } - - + + /** * The display name for this category. * @@ -149,12 +149,12 @@ public void setId(String id) { public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - - + + /** * A full description for this category. * @@ -163,12 +163,12 @@ public void setName(String name) { public String getDescription() { return this.description; } - + public void setDescription(String description) { this.description = description; } - - + + /** * An image icon to represent this category. * @@ -177,12 +177,12 @@ public void setDescription(String description) { public String getImage() { return this.image; } - + public void setImage(String image) { this.image = image; } - - + + /** * The full path to this category in the hierarchy. * @@ -191,12 +191,12 @@ public void setImage(String image) { public String getPath() { return this.path; } - + public void setPath(String path) { this.path = path; } - - + + /** * Get the weblog which owns this category. * @@ -205,12 +205,12 @@ public void setPath(String path) { public Weblog getWebsite() { return website; } - + public void setWebsite(Weblog website) { this.website = website; } - - + + /** * Get parent category, or null if category is root of hierarchy. * @@ -219,15 +219,15 @@ public void setWebsite(Weblog website) { public WeblogCategory getParent() { return this.parentCategory; } - + public void setParent(WeblogCategory parent) { this.parentCategory = parent; } - - + + /** * Get child categories of this category. - * + * * @hibernate.collection-key column="parentid" * @hibernate.collection-one-to-many class="org.apache.roller.weblogger.pojos.WeblogCategory" * @hibernate.set lazy="true" inverse="true" cascade="delete" order-by="name" @@ -235,12 +235,12 @@ public void setParent(WeblogCategory parent) { public Set getWeblogCategories() { return this.childCategories; } - + private void setWeblogCategories(Set cats) { this.childCategories = cats; } - - + + /** * Retrieve all weblog entries in this category and, optionally, include * weblog entries all sub-categories. @@ -253,31 +253,31 @@ public List retrieveWeblogEntries(boolean subcats) throws WebloggerException { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); return wmgr.getWeblogEntries(this, subcats); } - - + + /** * Add a category as a child of this category. */ public void addCategory(WeblogCategory category) { - + // make sure category is not null if(category == null || category.getName() == null) { throw new IllegalArgumentException("Category cannot be null and must have a valid name"); } - + // make sure we don't already have a category with that name if(this.hasCategory(category.getName())) { throw new IllegalArgumentException("Duplicate category name '"+category.getName()+"'"); } - + // set ourselves as the parent of the category category.setParent(this); - + // add it to our list of child categories getWeblogCategories().add(category); } - - + + /** * Does this category have a child category with the specified name? * @@ -295,13 +295,13 @@ public boolean hasCategory(String name) { } return false; } - - + + /** * Is this category a descendent of the other category? */ public boolean descendentOf(WeblogCategory ancestor) { - + // if this is a root node then we can't be a descendent if(getParent() == null) { return false; @@ -310,8 +310,8 @@ public boolean descendentOf(WeblogCategory ancestor) { return this.path.startsWith(ancestor.getPath()); } } - - + + /** * Determine if category is in use. Returns true if any weblog entries * use this category or any of it's subcategories. @@ -323,14 +323,14 @@ public boolean isInUse() { throw new RuntimeException(e); } } - - + + // convenience method for updating the category name, which triggers a path tree rebuild public void updateName(String newName) throws WebloggerException { - + // update name setName(newName); - + // calculate path if(getParent() == null) { setPath("/"); @@ -339,25 +339,25 @@ public void updateName(String newName) throws WebloggerException { } else { setPath(getParent().getPath() + "/" + getName()); } - + // update path tree for all children updatePathTree(this); } - - + + // updates the paths of all descendents of the given category - public static void updatePathTree(WeblogCategory cat) + public static void updatePathTree(WeblogCategory cat) throws WebloggerException { - + log.debug("Updating path tree for category "+cat.getPath()); - + WeblogCategory childCat = null; Iterator childCats = cat.getWeblogCategories().iterator(); while(childCats.hasNext()) { childCat = (WeblogCategory) childCats.next(); - + log.debug("OLD child category path was "+childCat.getPath()); - + // update path and save if("/".equals(cat.getPath())) { childCat.setPath("/" + childCat.getName()); @@ -365,12 +365,12 @@ public static void updatePathTree(WeblogCategory cat) childCat.setPath(cat.getPath() + "/" + childCat.getName()); } WebloggerFactory.getWeblogger().getWeblogEntryManager().saveWeblogCategory(childCat); - + log.debug("NEW child category path is "+ childCat.getPath()); - + // then make recursive call to update this cats children updatePathTree(childCat); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategoryPathComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategoryPathComparator.java index ab9afb6846..272e5965f2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategoryPathComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogCategoryPathComparator.java @@ -25,11 +25,11 @@ * Compare weblog categories by path. */ public class WeblogCategoryPathComparator implements Comparator { - + public int compare(Object o1, Object o2) { WeblogCategory f1 = (WeblogCategory)o1; WeblogCategory f2 = (WeblogCategory)o2; return f1.getPath().compareTo(f2.getPath()); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntry.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntry.java index 816ca82c01..e31104c0d5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntry.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntry.java @@ -67,14 +67,14 @@ public class WeblogEntry implements Serializable { private static Log mLogger = LogFactory.getFactory().getInstance(WeblogEntry.class); - + public static final long serialVersionUID = 2341505386843044125L; - + public static final String DRAFT = "DRAFT"; public static final String PUBLISHED = "PUBLISHED"; public static final String PENDING = "PENDING"; public static final String SCHEDULED = "SCHEDULED"; - + // Simple properies private String id = UUIDGenerator.generateUUID(); private String title = null; @@ -93,24 +93,24 @@ public class WeblogEntry implements Serializable { private Boolean pinnedToMain = Boolean.FALSE; private String status = DRAFT; private String locale = null; - private String creatorUserName = null; + private String creatorUserName = null; // Associated objects private Weblog website = null; private WeblogCategory category = null; - + // Collection of name/value entry attributes private Set attSet = new TreeSet(); - + private Set tagSet = new HashSet(); private Set removedTags = new HashSet(); private Set addedTags = new HashSet(); - + //----------------------------------------------------------- Construction - + public WeblogEntry() { } - + public WeblogEntry( String id, WeblogCategory category, @@ -135,18 +135,18 @@ public WeblogEntry( this.updateTime = updateTime; this.status = status; } - + public WeblogEntry(WeblogEntry otherData) { this.setData(otherData); } - + //---------------------------------------------------------- Initializaion - + /** * Set bean properties based on other bean. */ public void setData(WeblogEntry other) { - + this.setId(other.getId()); this.setCategory(other.getCategory()); this.setWebsite(other.getWebsite()); @@ -165,7 +165,7 @@ public void setData(WeblogEntry other) { this.setPinnedToMain(other.getPinnedToMain()); this.setLocale(other.getLocale()); } - + //------------------------------------------------------- Good citizenship public String toString() { @@ -184,36 +184,36 @@ public boolean equals(Object other) { if (other instanceof WeblogEntry != true) return false; WeblogEntry o = (WeblogEntry)other; return new EqualsBuilder() - .append(getAnchor(), o.getAnchor()) - .append(getWebsite(), o.getWebsite()) + .append(getAnchor(), o.getAnchor()) + .append(getWebsite(), o.getWebsite()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getAnchor()) .append(getWebsite()) .toHashCode(); } - + //------------------------------------------------------ Simple properties - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field - * @hibernate.id column="id" generator-class="assigned" + * @hibernate.id column="id" generator-class="assigned" */ public String getId() { return this.id; } - + /** @ejb:persistent-field */ public void setId(String id) { // Form bean workaround: empty string is never a valid id - if (id != null && id.trim().length() == 0) return; + if (id != null && id.trim().length() == 0) return; this.id = id; } - + /** * @roller.wrapPojoMethod type="pojo" * @ejb:persistent-field @@ -222,16 +222,16 @@ public void setId(String id) { public WeblogCategory getCategory() { return this.category; } - + /** @ejb:persistent-field */ public void setCategory(WeblogCategory category) { this.category = category; } - + /** * Return collection of WeblogCategory objects of this entry. * Added for symetry with PlanetEntryData object. - * + * * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogCategory" */ public List getCategories() { @@ -239,12 +239,12 @@ public List getCategories() { cats.add(getCategory()); return cats; } - + /** No-op method to please XDoclet */ public void setCategories(List cats) { // no-op } - + /** * @roller.wrapPojoMethod type="pojo" * @ejb:persistent-field @@ -253,12 +253,12 @@ public void setCategories(List cats) { public Weblog getWebsite() { return this.website; } - + /** @ejb:persistent-field */ public void setWebsite(Weblog website) { this.website = website; } - + /** * @roller.wrapPojoMethod type="simple" */ @@ -269,16 +269,16 @@ public User getCreator() { mLogger.error("ERROR fetching user object for username: " + getCreatorUserName(), e); } return null; - } - + } + public String getCreatorUserName() { return creatorUserName; } public void setCreatorUserName(String creatorUserName) { this.creatorUserName = creatorUserName; - } - + } + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -287,12 +287,12 @@ public void setCreatorUserName(String creatorUserName) { public String getTitle() { return this.title; } - + /** @ejb:persistent-field */ public void setTitle(String title) { this.title = title; } - + /** * Get summary for weblog entry (maps to RSS description and Atom summary). * @roller.wrapPojoMethod type="simple" @@ -302,7 +302,7 @@ public void setTitle(String title) { public String getSummary() { return summary; } - + /** * Set summary for weblog entry (maps to RSS description and Atom summary). * @ejb:persistent-field @@ -310,7 +310,7 @@ public String getSummary() { public void setSummary(String summary) { this.summary = summary; } - + /** * Get content text for weblog entry (maps to RSS content:encoded and Atom content). * @roller.wrapPojoMethod type="simple" @@ -320,7 +320,7 @@ public void setSummary(String summary) { public String getText() { return this.text; } - + /** * Set content text for weblog entry (maps to RSS content:encoded and Atom content). * @ejb:persistent-field @@ -328,7 +328,7 @@ public String getText() { public void setText(String text) { this.text = text; } - + /** * Get content type (text, html, xhtml or a MIME content type) * @roller.wrapPojoMethod type="simple" @@ -338,7 +338,7 @@ public void setText(String text) { public String getContentType() { return contentType; } - + /** * Set content type (text, html, xhtml or a MIME content type) * @ejb:persistent-field @@ -346,7 +346,7 @@ public String getContentType() { public void setContentType(String contentType) { this.contentType = contentType; } - + /** * Get URL for out-of-line content. * @roller.wrapPojoMethod type="simple" @@ -356,7 +356,7 @@ public void setContentType(String contentType) { public String getContentSrc() { return contentSrc; } - + /** * Set URL for out-of-line content. * @ejb:persistent-field @@ -364,7 +364,7 @@ public String getContentSrc() { public void setContentSrc(String contentSrc) { this.contentSrc = contentSrc; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -373,12 +373,12 @@ public void setContentSrc(String contentSrc) { public String getAnchor() { return this.anchor; } - + /** @ejb:persistent-field */ public void setAnchor(String anchor) { this.anchor = anchor; } - + //------------------------------------------------------------------------- /** * Map attributes as set because XDoclet 1.2b4 map support is broken. @@ -396,8 +396,8 @@ public Set getEntryAttributes() { public void setEntryAttributes(Set atts) { this.attSet = atts; } - - + + /** * Would be named getEntryAttribute, but that would set off XDoclet * @@ -412,13 +412,13 @@ public String findEntryAttribute(String name) { } return null; } - + public void putEntryAttribute(String name, String value) throws Exception { WeblogEntryAttribute att = null; for (Iterator it = getEntryAttributes().iterator(); it.hasNext(); ) { WeblogEntryAttribute o = (WeblogEntryAttribute) it.next(); if (name.equals(o.getName())) { - att = o; + att = o; break; } } @@ -432,9 +432,9 @@ public void putEntryAttribute(String name, String value) throws Exception { att.setValue(value); } } - + //------------------------------------------------------------------------- - + /** *

      Publish time is the time that an entry is to be (or was) made available * for viewing by newsfeed readers and visitors to the Roller site.

      @@ -453,12 +453,12 @@ public void putEntryAttribute(String name, String value) throws Exception { public Timestamp getPubTime() { return this.pubTime; } - + /** @ejb:persistent-field */ public void setPubTime(Timestamp pubTime) { this.pubTime = pubTime; } - + /** *

      Update time is the last time that an weblog entry was saved in the * Roller weblog editor or via web services API (XML-RPC or Atom).

      @@ -477,12 +477,12 @@ public void setPubTime(Timestamp pubTime) { public Timestamp getUpdateTime() { return this.updateTime; } - + /** @ejb:persistent-field */ public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } - + /** * @roller.wrapPojoMethod type="simple" * @ejb:persistent-field @@ -491,12 +491,12 @@ public void setUpdateTime(Timestamp updateTime) { public String getStatus() { return this.status; } - + /** @ejb:persistent-field */ public void setStatus(String status) { this.status = status; } - + /** * Some weblog entries are about one specific link. * @return Returns the link. @@ -508,7 +508,7 @@ public void setStatus(String status) { public String getLink() { return link; } - + /** * @ejb:persistent-field * @param link The link to set. @@ -516,7 +516,7 @@ public String getLink() { public void setLink(String link) { this.link = link; } - + /** * Comma-delimited list of this entry's Plugins. * @@ -527,13 +527,13 @@ public void setLink(String link) { public String getPlugins() { return plugins; } - + /** @ejb:persistent-field */ public void setPlugins(String string) { plugins = string; } - - + + /** * True if comments are allowed on this weblog entry. * @@ -551,7 +551,7 @@ public Boolean getAllowComments() { public void setAllowComments(Boolean allowComments) { this.allowComments = allowComments; } - + /** * Number of days after pubTime that comments should be allowed, or 0 for no limit. * @@ -569,7 +569,7 @@ public Integer getCommentDays() { public void setCommentDays(Integer commentDays) { this.commentDays = commentDays; } - + /** * True if this entry should be rendered right to left. * @@ -587,7 +587,7 @@ public Boolean getRightToLeft() { public void setRightToLeft(Boolean rightToLeft) { this.rightToLeft = rightToLeft; } - + /** * True if story should be pinned to the top of the Roller site main blog. * @return Returns the pinned. @@ -608,8 +608,8 @@ public Boolean getPinnedToMain() { public void setPinnedToMain(Boolean pinnedToMain) { this.pinnedToMain = pinnedToMain; } - - + + /** * The locale string that defines the i18n approach for this entry. * @@ -620,15 +620,15 @@ public void setPinnedToMain(Boolean pinnedToMain) { public String getLocale() { return locale; } - - + + public void setLocale(String locale) { this.locale = locale; } - + /** - * @ejb:persistent-field - * + * @ejb:persistent-field + * * @hibernate.set lazy="true" order-by="name" inverse="true" cascade="all" * @hibernate.collection-key column="entryid" * @hibernate.collection-one-to-many class="org.apache.roller.weblogger.pojos.WeblogEntryTag" @@ -637,17 +637,17 @@ public Set getTags() { return tagSet; } - + private void setTags(Set tagSet) throws WebloggerException { this.tagSet = tagSet; this.removedTags = new HashSet(); this.addedTags = new HashSet(); - } - + } + /** * Roller lowercases all tags based on locale because there's not a 1:1 mapping - * between uppercase/lowercase characters across all languages. + * between uppercase/lowercase characters across all languages. * @param name * @throws WebloggerException */ @@ -656,7 +656,7 @@ public void addTag(String name) throws WebloggerException { name = Utilities.normalizeTag(name, localeObject); if(name.length() == 0) return; - + for (Iterator it = getTags().iterator(); it.hasNext();) { WeblogEntryTag tag = (WeblogEntryTag) it.next(); if (tag.getName().equals(name)) @@ -670,7 +670,7 @@ public void addTag(String name) throws WebloggerException { tag.setWeblogEntry(this); tag.setTime(getUpdateTime()); tagSet.add(tag); - + addedTags.add(name); } @@ -681,25 +681,25 @@ public void onRemoveTag(String name) throws WebloggerException { public Set getAddedTags() { return addedTags; } - + public Set getRemovedTags() { return removedTags; } public void updateTags(List updatedTags) throws WebloggerException { - + if(updatedTags == null) { return; } - + HashSet newTags = new HashSet(updatedTags.size()); Locale localeObject = getWebsite() != null ? getWebsite().getLocaleInstance() : Locale.getDefault(); - + for(Iterator it = updatedTags.iterator(); it.hasNext();) { String name = it.next(); newTags.add(Utilities.normalizeTag(name, localeObject)); } - + HashSet removeTags = new HashSet(); // remove old ones no longer passed. @@ -716,12 +716,12 @@ public void updateTags(List updatedTags) throws WebloggerException { for (Iterator it = removeTags.iterator(); it.hasNext();) { weblogManager.removeWeblogEntryTag((String) it.next(), this); } - + for (Iterator it = newTags.iterator(); it.hasNext();) { addTag((String) it.next()); } } - + /** * @roller.wrapPojoMethod type="simple" */ @@ -744,13 +744,13 @@ public void setTagsAsString(String tags) throws WebloggerException { } updateTags(Utilities.splitStringAsTags(tags)); - } + } // ------------------------------------------------------------------------ - + /** * True if comments are still allowed on this entry considering the - * allowComments and commentDays fields as well as the website and + * allowComments and commentDays fields as well as the website and * site-wide configs. * * @roller.wrapPojoMethod type="simple" @@ -775,7 +775,7 @@ public boolean getCommentsStillAllowed() { if(pubTime == null) { pubTime = getUpdateTime(); } - + Calendar expireCal = Calendar.getInstance( getWebsite().getLocaleInstance()); expireCal.setTime(pubTime); @@ -791,10 +791,10 @@ public boolean getCommentsStillAllowed() { public void setCommentsStillAllowed(boolean ignored) { // no-op } - - + + //------------------------------------------------------------------------ - + /** * Format the publish time of this weblog entry using the specified pattern. * See java.text.SimpleDateFormat for more information on this format. @@ -807,17 +807,17 @@ public String formatPubTime(String pattern) { try { SimpleDateFormat format = new SimpleDateFormat(pattern, this.getWebsite().getLocaleInstance()); - + return format.format(getPubTime()); } catch (RuntimeException e) { mLogger.error("Unexpected exception", e); } - + return "ERROR: formatting date"; } - + //------------------------------------------------------------------------ - + /** * Format the update time of this weblog entry using the specified pattern. * See java.text.SimpleDateFormat for more information on this format. @@ -829,24 +829,24 @@ public String formatPubTime(String pattern) { public String formatUpdateTime(String pattern) { try { SimpleDateFormat format = new SimpleDateFormat(pattern); - + return format.format(getUpdateTime()); } catch (RuntimeException e) { mLogger.error("Unexpected exception", e); } - + return "ERROR: formatting date"; } - + //------------------------------------------------------------------------ - + /** * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogEntryComment" */ public List getComments() { return getComments(true, true); } - + /** * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.WeblogEntryComment" * @@ -869,22 +869,22 @@ public List getComments(boolean ignoreSpam, boolean approvedOnly) { } catch (WebloggerException alreadyLogged) {} return list; } - + /** * @roller.wrapPojoMethod type="simple" - */ + */ public int getCommentCount() { List comments = getComments(true, true); return comments.size(); } - + /** No-op to please XDoclet */ public void setCommentCount(int ignored) { // no-op } - + //------------------------------------------------------------------------ - + /** * @roller.wrapPojoMethod type="pojo-collection" class="org.apache.roller.weblogger.pojos.RefererData" */ @@ -897,32 +897,32 @@ public List getReferers() { } return referers; } - + //------------------------------------------------------------------------ - + /** * Returns absolute entry permalink. */ public String getPermalink() { return WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogEntryURL(getWebsite(), null, anchor, true); } - + /** * Returns entry permalink, relative to Roller context. * @deprecated Use getPermalink() instead. * @roller.wrapPojoMethod type="simple" */ public String getPermaLink() { - String lAnchor = this.getAnchor(); + String lAnchor = this.getAnchor(); try { lAnchor = URLEncoder.encode(anchor, "UTF-8"); } catch (UnsupportedEncodingException e) { // go with the "no encoding" version - } + } Weblog website = this.getWebsite(); return "/" + getWebsite().getHandle() + "/entry/" + lAnchor; } - + /** * Get relative URL to comments page. * @roller.wrapPojoMethod type="simple" @@ -931,14 +931,14 @@ public String getPermaLink() { public String getCommentsLink() { return getPermaLink() + "#comments"; } - - /** - * to please XDoclet + + /** + * to please XDoclet * @deprecated Use commentLink() instead */ public void setCommentsLink(String ignored) {} - - + + /** * Return the Title of this post, or the first 255 characters of the * entry's text. @@ -952,7 +952,7 @@ public String getDisplayTitle() { } return Utilities.removeHTML(getTitle()); } - + /** * Return RSS 09x style description (escaped HTML version of entry text) * @@ -961,7 +961,7 @@ public String getDisplayTitle() { public String getRss09xDescription() { return getRss09xDescription(-1); } - + /** * Return RSS 09x style description (escaped HTML version of entry text) * @@ -974,27 +974,27 @@ public String getRss09xDescription(int maxLength) { } return ret; } - + /** Create anchor for weblog entry, based on title or text */ protected String createAnchor() throws WebloggerException { return WebloggerFactory.getWeblogger().getWeblogEntryManager().createAnchor(this); } - + /** Create anchor for weblog entry, based on title or text */ public String createAnchorBase() { - + // Use title (minus non-alphanumeric characters) String base = null; if (!StringUtils.isEmpty(getTitle())) { - base = Utilities.replaceNonAlphanumeric(getTitle(), ' ').trim(); + base = Utilities.replaceNonAlphanumeric(getTitle(), ' ').trim(); } // If we still have no base, then try text (minus non-alphanumerics) if (StringUtils.isEmpty(base) && !StringUtils.isEmpty(getText())) { - base = Utilities.replaceNonAlphanumeric(getText(), ' ').trim(); + base = Utilities.replaceNonAlphanumeric(getText(), ' ').trim(); } - + if (!StringUtils.isEmpty(base)) { - + // Use only the first 4 words StringTokenizer toker = new StringTokenizer(base); String tmp = null; @@ -1012,20 +1012,20 @@ public String createAnchorBase() { else { base = DateUtil.format8chars(getPubTime()); } - + return base; } - + /** * A no-op. TODO: fix formbean generation so this is not needed. */ public void setPermalink(String string) {} - + /** * A no-op. TODO: fix formbean generation so this is not needed. */ public void setPermaLink(String string) {} - + /** * A no-op. * TODO: fix formbean generation so this is not needed. @@ -1033,7 +1033,7 @@ public void setPermaLink(String string) {} */ public void setDisplayTitle(String string) { } - + /** * A no-op. * TODO: fix formbean generation so this is not needed. @@ -1041,8 +1041,8 @@ public void setDisplayTitle(String string) { */ public void setRss09xDescription(String string) { } - - + + /** * Convenience method to transform mPlugins to a List * @@ -1054,8 +1054,8 @@ public List getPluginsList() { return Arrays.asList( StringUtils.split(plugins, ",") ); } return new ArrayList(); - } - + } + /** Convenience method for checking status */ public boolean isDraft() { return status.equals(DRAFT); @@ -1063,7 +1063,7 @@ public boolean isDraft() { /** no-op: needed only to satisfy XDoclet, use setStatus() instead */ public void setDraft(boolean value) { } - + /** Convenience method for checking status */ public boolean isPending() { return status.equals(PENDING); @@ -1071,7 +1071,7 @@ public boolean isPending() { /** no-op: needed only to satisfy XDoclet, use setStatus() instead */ public void setPending(boolean value) { } - + /** Convenience method for checking status */ public boolean isPublished() { return status.equals(PUBLISHED); @@ -1079,7 +1079,7 @@ public boolean isPublished() { /** no-op: needed only to satisfy XDoclet, use setStatus() instead */ public void setPublished(boolean value) { } - + /** * Get entry text, transformed by plugins enabled for entry. * @roller.wrapPojoMethod type="simple" @@ -1093,7 +1093,7 @@ public String getTransformedText() { public void setTransformedText(String t) { // no-op } - + /** * Get entry summary, transformed by plugins enabled for entry. * @roller.wrapPojoMethod type="simple" @@ -1106,28 +1106,28 @@ public String getTransformedSummary() { */ public void setTransformedSummary(String t) { // no-op - } - + } + /** * Determine if the specified user has permissions to edit this entry. */ public boolean hasWritePermissions(User user) throws WebloggerException { - + // global admins can hack whatever they want - GlobalPermission adminPerm = + GlobalPermission adminPerm = new GlobalPermission(Collections.singletonList(GlobalPermission.ADMIN)); boolean hasAdmin = WebloggerFactory.getWeblogger().getUserManager() - .checkPermission(adminPerm, user); + .checkPermission(adminPerm, user); if (hasAdmin) { return true; } - + WeblogPermission perm = null; try { // if user is an author then post status defaults to PUBLISHED, otherwise PENDING UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); perm = umgr.getWeblogPermission(getWebsite(), user); - + } catch (WebloggerException ex) { // security interceptor should ensure this never happens mLogger.error("ERROR retrieving user's permission", ex); @@ -1135,14 +1135,14 @@ public boolean hasWritePermissions(User user) throws WebloggerException { boolean author = perm.hasAction(WeblogPermission.POST) || perm.hasAction(WeblogPermission.ADMIN); boolean limited = !author && perm.hasAction(WeblogPermission.EDIT_DRAFT); - + if (author || (limited && isDraft()) || (limited && isPending())) { return true; } - + return false; } - + /** * Transform string based on plugins enabled for this weblog entry. */ @@ -1152,10 +1152,10 @@ private String render(String str) { Map plugins = this.website.getInitializedPlugins(); if (str != null && plugins != null) { List entryPlugins = getPluginsList(); - + // if no Entry plugins, don't bother looping. if (entryPlugins != null && !entryPlugins.isEmpty()) { - + // now loop over mPagePlugins, matching // against Entry plugins (by name): // where a match is found render Plugin. @@ -1172,11 +1172,11 @@ private String render(String str) { } } } - } + } return ret; } - - + + /** * Get the right transformed display content depending on the situation. * @@ -1188,12 +1188,12 @@ private String render(String str) { * @roller.wrapPojoMethod type="simple" */ public String displayContent(String readMoreLink) { - + String displayContent = null; - - if(readMoreLink == null || readMoreLink.trim().length() < 1 || + + if(readMoreLink == null || readMoreLink.trim().length() < 1 || "nil".equals(readMoreLink)) { - + // no readMore link means permalink, so prefer text over summary if(StringUtils.isNotEmpty(this.getText())) { displayContent = this.getTransformedText(); @@ -1209,34 +1209,34 @@ public String displayContent(String readMoreLink) { // add read more List args = new ArrayList(); args.add(readMoreLink); - + // TODO: we need a more appropriate way to get the view locale here String readMore = I18nMessages.getMessages(getWebsite().getLocaleInstance()).getString("macro.weblog.readMoreLink", args); - + displayContent += readMore; } } else { displayContent = this.getTransformedText(); } } - + return displayContent; } - - + + /** * Get the right transformed display content. * * @roller.wrapPojoMethod type="simple" */ - public String getDisplayContent() { + public String getDisplayContent() { return displayContent(null); } - - + + /** No-op method to please XDoclet */ public void setDisplayContent(String ignored) {} - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.java index 2197bc30fa..27c09ce4d4 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.java @@ -27,55 +27,55 @@ * Weblog entry attribute. */ public class WeblogEntryAttribute implements Comparable { - + private String id = UUIDGenerator.generateUUID(); private WeblogEntry entry; private String name; private String value; - - + + public WeblogEntryAttribute() { } - - + + public String getId() { return this.id; } - - public void setId(String id) { + + public void setId(String id) { this.id = id; } - - + + public WeblogEntry getEntry() { return entry; } - + public void setEntry(WeblogEntry entry) { this.entry = entry; } - - + + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - - + + public String getValue() { return value; } - + public void setValue(String value) { this.value = value; } - - + + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -85,7 +85,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof WeblogEntryAttribute != true) return false; @@ -95,17 +95,17 @@ public boolean equals(Object other) { .append(getEntry(), o.getEntry()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) .append(getEntry()) .toHashCode(); } - + public int compareTo(Object o) { WeblogEntryAttribute att = (WeblogEntryAttribute)o; return getName().compareTo(att.getName()); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryComment.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryComment.java index b9df5e8e92..800792d716 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryComment.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryComment.java @@ -29,15 +29,15 @@ * WeblogEntry comment bean. */ public class WeblogEntryComment implements Serializable { - + public static final long serialVersionUID = -6668122596726478462L; - + // status options public static final String APPROVED = "APPROVED"; public static final String DISAPPROVED = "DISAPPROVED"; public static final String SPAM = "SPAM"; public static final String PENDING = "PENDING"; - + // attributes private String id = UUIDGenerator.generateUUID(); private String name = null; @@ -53,119 +53,119 @@ public class WeblogEntryComment implements Serializable { private String plugins = null; private String contentType = "text/plain"; - + // associations private WeblogEntry weblogEntry = null; - - + + public WeblogEntryComment() {} - - + + /** - * Database ID of comment + * Database ID of comment */ public String getId() { return this.id; } - + /** * Database ID of comment */ public void setId(String id) { this.id = id; } - - + + /** * Weblog entry associated with comment. */ public WeblogEntry getWeblogEntry() { return weblogEntry; } - + /** * Weblog entry assocaited with comment */ public void setWeblogEntry(WeblogEntry entry) { weblogEntry = entry; } - - + + /** * Name of person who wrote comment. */ public String getName() { return this.name; } - + /** * Name of person who wrote comment. */ public void setName(String name) { this.name = name; } - - + + /** * Email of person who wrote comment. */ public String getEmail() { return this.email; } - + /** * Email of person who wrote comment. */ public void setEmail(String email) { this.email = email; } - - + + /** * URL of person who wrote comment. */ public String getUrl() { return this.url; } - + /** * URL of person who wrote comment. */ public void setUrl(String url) { this.url = url; } - - + + /** * Content of comment. */ public String getContent() { return this.content; } - + /** * Content of comment. */ public void setContent(String content) { this.content = content; } - - + + /** * Time that comment was posted. */ public Timestamp getPostTime() { return this.postTime; } - + /** * Time that comment was posted. */ public void setPostTime(Timestamp postTime) { this.postTime = postTime; } - - + + /** * Status of the comment, i.e. APPROVED, SPAM, PENDING, etc. */ @@ -179,8 +179,8 @@ public String getStatus() { public void setStatus(String status) { this.status = status; } - - + + /** * True if person who wrote comment wishes to be notified of new comments * on the same weblog entry. @@ -188,7 +188,7 @@ public void setStatus(String status) { public Boolean getNotify() { return this.notify; } - + /** * True if person who wrote comment wishes to be notified of new comments * on the same weblog entry. @@ -196,107 +196,107 @@ public Boolean getNotify() { public void setNotify(Boolean notify) { this.notify = notify; } - - + + /** * Host name or IP of person who wrote comment. */ public String getRemoteHost() { return this.remoteHost; } - + /** * Host name or IP of person who wrote comment. */ public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } - - + + /** * HTTP referrer from comment post request */ public String getReferrer() { return referrer; } - + /** * HTTP referrer from comment post request */ public void setReferrer(String referrer) { this.referrer = referrer; } - - + + /** * HTTP user-agent from comment post request */ public String getUserAgent() { return userAgent; } - + /** * HTTP user-agent from comment post request */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } - - + + /** * Comma separated list of comment plugins to apply. */ public String getPlugins() { return plugins; } - + /** * Comma separated list of comment plugins to apply. */ public void setPlugins(String plugins) { this.plugins = plugins; } - - + + /** * The content-type of the comment. */ public String getContentType() { return contentType; } - + /** * The content-type of the comment. */ public void setContentType(String contentType) { this.contentType = contentType; } - - + + /** * Indicates that weblog owner considers this comment to be spam. */ public Boolean getSpam() { return new Boolean(SPAM.equals(this.status)); } - - + + /** * True if comment has is pending moderator approval. */ public Boolean getPending() { return new Boolean(PENDING.equals(this.status)); } - - + + /** * Indicates that comment has been approved for display on weblog. */ public Boolean getApproved() { return new Boolean(APPROVED.equals(this.status)); } - - + + /** * Timestamp to be used to formulate comment permlink. */ @@ -306,7 +306,7 @@ public String getTimestamp() { } return null; } - + //------------------------------------------------------- Good citizenship public String toString() { @@ -325,18 +325,18 @@ public boolean equals(Object other) { if (other instanceof WeblogEntryComment != true) return false; WeblogEntryComment o = (WeblogEntryComment)other; return new EqualsBuilder() - .append(getName(), o.getName()) - .append(getPostTime(), o.getPostTime()) - .append(getWeblogEntry(), o.getWeblogEntry()) + .append(getName(), o.getName()) + .append(getPostTime(), o.getPostTime()) + .append(getWeblogEntry(), o.getWeblogEntry()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getName()) .append(getPostTime()) .append(getWeblogEntry()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTag.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTag.java index c645d097ad..04c35877f5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTag.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTag.java @@ -33,26 +33,26 @@ * @author Elias Torres */ public class WeblogEntryTag implements Serializable { - private static Log log = LogFactory.getLog(WeblogEntryTag.class); - + private static Log log = LogFactory.getLog(WeblogEntryTag.class); + private static final long serialVersionUID = -2602052289337573384L; - + private String id = UUIDGenerator.generateUUID(); private Weblog website = null; private WeblogEntry weblogEntry = null; private String userName = null; private String name = null; private Timestamp time = null; - - + + public WeblogEntryTag() { } - + public WeblogEntryTag( String id, Weblog website, WeblogEntry weblogEntry, - User user, + User user, String name, Timestamp time) { //this.id = id; @@ -62,42 +62,42 @@ public WeblogEntryTag( this.name = name; this.time = time; } - + //------------------------------------------------------- Simple properties - + /** * Unique ID and primary key. */ public String getId() { return this.id; } - + public void setId(String id) { this.id = id; } - - + + /** * ID of website that this tag refers to. */ public Weblog getWeblog() { return this.website; } - + public void setWeblog(Weblog website) { this.website = website; } - - + + public WeblogEntry getWeblogEntry() { return weblogEntry; } - + public void setWeblogEntry(WeblogEntry data) { weblogEntry = data; } - - + + public User getUser() { try { return WebloggerFactory.getWeblogger().getUserManager().getUserByUserName(getCreatorUserName()); @@ -106,7 +106,7 @@ public User getUser() { } return null; } - + public String getCreatorUserName() { return userName; } @@ -114,29 +114,29 @@ public String getCreatorUserName() { public void setCreatorUserName(String userName) { this.userName = userName; } - + /** * Tag value. */ public String getName() { return this.name; } - + public void setName( String name ) { this.name = name; } - - + + public java.sql.Timestamp getTime() { return this.time; } - + public void setTime(java.sql.Timestamp tagTime) { this.time = tagTime; } - + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -146,7 +146,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof WeblogEntryTag != true) return false; @@ -156,7 +156,7 @@ public boolean equals(Object other) { .append(getWeblogEntry(), o.getWeblogEntry()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.java index caf16c5def..ff0417ce68 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.java @@ -29,19 +29,19 @@ * Tag aggregate data. */ public class WeblogEntryTagAggregate implements Serializable { - + public static final long serialVersionUID = -4343500268898106982L; - + private String id = UUIDGenerator.generateUUID(); private String name = null; private Weblog website = null; private Timestamp lastUsed = null; private int total = 0; - - + + public WeblogEntryTagAggregate() { } - + public WeblogEntryTagAggregate(String id, Weblog website, String name, int total) { @@ -50,61 +50,61 @@ public WeblogEntryTagAggregate(String id, this.name = name; this.total = total; } - + //------------------------------------------------------- Simple properties - + /** * Unique ID and primary key. */ public String getId() { return this.id; } - + public void setId(String id) { this.id = id; } - - + + public Weblog getWeblog() { return this.website; } - + public void setWeblog(Weblog website) { this.website = website; } - - + + /** * Tag value. */ public String getName() { return this.name; } - + public void setName( String name ) { this.name = name; } - - + + public int getTotal() { return this.total; } - + public void setTotal(int total) { this.total = total; } - - + + public Timestamp getLastUsed() { return this.lastUsed; } - + public void setLastUsed(Timestamp lastUsed) { this.lastUsed = lastUsed; } - + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -115,7 +115,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof WeblogEntryTagAggregate != true) return false; @@ -125,12 +125,12 @@ public boolean equals(Object other) { .append(this.getWeblog(), o.getWeblog()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getName()) .append(getWeblog()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryWrapperComparator.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryWrapperComparator.java index 46fd171ca4..66dee32e6f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryWrapperComparator.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogEntryWrapperComparator.java @@ -26,13 +26,13 @@ * Sorts WeblogEntryData objects in reverse chronological order * (most recently published entries first). If they happen to * have the same pubTime, then sort alphabetically by title. - * + * * @author lance.lavandowska */ public class WeblogEntryWrapperComparator implements Comparator, Serializable { static final long serialVersionUID = -9067148992322255150L; - + public int compare(Object val1, Object val2) throws ClassCastException { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogHitCount.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogHitCount.java index 83ce83d69c..d90c5123ee 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogHitCount.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogHitCount.java @@ -27,15 +27,15 @@ * Represents hit count data for a weblog. */ public class WeblogHitCount implements Serializable { - + private String id = UUIDGenerator.generateUUID(); private Weblog weblog = null; private int dailyHits = 0; - - + + public WeblogHitCount() {} - - + + //------------------------------------------------------- Good citizenship public String toString() { @@ -46,24 +46,24 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { - + if(this == other) return true; if( !(other instanceof WeblogHitCount) ) return false; - + // our natural key, or business key, is our weblog final WeblogHitCount that = (WeblogHitCount) other; return this.getWeblog().equals(that.getWeblog()); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getWeblog()) .toHashCode(); } - - + + public String getId() { return id; } @@ -71,8 +71,8 @@ public String getId() { public void setId(String id) { this.id = id; } - - + + public Weblog getWeblog() { return weblog; } @@ -80,8 +80,8 @@ public Weblog getWeblog() { public void setWeblog(Weblog weblog) { this.weblog = weblog; } - - + + public int getDailyHits() { return dailyHits; } @@ -89,5 +89,5 @@ public int getDailyHits() { public void setDailyHits(int dailyHits) { this.dailyHits = dailyHits; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogPermission.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogPermission.java index a3cef3af22..d147def22f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogPermission.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogPermission.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.weblogger.pojos; +package org.apache.roller.weblogger.pojos; import java.io.Serializable; import java.security.Permission; @@ -39,7 +39,7 @@ public class WeblogPermission extends ObjectPermission implements Serializable { public static final String POST = "post"; public static final String ADMIN = "admin"; public static final List ALL_ACTIONS = new ArrayList(); - + static { ALL_ACTIONS.add(EDIT_DRAFT); ALL_ACTIONS.add(POST); @@ -57,22 +57,22 @@ public WeblogPermission(Weblog weblog, User user, String actions) { objectId = weblog.getHandle(); userName = user.getUserName(); } - + public WeblogPermission(Weblog weblog, User user, List actions) { super("WeblogPermission user: " + user.getUserName()); - setActionsAsList(actions); + setActionsAsList(actions); objectType = "Weblog"; objectId = weblog.getHandle(); userName = user.getUserName(); } - + public WeblogPermission(Weblog weblog, List actions) { super("WeblogPermission user: N/A"); - setActionsAsList(actions); + setActionsAsList(actions); objectType = "Weblog"; objectId = weblog.getHandle(); } - + public Weblog getWeblog() throws WebloggerException { if (objectId != null) { return WebloggerFactory.getWeblogger().getWeblogManager().getWeblogByHandle(objectId, null); @@ -98,17 +98,17 @@ public int hashCode() { public boolean implies(Permission perm) { if (perm instanceof WeblogPermission) { WeblogPermission rperm = (WeblogPermission)perm; - + if (hasAction(ADMIN)) { // admin implies all other permissions return true; - + } else if (hasAction(POST)) { // Best we've got is POST, so make sure perm doesn't specify POST for (String action : rperm.getActionsAsList()) { if (action.equals(ADMIN)) return false; } - + } else if (hasAction(EDIT_DRAFT)) { // Best we've got is EDIT_DRAFT, so make sure perm doesn't specify anything else for (String action : rperm.getActionsAsList()) { @@ -120,11 +120,11 @@ public boolean implies(Permission perm) { } return false; } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("GlobalPermission: "); - for (String action : getActionsAsList()) { + for (String action : getActionsAsList()) { sb.append(" ").append(action).append(" "); } return sb.toString(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogReferrer.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogReferrer.java index 0630bba7fc..f2b30532fd 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogReferrer.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogReferrer.java @@ -31,9 +31,9 @@ * @author David M Johnson */ public class WeblogReferrer implements Serializable { - + public static final long serialVersionUID = -1817992900602131316L; - + private String id = UUIDGenerator.generateUUID(); private Weblog website = null; private WeblogEntry weblogEntry = null; @@ -47,11 +47,11 @@ public class WeblogReferrer implements Serializable { private Boolean duplicate = null; private Integer dayHits = null; private Integer totalHits = null; - - + + public WeblogReferrer() { } - + public WeblogReferrer(String id, org.apache.roller.weblogger.pojos.Weblog website,org.apache.roller.weblogger.pojos.WeblogEntry weblogEntry, String dateString, String refererUrl, @@ -60,7 +60,7 @@ public WeblogReferrer(String id, String excerpt, Boolean visible, Boolean duplicate, Integer dayHits, Integer totalHits) { - + //this.id = id; this.website = website; this.weblogEntry = weblogEntry; @@ -79,21 +79,21 @@ public WeblogReferrer(String id, this.refererUrl = this.refererUrl.substring(0, 254); } } - + //------------------------------------------------------- Simple properties - + /** * Unique ID and primary key of this Referer. */ public String getId() { return this.id; } - + public void setId(String id) { this.id = id; } - - + + /** * ID of website that this referer refers to. * @@ -103,11 +103,11 @@ public void setId(String id) { public org.apache.roller.weblogger.pojos.Weblog getWebsite() { return this.website; } - + public void setWebsite(org.apache.roller.weblogger.pojos.Weblog website) { this.website = website; } - + /** * @roller.wrapPojoMethod type="pojo" * @hibernate.many-to-one column="entryid" cascade="none" @@ -115,14 +115,14 @@ public void setWebsite(org.apache.roller.weblogger.pojos.Weblog website) { public org.apache.roller.weblogger.pojos.WeblogEntry getWeblogEntry() { return weblogEntry; } - + /** * @param data */ public void setWeblogEntry(org.apache.roller.weblogger.pojos.WeblogEntry data) { weblogEntry = data; } - + /** * Date string in YYYYMMDD format. * @@ -132,11 +132,11 @@ public void setWeblogEntry(org.apache.roller.weblogger.pojos.WeblogEntry data) { public String getDateString() { return this.dateString; } - + public void setDateString(String dateString) { this.dateString = dateString; } - + /** * URL of the refering page. * @@ -146,14 +146,14 @@ public void setDateString(String dateString) { public String getRefererUrl() { return this.refererUrl; } - + public void setRefererUrl(String refererUrl) { this.refererUrl = refererUrl; if (this.refererUrl != null && this.refererUrl.length() > 255) { this.refererUrl = this.refererUrl.substring(0, 255); } } - + /** * Requested URL, the URL linked to by the refering page. * @@ -163,11 +163,11 @@ public void setRefererUrl(String refererUrl) { public String getRefererPermalink() { return this.refererPermalink; } - + public void setRefererPermalink(String refererPermalink) { this.refererPermalink = refererPermalink; } - + /** * Requested URL, the URL linked to by the refering page. * @@ -177,11 +177,11 @@ public void setRefererPermalink(String refererPermalink) { public String getRequestUrl() { return this.requestUrl; } - + public void setRequestUrl(String requestUrl) { this.requestUrl = requestUrl; } - + /** * The text on the refering page that surrounds the refering link. * @@ -191,11 +191,11 @@ public void setRequestUrl(String requestUrl) { public String getTitle() { return this.title; } - + public void setTitle(String title) { this.title = title; } - + /** * The text on the refering page that surrounds the refering link. * @@ -205,11 +205,11 @@ public void setTitle(String title) { public String getExcerpt() { return this.excerpt; } - + public void setExcerpt(String excerpt) { this.excerpt = excerpt; } - + /** * Should this referer be displayed? * @@ -219,11 +219,11 @@ public void setExcerpt(String excerpt) { public Boolean getVisible() { return this.visible; } - + public void setVisible(Boolean visible) { this.visible = visible; } - + /** * Is this referer a duplicate? * @@ -233,11 +233,11 @@ public void setVisible(Boolean visible) { public Boolean getDuplicate() { return this.duplicate; } - + public void setDuplicate(Boolean duplicate) { this.duplicate = duplicate; } - + /** * Hits received today from this referer. * @@ -247,11 +247,11 @@ public void setDuplicate(Boolean duplicate) { public Integer getDayHits() { return this.dayHits; } - + public void setDayHits(Integer dayHits) { this.dayHits = dayHits; } - + /** * Total hits received from this referer. * @@ -261,65 +261,65 @@ public void setDayHits(Integer dayHits) { public Integer getTotalHits() { return this.totalHits; } - + public void setTotalHits(Integer totalHits) { this.totalHits = totalHits; } - + //------------------------------------------------------------------------- - + /** * @roller.wrapPojoMethod type="simple" */ public String getDisplayUrl(int maxWidth, boolean includeHits) { StringBuffer sb = new StringBuffer(); - + String url = StringEscapeUtils.escapeHtml(getUrl()); String displayUrl = url.trim(); String restOfUrl = null; - + if (displayUrl.startsWith("http://")) { displayUrl = displayUrl.substring(7); } - + if (displayUrl.length() > maxWidth) { restOfUrl = "..." + displayUrl.substring(maxWidth, displayUrl.length()); displayUrl = displayUrl.substring(0, maxWidth) + "..."; } - + if (url.startsWith("http://")) { sb.append(" 0) { sb.append("\">"); } - + sb.append(displayUrl); - + if (includeHits) { sb.append(" ("); sb.append(getDayHits()); sb.append(")"); } - + if (url.startsWith("http://")) { sb.append(""); } - + return sb.toString(); } - + //------------------------------------------------------------------------- - + /** * @roller.wrapPojoMethod type="simple" */ @@ -330,18 +330,18 @@ public String getUrl() { return getRefererUrl(); } } - + //------------------------------------------------------------------------- - + /** * @roller.wrapPojoMethod type="simple" */ public String getDisplayUrl() { return getDisplayUrl(50, false); } - + //------------------------------------------------------- Good citizenship - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append("{"); @@ -353,7 +353,7 @@ public String toString() { buf.append("}"); return buf.toString(); } - + public boolean equals(Object other) { if (other == this) return true; if (other instanceof WeblogReferrer != true) return false; @@ -364,7 +364,7 @@ public boolean equals(Object other) { .append(getWebsite(),o.getWebsite()) .isEquals(); } - + public int hashCode() { return new HashCodeBuilder() .append(getRefererUrl()) @@ -372,5 +372,5 @@ public int hashCode() { .append(getWebsite()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTemplate.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTemplate.java index 1e565c2dc7..bf00f53d9b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTemplate.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTemplate.java @@ -37,13 +37,13 @@ * contains a reference to the website it is part of. */ public class WeblogTemplate implements ThemeTemplate, Serializable { - + public static final long serialVersionUID = -613737191638263428L; public static final String DEFAULT_PAGE = "Weblog"; - + private static Log log = LogFactory.getLog(WeblogTemplate.class); private static Set requiredTemplates = null; - + // attributes private String id = UUIDGenerator.generateUUID(); private String action = null; @@ -57,21 +57,21 @@ public class WeblogTemplate implements ThemeTemplate, Serializable { private boolean navbar = false; private String decoratorName = null; private String outputContentType = null; - + // associations private Weblog weblog = null; - - + + static { requiredTemplates = new HashSet(); requiredTemplates.add("Weblog"); requiredTemplates.add("_day"); } - - + + public WeblogTemplate() {} - - + + public ThemeTemplate getDecorator() { if(decoratorName != null && !id.equals(decoratorName)) { try { @@ -83,26 +83,26 @@ public ThemeTemplate getDecorator() { } return null; } - - + + public String getId() { return this.id; } - + public void setId( String id ) { this.id = id; } - - + + public Weblog getWebsite() { return this.weblog; } - + public void setWebsite( Weblog website ) { this.weblog = website; } - - + + public String getAction() { return action; } @@ -110,53 +110,53 @@ public String getAction() { public void setAction(String action) { this.action = action; } - - + + public String getName() { return this.name; } - + public void setName( String name ) { this.name = name; } - - + + public String getDescription() { return this.description; } - + public void setDescription( String description ) { this.description = description; } - - + + public String getLink() { return this.link; } - + public void setLink( String link ) { this.link = link; } - - + + public String getContents() { return this.contents; } - + public void setContents( String template ) { this.contents = template; } - - + + public Date getLastModified() { return lastModified; } - + public void setLastModified(final Date newtime ) { lastModified = newtime; } - - + + public String getTemplateLanguage() { return templateLanguage; } @@ -164,8 +164,8 @@ public String getTemplateLanguage() { public void setTemplateLanguage(String templateLanguage) { this.templateLanguage = templateLanguage; } - - + + public boolean isNavbar() { return navbar; } @@ -173,8 +173,8 @@ public boolean isNavbar() { public void setNavbar(boolean navbar) { this.navbar = navbar; } - - + + public boolean isHidden() { return hidden; } @@ -182,8 +182,8 @@ public boolean isHidden() { public void setHidden(boolean isHidden) { this.hidden = isHidden; } - - + + public String getDecoratorName() { return decoratorName; } @@ -191,20 +191,20 @@ public String getDecoratorName() { public void setDecoratorName(String decorator) { this.decoratorName = decorator; } - - - /** + + + /** * Content-type rendered by template or null for auto-detection by link extension. */ public String getOutputContentType() { return outputContentType; } - + public void setOutputContentType(String outputContentType) { this.outputContentType = outputContentType; } - - + + /** * Determine if this WeblogTemplate is required or not. */ @@ -222,8 +222,8 @@ public boolean isRequired() { */ return (requiredTemplates.contains(this.name) || "Weblog".equals(this.link)); } - - + + /** * A convenience method for testing if this template represents a 'custom' * template, meaning a template with action = ACTION_CUSTOM. @@ -231,8 +231,8 @@ public boolean isRequired() { public boolean isCustom() { return ACTION_CUSTOM.equals(getAction()) && !isRequired(); } - - + + //------------------------------------------------------- Good citizenship public String toString() { @@ -252,16 +252,16 @@ public boolean equals(Object other) { if (other instanceof WeblogTemplate != true) return false; WeblogTemplate o = (WeblogTemplate)other; return new EqualsBuilder() - .append(name, o.getName()) - .append(getWebsite(), o.getWebsite()) + .append(name, o.getName()) + .append(getWebsite(), o.getWebsite()) .isEquals(); } - - public int hashCode() { + + public int hashCode() { return new HashCodeBuilder() .append(getName()) .append(getWebsite()) .toHashCode(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTheme.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTheme.java index d3d543b420..a930a19fc0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTheme.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/WeblogTheme.java @@ -28,20 +28,20 @@ * rendering for a given weblog design. */ public abstract class WeblogTheme implements Theme, Serializable { - + // this is the name that will be used to identify a user customized theme public static final String CUSTOM = "custom"; - + protected Weblog weblog = null; - - + + public WeblogTheme(Weblog weblog) { this.weblog = weblog; } - - + + public Weblog getWeblog() { return this.weblog; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/ThemeTemplateWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/ThemeTemplateWrapper.java index e0b5295679..ad8fd0e1db 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/ThemeTemplateWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/ThemeTemplateWrapper.java @@ -26,62 +26,62 @@ * Pojo safety wrapper for ThemeTemplate objects. */ public class ThemeTemplateWrapper { - + // keep a reference to the wrapped pojo private final ThemeTemplate pojo; - + // this is private so that we can force the use of the .wrap(pojo) method private ThemeTemplateWrapper(ThemeTemplate toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static ThemeTemplateWrapper wrap(ThemeTemplate toWrap) { if(toWrap != null) return new ThemeTemplateWrapper(toWrap); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public String getName() { return this.pojo.getName(); } - - + + public String getDescription() { return this.pojo.getDescription(); } - - + + public String getContents() { return this.pojo.getContents(); } - - + + public String getLink() { return this.pojo.getLink(); } - - + + public Date getLastModified() { return this.pojo.getLastModified(); } - - + + public boolean isHidden() { return this.pojo.isHidden(); } - - + + public boolean isNavbar() { return this.pojo.isNavbar(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/UserWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/UserWrapper.java index 4ed2578120..90260057c8 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/UserWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/UserWrapper.java @@ -27,25 +27,25 @@ * Pojo safety wrapper for User objects. */ public class UserWrapper { - + // keep a reference to the wrapped pojo private final User pojo; - + // this is private so that we can force the use of the .wrap(pojo) method private UserWrapper(User toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static UserWrapper wrap(User toWrap) { if(toWrap != null) return new UserWrapper(toWrap); - + return null; } - - + + /** * This is here for backwards compatability. We no longer allow the * username to be displayed publicly, so screen name is returned instead. @@ -56,35 +56,35 @@ public String getUserName() { } return this.pojo.getUserName(); } - - + + public String getScreenName() { return this.pojo.getScreenName(); } - - + + public String getFullName() { return this.pojo.getFullName(); } - - + + public String getEmailAddress() { return this.pojo.getEmailAddress(); } - - + + public Date getDateCreated() { return this.pojo.getDateCreated(); } - - + + public String getLocale() { return this.pojo.getLocale(); } - - + + public String getTimeZone() { return this.pojo.getTimeZone(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkFolderWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkFolderWrapper.java index 2c672553d6..1b17f68f64 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkFolderWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkFolderWrapper.java @@ -33,58 +33,58 @@ * Pojo safety wrapper for WeblogBookmarkFolder object. */ public class WeblogBookmarkFolderWrapper { - + // keep a reference to the wrapped pojo private final WeblogBookmarkFolder pojo; - + // this is private so that we can force the use of the .wrap(pojo) method private WeblogBookmarkFolderWrapper(WeblogBookmarkFolder toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static WeblogBookmarkFolderWrapper wrap(WeblogBookmarkFolder toWrap) { if(toWrap != null) return new WeblogBookmarkFolderWrapper(toWrap); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public String getName() { return this.pojo.getName(); } - - + + public String getDescription() { return this.pojo.getDescription(); } - - + + public String getPath() { return this.pojo.getPath(); } - + // NOTE: removing this for 4.0 since there is really no need for this in templates // public WeblogWrapper getWebsite() { // return WeblogWrapper.wrap(this.pojo.getWebsite()); // } - - + + public WeblogBookmarkFolderWrapper getParent() { return WeblogBookmarkFolderWrapper.wrap(this.pojo.getParent()); } - - + + public List getFolders() { Set initialCollection = this.pojo.getFolders(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -95,15 +95,15 @@ public List getFolders() { wrappedCollection.add(i,WeblogBookmarkFolderWrapper.wrap((WeblogBookmarkFolder) it.next())); i++; } - + return wrappedCollection; } - - + + public List getBookmarks() { TreeSet initialCollection = new TreeSet(new BookmarkComparator()); initialCollection.addAll(this.pojo.getBookmarks()); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -114,16 +114,16 @@ public List getBookmarks() { wrappedCollection.add(i,WeblogBookmarkWrapper.wrap((WeblogBookmark) it.next())); i++; } - + return wrappedCollection; - } - - + } + + public List retrieveBookmarks(boolean subfolders) throws WebloggerException { - + List initialCollection = this.pojo.retrieveBookmarks(subfolders); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -134,14 +134,14 @@ public List retrieveBookmarks(boolean subfolders) wrappedCollection.add(i,WeblogBookmarkWrapper.wrap((WeblogBookmark) it.next())); i++; } - + return wrappedCollection; } - - + + // TODO: this method won't actually work and we probably don't need it here anyways? public boolean descendentOf(WeblogBookmarkFolder ancestor) { return this.pojo.descendentOf(ancestor); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkWrapper.java index 65a3409af1..e2719cf691 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogBookmarkWrapper.java @@ -25,67 +25,67 @@ * Pojo safety wrapper for WeblogBookmark object. */ public class WeblogBookmarkWrapper { - + // keep a reference to the wrapped pojo private final WeblogBookmark pojo; - + // this is private so that we can force the use of the .wrap(pojo) method private WeblogBookmarkWrapper(WeblogBookmark toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static WeblogBookmarkWrapper wrap(WeblogBookmark toWrap) { if(toWrap != null) return new WeblogBookmarkWrapper(toWrap); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public String getName() { return this.pojo.getName(); } - - + + public String getDescription() { return this.pojo.getDescription(); } - - + + public String getUrl() { return this.pojo.getUrl(); } - - + + public Integer getWeight() { return this.pojo.getWeight(); } - - + + public Integer getPriority() { return this.pojo.getPriority(); } - - + + public String getImage() { return this.pojo.getImage(); } - - + + public String getFeedUrl() { return this.pojo.getFeedUrl(); } - - + + public WeblogBookmarkFolderWrapper getFolder() { return WeblogBookmarkFolderWrapper.wrap(this.pojo.getFolder()); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogCategoryWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogCategoryWrapper.java index a9f94a6989..3476bed7d4 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogCategoryWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogCategoryWrapper.java @@ -32,68 +32,68 @@ * Pojo safety wrapper for WeblogCategory objects. */ public class WeblogCategoryWrapper { - + // keep a reference to the wrapped pojo private final WeblogCategory pojo; - + // url strategy to use for any url building private final URLStrategy urlStrategy; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogCategoryWrapper(WeblogCategory toWrap, URLStrategy strat) { this.pojo = toWrap; this.urlStrategy = strat; } - - + + // wrap the given pojo if it is not null public static WeblogCategoryWrapper wrap(WeblogCategory toWrap, URLStrategy strat) { if(toWrap != null) return new WeblogCategoryWrapper(toWrap, strat); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public String getName() { return this.pojo.getName(); } - - + + public String getDescription() { return this.pojo.getDescription(); } - - + + public String getImage() { return this.pojo.getImage(); } - - + + public String getPath() { return this.pojo.getPath(); } - - + + public WeblogWrapper getWebsite() { return WeblogWrapper.wrap(this.pojo.getWebsite(), urlStrategy); } - - + + public WeblogCategoryWrapper getParent() { return WeblogCategoryWrapper.wrap(this.pojo.getParent(), urlStrategy); } - - + + public List getWeblogCategories() { Set initialCollection = this.pojo.getWeblogCategories(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -104,16 +104,16 @@ public List getWeblogCategories() { wrappedCollection.add(i,WeblogCategoryWrapper.wrap((WeblogCategory) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public List retrieveWeblogEntries(boolean subcats) throws WebloggerException { - + List initialCollection = this.pojo.retrieveWeblogEntries(subcats); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -124,19 +124,19 @@ public List retrieveWeblogEntries(boolean subcats) wrappedCollection.add(i,WeblogEntryWrapper.wrap((WeblogEntry) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + // TODO: this method doesn't work and propably doesn't need to be here anyways? public boolean descendentOf(WeblogCategory ancestor) { return this.pojo.descendentOf(ancestor); } - - + + public boolean isInUse() { return this.pojo.isInUse(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryAttributeWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryAttributeWrapper.java index f26bb5e26c..8d67cb9f9a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryAttributeWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryAttributeWrapper.java @@ -25,42 +25,42 @@ * Pojo safety wrapper for WeblogEntryAttribute object. */ public class WeblogEntryAttributeWrapper { - + // keep a reference to the wrapped pojo private final WeblogEntryAttribute pojo; - + // this is private so that we can force the use of the .wrap(pojo) method private WeblogEntryAttributeWrapper(WeblogEntryAttribute toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static WeblogEntryAttributeWrapper wrap(WeblogEntryAttribute toWrap) { if(toWrap != null) return new WeblogEntryAttributeWrapper(toWrap); - + return null; } - + // NOTD: removing this for 4.0 because there is no need for it // public String getId() { // return this.pojo.getId(); // } - + // NOTE: removing this for 4.0 because there is no need for it // public WeblogEntryWrapper getEntry() { // return WeblogEntryWrapper.wrap(this.pojo.getEntry()); // } - - + + public String getName() { return this.pojo.getName(); } - - + + public String getValue() { return this.pojo.getValue(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryCommentWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryCommentWrapper.java index 1322348b2b..505f422cb5 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryCommentWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryCommentWrapper.java @@ -31,40 +31,40 @@ * Pojo safety wrapper for WeblogEntryComment object. */ public class WeblogEntryCommentWrapper { - + // keep a reference to the wrapped pojo private final WeblogEntryComment pojo; - + // url strategy to use for any url building private final URLStrategy urlStrategy; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogEntryCommentWrapper(WeblogEntryComment toWrap, URLStrategy strat) { this.pojo = toWrap; this.urlStrategy = strat; } - - + + // wrap the given pojo if it is not null public static WeblogEntryCommentWrapper wrap(WeblogEntryComment toWrap, URLStrategy strat) { if(toWrap != null) return new WeblogEntryCommentWrapper(toWrap, strat); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public WeblogEntryWrapper getWeblogEntry() { return WeblogEntryWrapper.wrap(this.pojo.getWeblogEntry(), urlStrategy); } - - + + /** * Get the name of the comment writer. * @@ -73,8 +73,8 @@ public WeblogEntryWrapper getWeblogEntry() { public String getName() { return StringEscapeUtils.escapeHtml(this.pojo.getName()); } - - + + /** * Get the email address of the comment writer, if specified. * @@ -83,8 +83,8 @@ public String getName() { public String getEmail() { return StringEscapeUtils.escapeHtml(this.pojo.getEmail()); } - - + + /** * Get the url of the comment writer, if specified. * @@ -93,57 +93,57 @@ public String getEmail() { public String getUrl() { return StringEscapeUtils.escapeHtml(this.pojo.getUrl()); } - - + + /** * Get the comment contents. * - * Any configured comment plugins are applied first, then the value is + * Any configured comment plugins are applied first, then the value is * always html escaped. */ public String getContent() { - + String content = this.pojo.getContent(); - + // escape content if content-type is text/plain if("text/plain".equals(this.pojo.getContentType())) { content = StringEscapeUtils.escapeHtml(content); } - + // apply plugins PluginManager pmgr = WebloggerFactory.getWeblogger().getPluginManager(); content = pmgr.applyCommentPlugins(this.pojo, content); - + // always add rel=nofollow for links content = Utilities.addNofollow(content); - + return content; } - - + + /** * Get the time the comment was posted. */ public Timestamp getPostTime() { return this.pojo.getPostTime(); } - - + + public String getStatus() { return this.pojo.getStatus(); } - - + + public Boolean getNotify() { return this.pojo.getNotify(); } - - + + public String getRemoteHost() { return this.pojo.getRemoteHost(); } - - + + /** * Get the http referrer of the comment poster, used for trackbacks. * @@ -152,30 +152,30 @@ public String getRemoteHost() { public String getReferrer() { return StringEscapeUtils.escapeHtml(this.pojo.getReferrer()); } - - + + public String getUserAgent() { return this.pojo.getUserAgent(); } - - + + public Boolean getSpam() { return this.pojo.getSpam(); } - - + + public Boolean getPending() { return this.pojo.getPending(); } - - + + public Boolean getApproved() { return this.pojo.getApproved(); } - - + + public String getTimestamp() { return this.pojo.getTimestamp(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryTagWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryTagWrapper.java index 04f2f4fe41..82b3d5335f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryTagWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryTagWrapper.java @@ -26,53 +26,53 @@ * Pojo safety wrapper for WeblogEntryTag objects. */ public class WeblogEntryTagWrapper { - + // keep a reference to the wrapped pojo private final WeblogEntryTag pojo; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogEntryTagWrapper(WeblogEntryTag toWrap) { this.pojo = toWrap; } - - + + // wrap the given pojo if it is not null public static WeblogEntryTagWrapper wrap(WeblogEntryTag toWrap) { if(toWrap != null) return new WeblogEntryTagWrapper(toWrap); - + return null; } - + // NOTE: removing for 4.0 because it is not necessary // public String getId() { // return this.pojo.getId(); // } - + // NOTE: removing for 4.0 because it is not necessary // public WeblogWrapper getWeblog() { // return WeblogWrapper.wrap(this.pojo.getWeblog()); // } - + // NOTE: removing for 4.0 because it is not necessary // public WeblogEntryWrapper getWeblogEntry() { // return WeblogEntryWrapper.wrap(this.pojo.getWeblogEntry()); // } - - + + public UserWrapper getUser() { return UserWrapper.wrap(this.pojo.getUser()); } - - + + public String getName() { return this.pojo.getName(); } - - + + public Timestamp getTime() { return this.pojo.getTime(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryWrapper.java index 1ac7b0ee6d..209ba30b5d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogEntryWrapper.java @@ -36,43 +36,43 @@ * Pojo safety wrapper for WeblogEntry objects. */ public class WeblogEntryWrapper { - + // keep a reference to the wrapped pojo private final WeblogEntry pojo; - + // url strategy to use for any url building private final URLStrategy urlStrategy; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogEntryWrapper(WeblogEntry toWrap, URLStrategy strat) { this.pojo = toWrap; this.urlStrategy = strat; } - - + + // wrap the given pojo if it is not null public static WeblogEntryWrapper wrap(WeblogEntry toWrap, URLStrategy strat) { if(toWrap != null) return new WeblogEntryWrapper(toWrap, strat); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public WeblogCategoryWrapper getCategory() { return WeblogCategoryWrapper.wrap(this.pojo.getCategory(), urlStrategy); } - - + + public List getCategories() { List initialCollection = this.pojo.getCategories(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -83,30 +83,30 @@ public List getCategories() { wrappedCollection.add(i,WeblogCategoryWrapper.wrap((WeblogCategory) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public WeblogWrapper getWebsite() { return WeblogWrapper.wrap(this.pojo.getWebsite(), urlStrategy); } - - + + public UserWrapper getCreator() { return UserWrapper.wrap(this.pojo.getCreator()); } - - + + public String getTitle() { return this.pojo.getTitle(); } - - + + public String getSummary() { return this.pojo.getSummary(); } - + /** * pojo method tagged with @roller.wrapPojoMethod type="simple" * @@ -115,26 +115,26 @@ public String getSummary() { public String getText() { return this.pojo.getText(); } - - + + public String getContentType() { return this.pojo.getContentType(); } - - + + public String getContentSrc() { return this.pojo.getContentSrc(); } - - + + public String getAnchor() { return this.pojo.getAnchor(); } - - + + public List getEntryAttributes() { Set initialCollection = this.pojo.getEntryAttributes(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -145,69 +145,69 @@ public List getEntryAttributes() { wrappedCollection.add(i,WeblogEntryAttributeWrapper.wrap((WeblogEntryAttribute) it.next())); i++; } - + return wrappedCollection; } - - + + public String findEntryAttribute(String name) { return this.pojo.findEntryAttribute(name); } - - + + public Timestamp getPubTime() { return this.pojo.getPubTime(); } - - + + public Timestamp getUpdateTime() { return this.pojo.getUpdateTime(); } - - + + public String getStatus() { return this.pojo.getStatus(); } - - + + public String getLink() { return this.pojo.getLink(); } - - + + public String getPlugins() { return this.pojo.getPlugins(); } - - + + public Boolean getAllowComments() { return this.pojo.getAllowComments(); } - - + + public Integer getCommentDays() { return this.pojo.getCommentDays(); } - - + + public Boolean getRightToLeft() { return this.pojo.getRightToLeft(); } - - + + public Boolean getPinnedToMain() { return this.pojo.getPinnedToMain(); } - - + + public String getLocale() { return this.pojo.getLocale(); } - - + + public List getTags() { Set initialCollection = this.pojo.getTags(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -218,34 +218,34 @@ public List getTags() { wrappedCollection.add(i,WeblogEntryTagWrapper.wrap((WeblogEntryTag) it.next())); i++; } - + return wrappedCollection; } - - + + public String getTagsAsString() { return this.pojo.getTagsAsString(); } - - + + public boolean getCommentsStillAllowed() { return this.pojo.getCommentsStillAllowed(); } - - + + public String formatPubTime(String pattern) { return this.pojo.formatPubTime(pattern); } - - + + public String formatUpdateTime(String pattern) { return this.pojo.formatUpdateTime(pattern); } - - + + public List getComments() { List initialCollection = this.pojo.getComments(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -256,14 +256,14 @@ public List getComments() { wrappedCollection.add(i,WeblogEntryCommentWrapper.wrap((WeblogEntryComment) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public List getComments(boolean ignoreSpam,boolean approvedOnly) { List initialCollection = this.pojo.getComments(ignoreSpam,approvedOnly); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -274,19 +274,19 @@ public List getComments(boolean ignoreSpam,boolean approvedOnly) { wrappedCollection.add(i,WeblogEntryCommentWrapper.wrap((WeblogEntryComment) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public int getCommentCount() { return this.pojo.getCommentCount(); } - - + + public List getReferers() { List initialCollection = this.pojo.getReferers(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -297,67 +297,67 @@ public List getReferers() { wrappedCollection.add(i,WeblogReferrerWrapper.wrap((WeblogReferrer) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public String getPermalink() { return this.pojo.getPermalink(); } - - + + public String getPermaLink() { return this.pojo.getPermaLink(); } - - + + public String getCommentsLink() { return this.pojo.getCommentsLink(); } - - + + public String getDisplayTitle() { return this.pojo.getDisplayTitle(); } - - + + public String getRss09xDescription() { return this.pojo.getRss09xDescription(); } - - + + public String getRss09xDescription(int maxLength) { return this.pojo.getRss09xDescription(maxLength); } - - + + // TODO: check this method for safety public List getPluginsList() { return this.pojo.getPluginsList(); } - - + + public String getTransformedText() { return this.pojo.getTransformedText(); } - - + + public String getTransformedSummary() { return this.pojo.getTransformedSummary(); } - - + + public String displayContent(String readMoreLink) { return this.pojo.displayContent(readMoreLink); } - - + + public String getDisplayContent() { return this.pojo.getDisplayContent(); } - - + + /** * this is a special method to access the original pojo. * we don't really want to do this, but it's necessary @@ -367,5 +367,5 @@ public String getDisplayContent() { public WeblogEntry getPojo() { return this.pojo; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogReferrerWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogReferrerWrapper.java index c324ebd3fa..8026c5f58d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogReferrerWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogReferrerWrapper.java @@ -26,107 +26,107 @@ * Pojo safety wrapper for WeblogReferrer object. */ public class WeblogReferrerWrapper { - + // keep a reference to the wrapped pojo private final WeblogReferrer pojo; - + // url strategy to use for any url building private final URLStrategy urlStrategy; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogReferrerWrapper(WeblogReferrer toWrap, URLStrategy strat) { this.pojo = toWrap; this.urlStrategy = strat; } - - + + // wrap the given pojo if it is not null public static WeblogReferrerWrapper wrap(WeblogReferrer toWrap, URLStrategy strat) { if(toWrap != null) return new WeblogReferrerWrapper(toWrap, strat); - + return null; } - - + + public String getId() { return this.pojo.getId(); } - - + + public WeblogWrapper getWebsite() { return WeblogWrapper.wrap(this.pojo.getWebsite(), urlStrategy); } - - + + public WeblogEntryWrapper getWeblogEntry() { return WeblogEntryWrapper.wrap(this.pojo.getWeblogEntry(), urlStrategy); } - - + + public String getDateString() { return this.pojo.getDateString(); } - - + + public String getRefererUrl() { return this.pojo.getRefererUrl(); } - - + + public String getRefererPermalink() { return this.pojo.getRefererPermalink(); } - - + + public String getRequestUrl() { return this.pojo.getRequestUrl(); } - - + + public String getTitle() { return this.pojo.getTitle(); } - - + + public String getExcerpt() { return this.pojo.getExcerpt(); } - - + + public Boolean getVisible() { return this.pojo.getVisible(); } - - + + public Boolean getDuplicate() { return this.pojo.getDuplicate(); } - - + + public Integer getDayHits() { return this.pojo.getDayHits(); } - - + + public Integer getTotalHits() { return this.pojo.getTotalHits(); } - - + + public String getDisplayUrl(int maxWidth,boolean includeHits) { return this.pojo.getDisplayUrl(maxWidth,includeHits); } - - + + public String getUrl() { return this.pojo.getUrl(); } - - + + public String getDisplayUrl() { return this.pojo.getDisplayUrl(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogWrapper.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogWrapper.java index ce9c575529..a2df280cfb 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogWrapper.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/pojos/wrapper/WeblogWrapper.java @@ -40,52 +40,52 @@ * Pojo safety wrapper for Weblog objects. */ public class WeblogWrapper { - + // keep a reference to the wrapped pojo private final Weblog pojo; - + // url strategy to use for any url building private final URLStrategy urlStrategy; - - + + // this is private so that we can force the use of the .wrap(pojo) method private WeblogWrapper(Weblog toWrap, URLStrategy strat) { this.pojo = toWrap; this.urlStrategy = strat; } - - + + // wrap the given pojo if it is not null public static WeblogWrapper wrap(Weblog toWrap, URLStrategy strat) { if(toWrap != null) return new WeblogWrapper(toWrap, strat); - + return null; } - - + + public ThemeTemplateWrapper getPageByAction(String action) throws WebloggerException { return ThemeTemplateWrapper.wrap(this.pojo.getTheme().getTemplateByAction(action)); } - - + + public ThemeTemplateWrapper getPageByName(String name) throws WebloggerException { return ThemeTemplateWrapper.wrap(this.pojo.getTheme().getTemplateByName(name)); } - - + + public ThemeTemplateWrapper getPageByLink(String link) throws WebloggerException { return ThemeTemplateWrapper.wrap(this.pojo.getTheme().getTemplateByLink(link)); } - - + + public List getPages() throws WebloggerException { - + List initialCollection = this.pojo.getTheme().getTemplates(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -96,171 +96,171 @@ public List getPages() throws WebloggerException { wrappedCollection.add(i,ThemeTemplateWrapper.wrap((ThemeTemplate) it.next())); i++; } - + return wrappedCollection; } - - + + public String getId() { return this.pojo.getId(); } - - + + public String getHandle() { return this.pojo.getHandle(); } - - + + public String getName() { return StringEscapeUtils.escapeHtml(this.pojo.getName()); } - - + + public String getDescription() { return this.pojo.getDescription(); } - - + + public UserWrapper getCreator() { return UserWrapper.wrap(this.pojo.getCreator()); } - - + + public String getDefaultPageId() { return this.pojo.getDefaultPageId(); } - - + + public String getWeblogDayPageId() { return this.pojo.getWeblogDayPageId(); } - - + + public Boolean getEnableBloggerApi() { return this.pojo.getEnableBloggerApi(); } - - + + public WeblogCategoryWrapper getBloggerCategory() { return WeblogCategoryWrapper.wrap(this.pojo.getBloggerCategory(), urlStrategy); } - - + + public WeblogCategoryWrapper getDefaultCategory() { return WeblogCategoryWrapper.wrap(this.pojo.getDefaultCategory(), urlStrategy); } - - + + public String getEditorPage() { return this.pojo.getEditorPage(); } - - + + public String getBlacklist() { return this.pojo.getBlacklist(); } - - + + public Boolean getAllowComments() { return this.pojo.getAllowComments(); } - - + + public Boolean getDefaultAllowComments() { return this.pojo.getDefaultAllowComments(); } - - + + public int getDefaultCommentDays() { return this.pojo.getDefaultCommentDays(); } - - + + public Boolean getModerateComments() { return this.pojo.getModerateComments(); } - - + + public Boolean getEmailComments() { return this.pojo.getEmailComments(); } - - + + public String getEmailFromAddress() { return this.pojo.getEmailFromAddress(); } - - + + public String getEmailAddress() { return this.pojo.getEmailAddress(); } - - + + public String getEditorTheme() { return this.pojo.getEditorTheme(); } - - + + public String getLocale() { return this.pojo.getLocale(); } - - + + public String getTimeZone() { return this.pojo.getTimeZone(); } - - + + public Date getDateCreated() { return this.pojo.getDateCreated(); } - - + + public String getDefaultPlugins() { return this.pojo.getDefaultPlugins(); } - - + + public Locale getLocaleInstance() { return this.pojo.getLocaleInstance(); } - - + + public TimeZone getTimeZoneInstance() { return this.pojo.getTimeZoneInstance(); } - - + + public int getEntryDisplayCount() { return this.pojo.getEntryDisplayCount(); } - - + + public Boolean getEnabled() { return this.pojo.getEnabled(); } - - + + public Boolean getActive() { return this.pojo.getActive(); } - - + + public Date getLastModified() { return this.pojo.getLastModified(); } - - + + public boolean isEnableMultiLang() { return this.pojo.isEnableMultiLang(); } - - + + public boolean isShowAllLangs() { return this.pojo.isShowAllLangs(); } - - + + public String getStylesheet() throws WebloggerException { // custom stylesheet comes from the weblog theme if(this.pojo.getTheme().getStylesheet() != null) { @@ -268,8 +268,8 @@ public String getStylesheet() throws WebloggerException { } return null; } - - + + /** * Get path to weblog icon image if defined. * @@ -279,12 +279,12 @@ public String getStylesheet() throws WebloggerException { * build the full url to that resource and return it. */ public String getIcon() { - + String iconPath = this.pojo.getIconPath(); if(iconPath == null) { return null; } - + if(iconPath.startsWith("http") || iconPath.startsWith("/")) { // if icon path is a relative path then assume it's a weblog resource return iconPath; @@ -292,34 +292,34 @@ public String getIcon() { // otherwise it's just a plain old url return urlStrategy.getWeblogResourceURL(this.pojo, iconPath, false); } - + } - - + + public String getAbout() { return this.pojo.getAbout(); } - - - + + + public String getURL() { return this.pojo.getURL(); } - - + + public String getAbsoluteURL() { return this.pojo.getAbsoluteURL(); } - - + + public WeblogEntryWrapper getWeblogEntry(String anchor) { return WeblogEntryWrapper.wrap(this.pojo.getWeblogEntry(anchor), urlStrategy); } - - + + public List getWeblogCategories() { Set initialCollection = this.pojo.getWeblogCategories(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -330,14 +330,14 @@ public List getWeblogCategories() { wrappedCollection.add(i,WeblogCategoryWrapper.wrap((WeblogCategory) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public List getWeblogCategories(String categoryPath) { Set initialCollection = this.pojo.getWeblogCategories(categoryPath); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -348,19 +348,19 @@ public List getWeblogCategories(String categoryPath) { wrappedCollection.add(i,WeblogCategoryWrapper.wrap((WeblogCategory) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public WeblogCategoryWrapper getWeblogCategory(String categoryPath) { return WeblogCategoryWrapper.wrap(this.pojo.getWeblogCategory(categoryPath), urlStrategy); } - - + + public List getRecentWeblogEntries(String cat,int length) { List initialCollection = this.pojo.getRecentWeblogEntries(cat,length); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -371,14 +371,14 @@ public List getRecentWeblogEntries(String cat,int length) { wrappedCollection.add(i,WeblogEntryWrapper.wrap((WeblogEntry) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public List getRecentWeblogEntriesByTag(String tag,int length) { List initialCollection = this.pojo.getRecentWeblogEntriesByTag(tag,length); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -389,14 +389,14 @@ public List getRecentWeblogEntriesByTag(String tag,int length) { wrappedCollection.add(i,WeblogEntryWrapper.wrap((WeblogEntry) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public List getRecentComments(int length) { List initialCollection = this.pojo.getRecentComments(length); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -407,19 +407,19 @@ public List getRecentComments(int length) { wrappedCollection.add(i,WeblogEntryCommentWrapper.wrap((WeblogEntryComment) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public WeblogBookmarkFolderWrapper getBookmarkFolder(String folderName) { return WeblogBookmarkFolderWrapper.wrap(this.pojo.getBookmarkFolder(folderName)); } - - + + public List getTodaysReferrers() { List initialCollection = this.pojo.getTodaysReferrers(); - + // iterate through and wrap // we force the use of an ArrayList because it should be good enough to cover // for any Collection type we encounter. @@ -430,31 +430,31 @@ public List getTodaysReferrers() { wrappedCollection.add(i,WeblogReferrerWrapper.wrap((WeblogReferrer) it.next(), urlStrategy)); i++; } - + return wrappedCollection; } - - + + public int getTodaysHits() { return this.pojo.getTodaysHits(); } - + // TODO: needs wrapping public List getPopularTags(int sinceDays,int length) { return this.pojo.getPopularTags(sinceDays,length); } - - + + public long getCommentCount() { return this.pojo.getCommentCount(); } - - + + public long getEntryCount() { return this.pojo.getEntryCount(); } - - + + /** * this is a special method to access the original pojo * we don't really want to do this, but it's necessary @@ -464,5 +464,5 @@ public long getEntryCount() { public Weblog getPojo() { return this.pojo; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/Blacklist.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/Blacklist.java index 615621fc89..34924dbfc2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/Blacklist.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/Blacklist.java @@ -48,55 +48,55 @@ * Loads MT-Blacklist style blacklist from disk and allows callers to test * strings against the blacklist and (optionally) addition blacklists. *
      - * First looks for blacklist.txt in uploads directory, than in classpath + * First looks for blacklist.txt in uploads directory, than in classpath * as /blacklist.txt. Download from web feature disabed. *
      - * Blacklist is formatted one entry per line. - * Any line that begins with # is considered to be a comment. - * Any line that begins with ( is considered to be a regex expression. + * Blacklist is formatted one entry per line. + * Any line that begins with # is considered to be a comment. + * Any line that begins with ( is considered to be a regex expression. *
      * For more information on the (discontinued) MT-Blacklist service: - * http://www.jayallen.org/projects/mt-blacklist. + * http://www.jayallen.org/projects/mt-blacklist. * * @author Lance Lavandowska * @author Allen Gilliland */ public class Blacklist { - + private static Log mLogger = LogFactory.getLog(Blacklist.class); - + private static Blacklist blacklist; private static final String blacklistFile = "blacklist.txt"; private static final String lastUpdateStr = "Last update:"; /** We no longer have a blacklist update URL */ - private static final String blacklistURL = null; + private static final String blacklistURL = null; private Date lastModified = null; private List blacklistStr = new LinkedList(); private List blacklistRegex = new LinkedList(); - + // setup our singleton at class loading time static { mLogger.info("Initializing MT Blacklist"); blacklist = new Blacklist(); blacklist.loadBlacklistFromFile(null); } - + /** Hide constructor */ private Blacklist() { } - + /** Singleton factory method. */ public static Blacklist getBlacklist() { return blacklist; } - + /** Updated MT blacklist if necessary. */ public static void checkForUpdate() { getBlacklist().update(); } - + /** Non-Static update method. */ public void update() { if (this.blacklistURL != null) { @@ -106,42 +106,42 @@ public void update() { } } } - + /** Download the MT blacklist from the web to our uploads directory. */ private boolean downloadBlacklist() { - + boolean blacklist_updated = false; try { mLogger.debug("Attempting to download MT blacklist"); - + URL url = new URL(blacklistURL); - HttpURLConnection connection = + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - + // after spending way too much time debugging i've discovered // that the blacklist server is selective based on the User-Agent // header. without this header set i always get a 403 response :( connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - + if (this.lastModified != null) { connection.setRequestProperty("If-Modified-Since", DateUtil.formatRfc822(this.lastModified)); } - + int responseCode = connection.getResponseCode(); - + mLogger.debug("HttpConnection response = "+responseCode); - + // did the connection return NotModified? If so, no need to parse if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { mLogger.debug("MT blacklist site says we are current"); return false; } - + // did the connection return a LastModified header? - long lastModifiedLong = + long lastModifiedLong = connection.getHeaderFieldDate("Last-Modified", -1); - + // if the file is newer than our current then we need do update it if (responseCode == HttpURLConnection.HTTP_OK && (this.lastModified == null || @@ -149,40 +149,40 @@ private boolean downloadBlacklist() { mLogger.debug("my last modified = "+this.lastModified.getTime()); mLogger.debug("MT last modified = "+lastModifiedLong); - + // save the new blacklist InputStream instream = connection.getInputStream(); - + String uploadDir = WebloggerConfig.getProperty("uploads.dir"); String path = uploadDir + File.separator + blacklistFile; FileOutputStream outstream = new FileOutputStream(path); - + mLogger.debug("writing updated MT blacklist to "+path); - + // read from url and write to file byte[] buf = new byte[4096]; int length = 0; while((length = instream.read(buf)) > 0) outstream.write(buf, 0, length); - + outstream.close(); instream.close(); - + blacklist_updated = true; - + mLogger.debug("MT blacklist download completed."); - + } else { mLogger.debug("blacklist *NOT* saved, assuming we are current"); } - + } catch (Exception e) { mLogger.error("error downloading blacklist", e); } - + return blacklist_updated; } - + /** * Load the MT blacklist from the file system. * We look for a previously downloaded version of the blacklist first and @@ -190,7 +190,7 @@ private boolean downloadBlacklist() { * Only public for purposes of unit testing. */ public void loadBlacklistFromFile(String blacklistFilePath) { - + InputStream txtStream = null; try { String path = blacklistFilePath; @@ -199,25 +199,25 @@ public void loadBlacklistFromFile(String blacklistFilePath) { path = uploadDir + File.separator + blacklistFile; } File blacklistFile = new File(path); - + // check our lastModified date to see if we need to re-read the file if (this.lastModified != null && - this.lastModified.getTime() >= blacklistFile.lastModified()) { + this.lastModified.getTime() >= blacklistFile.lastModified()) { mLogger.debug("Blacklist is current, no need to load again"); return; } else { this.lastModified = new Date(blacklistFile.lastModified()); - } - txtStream = new FileInputStream(blacklistFile); + } + txtStream = new FileInputStream(blacklistFile); mLogger.info("Loading blacklist from "+path); - + } catch (Exception e) { // Roller keeps a copy in the webapp just in case - txtStream = getClass().getResourceAsStream("/blacklist.txt"); + txtStream = getClass().getResourceAsStream("/blacklist.txt"); mLogger.warn( "Couldn't find downloaded blacklist, loaded blacklist.txt from classpath instead"); } - + if (txtStream != null) { readFromStream(txtStream, false); } else { @@ -227,7 +227,7 @@ public void loadBlacklistFromFile(String blacklistFilePath) { mLogger.info("Number of blacklist string rules: "+blacklistStr.size()); mLogger.info("Number of blacklist regex rules: "+blacklistRegex.size()); } - + /** * Read in the InputStream for rules. * @param txtStream @@ -245,7 +245,7 @@ private String readFromStream(InputStream txtStream, boolean saveStream) { } else { readRule(line); } - + if (saveStream) buf.append(line).append("\n"); } } catch (Exception e) { @@ -259,18 +259,18 @@ private String readFromStream(InputStream txtStream, boolean saveStream) { } return buf.toString(); } - + private void readRule(String str) { if (StringUtils.isEmpty(str)) return; // bad condition - + String rule = str.trim(); - + if (str.indexOf("#") > 0) // line has a comment { int commentLoc = str.indexOf("#"); rule = str.substring(0, commentLoc-1).trim(); // strip comment } - + if (rule.indexOf( "(" ) > -1) // regex rule { // pre-compile patterns since they will be frequently used @@ -279,7 +279,7 @@ private void readRule(String str) { blacklistStr.add(rule); } } - + /** Read comment and try to parse out "Last update" value */ private void readComment(String str) { int lastUpdatePos = str.indexOf(lastUpdateStr); @@ -294,20 +294,20 @@ private void readComment(String str) { } } } - - /** - * Does the String argument match any of the rules in the built-in blacklist? + + /** + * Does the String argument match any of the rules in the built-in blacklist? */ public boolean isBlacklisted(String str) { return isBlacklisted(str, null, null); } - - /** + + /** * Does the String argument match any of the rules in the built-in blacklist * plus additional blacklists provided by caller? * @param str String to be checked against blacklist * @param moreStringRules Additional string rules to consider - * @param moreRegexRules Additional regex rules to consider + * @param moreRegexRules Additional regex rules to consider */ public boolean isBlacklisted( String str, List moreStringRules, List moreRegexRules) { @@ -316,7 +316,7 @@ public boolean isBlacklisted( // First iterate over blacklist, doing indexOf. // Then iterate over blacklistRegex and test. // As soon as there is a hit in either case return true - + // test plain String.indexOf List stringRules = blacklistStr; if (moreStringRules != null && moreStringRules.size() > 0) { @@ -325,7 +325,7 @@ public boolean isBlacklisted( stringRules.addAll(blacklistStr); } if (testStringRules(str, stringRules)) return true; - + // test regex blacklisted List regexRules = blacklistRegex; if (moreRegexRules != null && moreRegexRules.size() > 0) { @@ -334,20 +334,20 @@ public boolean isBlacklisted( regexRules.addAll(blacklistRegex); } return testRegExRules(str, regexRules); - } + } - /** + /** * Test string only against rules provided by caller, NOT against built-in blacklist. * @param str String to be checked against rules * @param moreStringRules String rules to consider - * @param moreRegexRules Regex rules to consider + * @param moreRegexRules Regex rules to consider */ public static boolean matchesRulesOnly( String str, List stringRules, List regexRules) { if (testStringRules(str, stringRules)) return true; - return testRegExRules(str, regexRules); + return testRegExRules(str, regexRules); } - + /** Test String against the RegularExpression rules. */ private static boolean testRegExRules(String str, List regexRules) { boolean hit = false; @@ -355,12 +355,12 @@ private static boolean testRegExRules(String str, List regexRules) { Iterator iter = regexRules.iterator(); while (iter.hasNext()) { testPattern = (Pattern)iter.next(); - + // want to see what it is matching on, but only in debug mode if (mLogger.isDebugEnabled()) { Matcher matcher = testPattern.matcher(str); if (matcher.find()) { - mLogger.debug(matcher.group() + mLogger.debug(matcher.group() + " matched by " + testPattern.pattern()); return true; } @@ -386,7 +386,7 @@ private static boolean testRegExRules(String str, List regexRules) { */ private static boolean testStringRules(String source, List rules) { boolean matches = false; - + for (Object ruleObj : rules) { String rule; rule = (String) ruleObj; @@ -425,10 +425,10 @@ private static boolean testStringRules(String source, List rules) { } } } - + return matches; - } - + } + /** Utility method to populate lists based a blacklist in string form */ public static void populateSpamRules( String blacklist, List stringRules, List regexRules, String addendum) { @@ -444,9 +444,9 @@ public static void populateSpamRules( } else { stringRules.add(token); } - } + } } - + /** Return pretty list of String and RegEx rules. */ public String toString() { StringBuffer buf = new StringBuffer("blacklist "); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/BlacklistChecker.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/BlacklistChecker.java index 2796af2ab1..0e2e07655a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/BlacklistChecker.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/BlacklistChecker.java @@ -31,11 +31,11 @@ * @author Lance Lavandowska * @author Dave Johnson */ -public class BlacklistChecker { +public class BlacklistChecker { private static Log mLogger = LogFactory.getLog(BlacklistChecker.class); - - /** - * Test comment, applying all blacklists, if configured + + /** + * Test comment, applying all blacklists, if configured * @return True if comment matches blacklist term */ public static boolean checkComment(WeblogEntryComment comment) { @@ -44,9 +44,9 @@ public static boolean checkComment(WeblogEntryComment comment) { } return false; } - - /** - * Test trackback comment, applying all blacklists, if configured + + /** + * Test trackback comment, applying all blacklists, if configured * @return True if comment matches blacklist term */ public static boolean checkTrackback(WeblogEntryComment comment) { @@ -56,8 +56,8 @@ public static boolean checkTrackback(WeblogEntryComment comment) { return false; } - /** - * Test referrer URL, applying blacklist and website blacklist only if configured + /** + * Test referrer URL, applying blacklist and website blacklist only if configured * @return True if comment matches blacklist term */ public static boolean checkReferrer(Weblog website, String referrerURL) { @@ -75,8 +75,8 @@ public static boolean checkReferrer(Weblog website, String referrerURL) { return false; } - /** - * Test comment against built in blacklist, site blacklist and website blacklist + /** + * Test comment against built in blacklist, site blacklist and website blacklist * @return True if comment matches blacklist term */ private static boolean testComment(WeblogEntryComment c) { @@ -85,7 +85,7 @@ private static boolean testComment(WeblogEntryComment c) { List regexRules = new ArrayList(); Weblog website = c.getWeblogEntry().getWebsite(); Blacklist.populateSpamRules( - website.getBlacklist(), stringRules, regexRules, + website.getBlacklist(), stringRules, regexRules, WebloggerRuntimeConfig.getProperty("spam.blacklist")); Blacklist blacklist = Blacklist.getBlacklist(); if ( blacklist.isBlacklisted(c.getUrl(), stringRules, regexRules) @@ -95,6 +95,6 @@ private static boolean testComment(WeblogEntryComment c) { ret = true; } return ret; - } + } } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/GenericThrottle.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/GenericThrottle.java index ec60d1e01b..cda2f8b91b 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/GenericThrottle.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/GenericThrottle.java @@ -34,45 +34,45 @@ * considered to be abusive. */ public class GenericThrottle { - + private static Log log = LogFactory.getLog(GenericThrottle.class); - + // threshold and interval to determine who is abusive private int threshold = 1; private int interval = 0; - + // a cache to maintain the data Cache clientHistoryCache = null; - - + + public GenericThrottle(int thresh, int inter, int maxEntries) { - + // threshold can't be negative, that would mean everyone is abusive if(thresh > -1) { this.threshold = thresh; } - + // interval must be a positive value if(inter > 0) { this.interval = inter; } - + // max entries must be a positive value if(maxEntries < 0) { maxEntries = 1; } - + // cache props Map cacheProps = new HashMap(); cacheProps.put("id", "throttle"); cacheProps.put("size", ""+maxEntries); cacheProps.put("timeout", ""+this.interval); - + // get cache instance. handler is null cuz we don't want to register it this.clientHistoryCache = CacheManager.constructCache(null, cacheProps); } - - + + /** * Process a new hit from the client. * @@ -83,53 +83,53 @@ public GenericThrottle(int thresh, int inter, int maxEntries) { * @retuns true if client is abusive, false otherwise */ public boolean processHit(String clientId) { - + if(clientId == null) { return false; } - + // see if we have any info about this client yet ClientInfo client = null; ExpiringCacheEntry cacheEntry = (ExpiringCacheEntry) this.clientHistoryCache.get(clientId); if(cacheEntry != null) { log.debug("HIT "+clientId); client = (ClientInfo) cacheEntry.getValue(); - + // this means entry had expired if(client == null) { log.debug("EXPIRED "+clientId); this.clientHistoryCache.remove(clientId); } } - - // if we already know this client then update their hit count and + + // if we already know this client then update their hit count and // see if they have surpassed the threshold if(client != null) { client.hits++; - + log.debug("STATUS "+clientId+" - "+client.hits+" hits since "+client.start); - + // abusive client if(client.hits > this.threshold) { return true; } - + } else { log.debug("NEW "+clientId); - + // first timer ClientInfo newClient = new ClientInfo(); newClient.hits = 1; newClient.id = clientId; - + ExpiringCacheEntry newEntry = new ExpiringCacheEntry(newClient, this.interval); this.clientHistoryCache.put(clientId, newEntry); } - + return false; } - - + + /** * Check the current status of a client. * @@ -139,40 +139,40 @@ public boolean processHit(String clientId) { * @return true if client is abusive, false otherwise. */ public boolean isAbusive(String clientId) { - + if(clientId == null) { return false; } - + // see if we have any info about this client ClientInfo client = null; ExpiringCacheEntry cacheEntry = (ExpiringCacheEntry) this.clientHistoryCache.get(clientId); if(cacheEntry != null) { log.debug("HIT "+clientId); client = (ClientInfo) cacheEntry.getValue(); - + // this means entry had expired if(client == null) { log.debug("EXPIRED "+clientId); this.clientHistoryCache.remove(clientId); } } - + if(client != null) { return (client.hits > this.threshold); } else { return false; } } - - + + // just something to keep a few properties in private class ClientInfo { - + public String id = null; public int hits = 0; public java.util.Date start = new java.util.Date(); - + } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nMessages.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nMessages.java index 0375cc99e0..c153c97bea 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nMessages.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nMessages.java @@ -36,87 +36,87 @@ * A utility class for handling i18n messaging. */ public class I18nMessages { - + private static final Log log = LogFactory.getLog(I18nMessages.class); - + // locale and bundle we are using for messaging private final Locale locale; private final ResourceBundle bundle; - + // a map of cached messages instances, keyed by locale - private static Map messagesMap = + private static Map messagesMap = Collections.synchronizedMap(new HashMap()); - - + + private I18nMessages(String locale) { Locale loc = I18nUtils.toLocale(locale); this.locale = loc; this.bundle = ResourceBundle.getBundle("ApplicationResources", loc); } - + private I18nMessages(Locale locale) { this.locale = locale; this.bundle = ResourceBundle.getBundle("ApplicationResources", locale); } - - + + /** * Get an instance for a given locale. */ public static I18nMessages getMessages(String locale) { - + log.debug("request for messages in locale = "+locale); - + // check if we already have a message utils created for that locale I18nMessages messages = messagesMap.get(locale); - + // if no utils for that language yet then construct if(messages == null) { messages = new I18nMessages(locale); - + // keep a reference to it messagesMap.put(messages.getLocale(), messages); } - + return messages; } - - + + /** * Get an instance for a given locale. */ public static I18nMessages getMessages(Locale locale) { - + log.debug("request for messages in locale = "+locale.toString()); - + // check if we already have a message utils created for that locale I18nMessages messages = messagesMap.get(locale); - + // if no utils for that language yet then construct if(messages == null) { messages = new I18nMessages(locale); - + // keep a reference to it messagesMap.put(messages.getLocale(), messages); } - + return messages; } - - + + /** * The locale representing this message utils. */ public final Locale getLocale() { return this.locale; } - - + + /** * Get a message from the bundle. */ public final String getString(String key) { - + try { return bundle.getString(key); } catch (Exception e) { @@ -125,14 +125,14 @@ public final String getString(String key) { return key; } } - - + + /** * Get a message from the bundle and substitute the given args into * the message contents. */ public final String getString(String key, List args) { - + try { String msg = bundle.getString(key); return MessageFormat.format(msg, args.toArray()); @@ -142,14 +142,14 @@ public final String getString(String key, List args) { return key; } } - - + + /** * Get a message from the bundle and substitute the given args into * the message contents. */ public final String getString(String key, Object[] args) { - + try { String msg = bundle.getString(key); return MessageFormat.format(msg, args); @@ -159,10 +159,10 @@ public final String getString(String key, Object[] args) { return key; } } - + /** * Reload bundle. - * + * * @param key * the key */ @@ -191,7 +191,7 @@ public static final void reloadBundle(Locale key) { /** * Clear tomcat cache. - * + * * @see com.opensymphony.xwork2.util.LocalizedTextUtil */ private static void clearTomcatCache() { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nUtils.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nUtils.java index 4bada395f0..984a4e387d 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nUtils.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/I18nUtils.java @@ -26,7 +26,7 @@ * A utility class for dealing with i18n. */ public final class I18nUtils { - + public static final Locale toLocale(String locale) { if (locale != null) { String[] localeStr = StringUtils.split(locale,"_"); @@ -46,5 +46,5 @@ public static final Locale toLocale(String locale) { } return Locale.getDefault(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/IPBanList.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/IPBanList.java index b205981865..b7e696a791 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/IPBanList.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/IPBanList.java @@ -37,73 +37,73 @@ * automatically re-read the file and update the list when that happens. */ public class IPBanList { - + private static Log log = LogFactory.getLog(IPBanList.class); - + // set of ips that are banned, use a set to ensure uniqueness private Set bannedIps = new HashSet(); - + // file listing the ips that are banned private ModifiedFile bannedIpsFile = null; - + // reference to our singleton instance private static IPBanList instance = null; - - + + static { instance = new IPBanList(); } - - + + // private because we are a singleton private IPBanList() { - + log.debug("INIT"); - + // load up set of denied ips String banIpsFilePath = WebloggerConfig.getProperty("ipbanlist.file"); if(banIpsFilePath != null) { ModifiedFile banIpsFile = new ModifiedFile(banIpsFilePath); - + if(banIpsFile.exists() && banIpsFile.canRead()) { this.bannedIpsFile = banIpsFile; this.loadBannedIps(); } } } - - + + // access to the singleton instance public static IPBanList getInstance() { return instance; } - - + + public boolean isBanned(String ip) { - + // update the banned ips list if needed this.loadBannedIpsIfNeeded(false); - + if(ip != null) { return this.bannedIps.contains(ip); } else { return false; } } - - + + public void addBannedIp(String ip) { - + if(ip == null) { return; } - + // update the banned ips list if needed this.loadBannedIpsIfNeeded(false); - - if(!this.bannedIps.contains(ip) && + + if(!this.bannedIps.contains(ip) && (bannedIpsFile != null && bannedIpsFile.canWrite())) { - + try { synchronized(this) { // add to file @@ -111,76 +111,76 @@ public void addBannedIp(String ip) { out.println(ip); out.close(); this.bannedIpsFile.clearChanged(); - + // add to Set this.bannedIps.add(ip); } - + log.debug("ADDED "+ip); } catch(Exception e) { log.error("Error adding banned ip to file", e); } } } - - + + /** * Check if the banned ips file has changed and needs to be reloaded. */ private void loadBannedIpsIfNeeded(boolean forceLoad) { - - if(bannedIpsFile != null && + + if(bannedIpsFile != null && (bannedIpsFile.hasChanged() || forceLoad)) { - + // need to reload this.loadBannedIps(); } } - - + + /** * Load the list of banned ips from a file. This clears the old list and * loads exactly what is in the file. */ private synchronized void loadBannedIps() { - + if(bannedIpsFile != null) { - + try { HashSet newBannedIpList = new HashSet(); - + // TODO: optimize this BufferedReader in = new BufferedReader(new FileReader(this.bannedIpsFile)); - + String ip = null; while((ip = in.readLine()) != null) { newBannedIpList.add(ip); } - + in.close(); - + // list updated, reset modified file this.bannedIps = newBannedIpList; this.bannedIpsFile.clearChanged(); - + log.info(this.bannedIps.size()+" banned ips loaded"); } catch(Exception ex) { log.error("Error loading banned ips from file", ex); } - + } } - - - // a simple extension to the File class which tracks if the file has + + + // a simple extension to the File class which tracks if the file has // changed since the last time we checked private class ModifiedFile extends java.io.File { - + private long myLastModified = 0; - + public ModifiedFile(String filePath) { super(filePath); - + this.myLastModified = lastModified(); } @@ -191,10 +191,10 @@ public boolean hasChanged() { return false; } } - + public void clearChanged() { myLastModified = lastModified(); } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LRUCache2.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LRUCache2.java index 94d386a6d3..023fe7631a 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LRUCache2.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LRUCache2.java @@ -24,7 +24,7 @@ import java.util.Map; /** * LRU cache with per-entry timeout logic. - * + * * @author Dave Johnson */ public class LRUCache2 @@ -35,7 +35,7 @@ public class LRUCache2 /** * Create cache. - * + * * @param maxsize * Maximum number of entries in cache. * @param timeout @@ -50,7 +50,7 @@ public LRUCache2(int maxsize, long timeout) /** * Create cache that uses custom environment. - * + * * @param maxsize * Maximum number of entries in cache. * @param timeout @@ -157,7 +157,7 @@ public Object getValue() return value; } } - + // David Flanaghan: http://www.davidflanagan.com/blog/000014.html private static class LRULinkedHashMap extends LinkedHashMap { diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LinkbackExtractor.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LinkbackExtractor.java index e157512fa5..bfa93f93e8 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LinkbackExtractor.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/LinkbackExtractor.java @@ -45,7 +45,7 @@ /** * Parses HTML file for referring linkback title and excerpt. - * + * * @author David M Johnson */ public class LinkbackExtractor @@ -67,7 +67,7 @@ public class LinkbackExtractor //------------------------------------------------------------------------ /** * Extract referring page title, excerpt, and permalink. - * + * * @param refererUrl * @param requestUrl */ @@ -162,7 +162,7 @@ public Parser getParser() private void extractByParsingRss(String rssLink, String requestURL) throws IllegalArgumentException, MalformedURLException, FeedException, IOException { - SyndFeedInput feedInput = new SyndFeedInput(); + SyndFeedInput feedInput = new SyndFeedInput(); SyndFeed feed = feedInput.build( new InputStreamReader(new URL(rssLink).openStream())); Iterator itemIter = feed.getEntries().iterator(); @@ -211,7 +211,7 @@ private void extractByParsingRss(String rssLink, String requestURL) //------------------------------------------------------------------------ /** * Returns the excerpt. - * + * * @return String */ public String getExcerpt() @@ -222,7 +222,7 @@ public String getExcerpt() //------------------------------------------------------------------------ /** * Returns the title. - * + * * @return String */ public String getTitle() @@ -233,7 +233,7 @@ public String getTitle() //------------------------------------------------------------------------ /** * Returns the permalink. - * + * * @return String */ public String getPermalink() @@ -244,7 +244,7 @@ public String getPermalink() //------------------------------------------------------------------------ /** * Sets the permalink. - * + * * @param permalink * The permalink to set */ @@ -277,7 +277,7 @@ private final class LinkbackCallback extends ParserCallback /** * Look for divider tags and for the permalink. - * + * * @param tag * HTML tag * @param atts @@ -384,7 +384,7 @@ else if (!mRssLink.startsWith("http")) /** * Stop at the very first divider tag after the permalink. - * + * * @param tag * End tag * @param pos diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MailUtil.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MailUtil.java index e1b372a88b..25dffdfafc 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MailUtil.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MailUtil.java @@ -58,38 +58,38 @@ * A utility class for helping with sending emails. */ public class MailUtil { - + private static Log log = LogFactory.getLog(MailUtil.class); - + private static final String EMAIL_ADDR_REGEXP = "^.*@.*[.].{2,}$"; - - + + /** - * Ideally mail senders should call this first to avoid errors that occur - * when mail is not properly configured. We'll complain about that at + * Ideally mail senders should call this first to avoid errors that occur + * when mail is not properly configured. We'll complain about that at * startup, no need to complain on every attempt to send. */ public static boolean isMailConfigured() { - return WebloggerStartup.getMailProvider() != null; + return WebloggerStartup.getMailProvider() != null; } - + /** * Send an email notice that a new pending entry has been submitted. */ - public static void sendPendingEntryNotice(WeblogEntry entry) + public static void sendPendingEntryNotice(WeblogEntry entry) throws WebloggerException { - + Session mailSession = WebloggerStartup.getMailProvider() != null ? WebloggerStartup.getMailProvider().getSession() : null; if (mailSession == null) { throw new WebloggerException("Couldn't get mail Session"); } - + try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); - + String userName = entry.getCreator().getUserName(); String from = entry.getCreator().getEmailAddress(); String cc[] = new String[] {from}; @@ -97,26 +97,26 @@ public static void sendPendingEntryNotice(WeblogEntry entry) String to[]; String subject; String content; - + // list of enabled website authors and admins ArrayList reviewers = new ArrayList(); List websiteUsers = wmgr.getWeblogUsers(entry.getWebsite(), true); - + // build list of reviewers (website users with author permission) Iterator websiteUserIter = websiteUsers.iterator(); while (websiteUserIter.hasNext()) { User websiteUser = (User)websiteUserIter.next(); - if (entry.getWebsite().hasUserPermission( + if (entry.getWebsite().hasUserPermission( websiteUser, WeblogPermission.POST) && websiteUser.getEmailAddress() != null) { reviewers.add(websiteUser.getEmailAddress()); } } to = (String[])reviewers.toArray(new String[reviewers.size()]); - + // Figure URL to entry edit page String editURL = WebloggerFactory.getWeblogger().getUrlStrategy().getEntryEditURL(entry.getWebsite().getHandle(), entry.getId(), true); - + ResourceBundle resources = ResourceBundle.getBundle( "ApplicationResources", entry.getWebsite().getLocaleInstance()); StringBuffer sb = new StringBuffer(); @@ -141,15 +141,15 @@ public static void sendPendingEntryNotice(WeblogEntry entry) log.error("ERROR: Problem sending pending entry notification email."); } } - - + + /** * Send a weblog invitation email. */ - public static void sendWeblogInvitation(Weblog website, + public static void sendWeblogInvitation(Weblog website, User user) throws WebloggerException { - + Session mailSession = WebloggerStartup.getMailProvider() != null ? WebloggerStartup.getMailProvider().getSession() : null; @@ -157,10 +157,10 @@ public static void sendWeblogInvitation(Weblog website, throw new WebloggerException("ERROR: Notification email(s) not sent, " + "Roller's mail session not properly configured"); } - + try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - + String userName = user.getUserName(); String from = website.getEmailAddress(); String cc[] = new String[] {from}; @@ -168,11 +168,11 @@ public static void sendWeblogInvitation(Weblog website, String to[] = new String[] {user.getEmailAddress()}; String subject; String content; - + // Figure URL to entry edit page String rootURL = WebloggerRuntimeConfig.getAbsoluteContextURL(); String url = rootURL + "/roller-ui/menu.rol"; - + ResourceBundle resources = ResourceBundle.getBundle( "ApplicationResources", website.getLocaleInstance()); @@ -201,14 +201,14 @@ public static void sendWeblogInvitation(Weblog website, + "due to Roller configuration or mail server problem.", e); } } - - + + /** * Send a weblog invitation email. */ public static void sendUserActivationEmail(User user) throws WebloggerException { - + Session mailSession = WebloggerStartup.getMailProvider() != null ? WebloggerStartup.getMailProvider().getSession() : null; @@ -216,25 +216,25 @@ public static void sendUserActivationEmail(User user) throw new WebloggerException("ERROR: Notification email(s) not sent, " + "Roller's mail session not properly configured"); } - + try { ResourceBundle resources = ResourceBundle.getBundle( "ApplicationResources", I18nUtils.toLocale(user.getLocale())); - + String from = WebloggerRuntimeConfig.getProperty( "user.account.activation.mail.from"); - + String cc[] = new String[0]; String bcc[] = new String[0]; String to[] = new String[] { user.getEmailAddress() }; String subject = resources.getString( "user.account.activation.mail.subject"); String content; - + String rootURL = WebloggerRuntimeConfig.getAbsoluteContextURL(); - + StringBuffer sb = new StringBuffer(); - + // activationURL= String activationURL = rootURL + "/roller-ui/register!activate.rol?activationCode=" @@ -244,60 +244,60 @@ public static void sendUserActivationEmail(User user) new Object[] { user.getFullName(), user.getUserName(), activationURL })); content = sb.toString(); - + sendHTMLMessage(from, to, cc, bcc, subject, content); } catch (MessagingException e) { throw new WebloggerException("ERROR: Problem sending activation email.", e); } } - - + + /** * Send email notification of new or newly approved comment. * TODO: Make the addressing options configurable on a per-website basis. - * + * * @param commentObject The new comment - * @param messages Messages to be included in e-mail (or null). - * Errors will be assumed to be "validation errors" + * @param messages Messages to be included in e-mail (or null). + * Errors will be assumed to be "validation errors" * and messages will be assumed to be "from the system" */ public static void sendEmailNotification(WeblogEntryComment commentObject, - RollerMessages messages, + RollerMessages messages, I18nMessages resources, - boolean notifySubscribers) + boolean notifySubscribers) throws MailingException { - + WeblogEntry entry = commentObject.getWeblogEntry(); Weblog weblog = entry.getWebsite(); User user = entry.getCreator(); - + // Only send email if email notificaiton is enabled boolean notify = WebloggerRuntimeConfig.getBooleanProperty("users.comments.emailnotify"); if (!notify || !weblog.getEmailComments().booleanValue()) { // notifications disabled, just bail return; } - + log.debug("Comment notification enabled ... preparing email"); - + // Determine message and addressing options from init parameters boolean hideCommenterAddrs = WebloggerConfig.getBooleanProperty( "comment.notification.hideCommenterAddresses"); - + // use either the weblog configured from address or the site configured from address String from = weblog.getEmailFromAddress(); if(StringUtils.isEmpty(from)) { // TODO: this should not be the users email address from = user.getEmailAddress(); } - + // build list of email addresses to send notification to Set subscribers = new TreeSet(); - + // If we are to notify subscribers, then... if (notifySubscribers) { log.debug("Sending notification email to all subscribers"); - + // Get all the subscribers to this comment thread List comments = entry.getComments(true, true); for (Iterator it = comments.iterator(); it.hasNext();) { @@ -319,54 +319,54 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, } else { log.debug("Sending notification email only to weblog owner"); } - + // Form array of commenter addrs String[] commenterAddrs = (String[])subscribers.toArray(new String[0]); - + //------------------------------------------ // --- Form the messages to be sent - // Build separate owner and commenter (aka subscriber) messages - + // Determine with mime type to use for e-mail StringBuffer msg = new StringBuffer(); StringBuffer ownermsg = new StringBuffer(); boolean escapeHtml = !WebloggerRuntimeConfig.getBooleanProperty("users.comments.htmlenabled"); - + // first the commenter message - + if (!escapeHtml) { msg.append(""); } - + if (!StringUtils.isEmpty(commentObject.getName())) { msg.append(commentObject.getName() + " " + resources.getString("email.comment.wrote")+": "); } else { msg.append(resources.getString("email.comment.anonymous")+": "); } - + msg.append((escapeHtml) ? "\n\n" : "

      "); - + msg.append((escapeHtml) ? Utilities.escapeHTML(commentObject.getContent()) : Utilities.transformToHTMLSubset(Utilities.escapeHTML(commentObject.getContent()))); - + msg.append((escapeHtml) ? "\n\n----\n" : "


      "); msg.append(resources.getString("email.comment.respond") + ": "); msg.append((escapeHtml) ? "\n" : "
      "); - + // Build link back to comment String commentURL = WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogCommentsURL(weblog, null, entry.getAnchor(), true); - + if (escapeHtml) { msg.append(commentURL); } else { msg.append(""+commentURL+"
      "); } - + // next the owner message - + // First, list any messages from the system that were passed in: if (messages.getMessageCount() > 0) { ownermsg.append((escapeHtml) ? "" : "

      "); @@ -383,7 +383,7 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, if (messages.getMessageCount() > 0) { ownermsg.append((escapeHtml) ? "\n\n" : "

    "); } - + // Next, list any validation error messages that were passed in: if (messages.getErrorCount() > 0) { ownermsg.append((escapeHtml) ? "" : "

    "); @@ -400,20 +400,20 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, if (messages.getErrorCount() > 0) { ownermsg.append((escapeHtml) ? "\n\n" : ""); } - + ownermsg.append(msg); - + // add link to weblog edit page so user can login to manage comments ownermsg.append((escapeHtml) ? "\n\n----\n" : "


    "); ownermsg.append("Link to comment management page:"); ownermsg.append((escapeHtml) ? "\n" : "
    "); - + Map parameters = new HashMap(); parameters.put("bean.entryId", entry.getId()); String deleteURL = WebloggerFactory.getWeblogger().getUrlStrategy().getActionURL( "comments", "/roller-ui/authoring", weblog.getHandle(), parameters, true); - + if (escapeHtml) { ownermsg.append(deleteURL); } else { @@ -422,7 +422,7 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, msg.append(""); ownermsg.append(""); } - + String subject = null; if ((subscribers.size() > 1) || (StringUtils.equals(commentObject.getEmail(), user.getEmailAddress()))) { @@ -431,11 +431,11 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, subject = resources.getString("email.comment.title") + ": "; } subject += entry.getTitle(); - + // send message to email recipients try { boolean isHtml = !escapeHtml; - + // Send separate messages to owner and commenters if(isHtml) { sendHTMLMessage( @@ -454,28 +454,28 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, subject, ownermsg.toString()); } - + // now send to subscribers if (notifySubscribers && commenterAddrs.length > 0) { // If hiding commenter addrs, they go in Bcc: otherwise in the To: of the second message String[] to = hideCommenterAddrs ? null : commenterAddrs; String[] bcc = hideCommenterAddrs ? commenterAddrs : null; - + if(isHtml) { sendHTMLMessage( - from, - to, - null, - bcc, - subject, + from, + to, + null, + bcc, + subject, msg.toString()); } else { sendTextMessage( - from, - to, - null, - bcc, - subject, + from, + to, + null, + bcc, + subject, msg.toString()); } } @@ -486,18 +486,18 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, log.debug(e); } } - + log.debug("Done sending email message"); } - + public static void sendEmailApprovalNotifications(List comments, - I18nMessages resources) + I18nMessages resources) throws MailingException { - + RollerMessages messages = new RollerMessages(); - for (WeblogEntryComment comment : comments) { - + for (WeblogEntryComment comment : comments) { + // Send email notifications because a new comment has been approved sendEmailNotification(comment, messages, resources, true); @@ -505,45 +505,45 @@ public static void sendEmailApprovalNotifications(List comme sendEmailApprovalNotification(comment, resources); } } - - + + /** * Send message to author of approved comment * * TODO: Make the addressing options configurable on a per-website basis. */ - public static void sendEmailApprovalNotification(WeblogEntryComment cd, - I18nMessages resources) + public static void sendEmailApprovalNotification(WeblogEntryComment cd, + I18nMessages resources) throws MailingException { - + WeblogEntry entry = cd.getWeblogEntry(); Weblog weblog = entry.getWebsite(); User user = entry.getCreator(); - + // Only send email if email notificaiton is enabled boolean notify = WebloggerRuntimeConfig.getBooleanProperty("users.comments.emailnotify"); if (!notify || !weblog.getEmailComments().booleanValue()) { // notifications disabled, just bail return; } - + log.debug("Comment notification enabled ... preparing email"); - + // use either the weblog configured from address or the site configured from address String from = weblog.getEmailFromAddress(); if(StringUtils.isEmpty(from)) { // TODO: this should not be the users email address from = user.getEmailAddress(); } - + // form the message to be sent String subject = resources.getString("email.comment.commentApproved"); - + StringBuffer msg = new StringBuffer(); msg.append(resources.getString("email.comment.commentApproved")); msg.append("\n\n"); msg.append(WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogCommentsURL(weblog, null, entry.getAnchor(), true)); - + // send message to author of approved comment try { sendTextMessage( @@ -560,13 +560,13 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, log.debug(e); } } - + log.debug("Done sending email message"); } - - + + // agangolli: Incorporated suggested changes from Ken Blackler. - + /** * This method is used to send a Message with a pre-defined * mime-type. @@ -589,45 +589,45 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, String mimeType ) throws MessagingException { - + MailProvider mailProvider = WebloggerStartup.getMailProvider(); if (mailProvider == null) { return; } - + Session session = mailProvider.getSession(); Message message = new MimeMessage(session); - + // n.b. any default from address is expected to be determined by caller. if (! StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (log.isDebugEnabled()) log.debug("e-mail from: " + sentFrom); } - + if (to!=null) { InternetAddress[] sendTo = new InternetAddress[to.length]; - + for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (log.isDebugEnabled()) log.debug("sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } - + if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; - + for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (log.isDebugEnabled()) log.debug("copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } - + if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; - + for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (log.isDebugEnabled()) log.debug("blind copying e-mail to: " + bcc[i]); @@ -637,18 +637,18 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, message.setSubject((subject == null) ? "(no subject)" : subject); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); - + // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; - + SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); - + Transport transport = mailProvider.getTransport(); - + // Try to send while there remain some potentially good addresses - try { + try { do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; @@ -664,15 +664,15 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, remainingAddresses=ex.getValidUnsentAddresses(); } } while (remainingAddresses!=null && remainingAddresses.length>0 && remainingAddresses.length!=nAddresses); - + } finally { transport.close(); } - + if (bFailedToSome) throw sendex; } - - + + /** * This method is used to send a Text Message. * @@ -694,8 +694,8 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, throws MessagingException { sendMessage(from, to, cc, bcc, subject, content, "text/plain; charset=utf-8"); } - - + + /** * This method overrides the sendTextMessage to specify * one receiver and mulitple cc recipients. @@ -718,11 +718,11 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, throws MessagingException { String[] recipient = null; if (to!=null) recipient = new String[] {to}; - + sendMessage(from, recipient, cc, bcc, subject, content, "text/plain; charset=utf-8"); } - - + + /** * This method overrides the sendTextMessage to specify * only one receiver and cc recipients, rather than @@ -748,15 +748,15 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, String[] recipient = null; String[] copy = null; String[] bcopy = null; - + if (to!=null) recipient = new String[] {to}; if (cc!=null) copy = new String[] {cc}; if (bcc!=null) bcopy = new String[] {bcc}; - + sendMessage(from, recipient, copy, bcopy, subject, content, "text/plain; charset=utf-8"); } - - + + /** * This method is used to send a HTML Message * @@ -778,8 +778,8 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, throws MessagingException { sendMessage(from, to, cc, bcc, subject, content, "text/html; charset=utf-8"); } - - + + /** * This method overrides the sendHTMLMessage to specify * only one sender, rather than an array of senders. @@ -803,15 +803,15 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, String[] recipient = null; String[] copy = null; String[] bcopy = null; - + if (to!=null) recipient = new String[] {to}; if (cc!=null) copy = new String[] {cc}; if (bcc!=null) bcopy = new String[] {bcc}; - + sendMessage(from, recipient, copy, bcopy, subject, content, "text/html; charset=utf-8"); } - - + + /** * This method overrides the sendHTMLMessage to specify * one receiver and mulitple cc recipients. @@ -835,11 +835,11 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, throws MessagingException { String[] recipient = null; if (to!=null) recipient = new String[] {to}; - + sendMessage(from, recipient, cc, bcc, subject, content, "text/html; charset=utf-8"); } - - + + /** * An exception thrown if there is a problem sending an email. */ diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastException.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastException.java index b9621ccb69..27aec463cb 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastException.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastException.java @@ -25,24 +25,24 @@ * An exception thrown when dealing with Mediacast files. */ public class MediacastException extends WebloggerException { - + private int errorCode = 0; private String errorKey = null; - - + + public MediacastException(int code, String msgKey) { this.errorCode = code; this.errorKey = msgKey; } - - + + public MediacastException(int code, String msgKey, Throwable t) { super(t); this.errorCode = code; this.errorKey = msgKey; } - - + + public int getErrorCode() { return errorCode; } @@ -50,7 +50,7 @@ public int getErrorCode() { public String getErrorKey() { return errorKey; } - + public void setErrorCode(int errorCode) { this.errorCode = errorCode; } @@ -58,5 +58,5 @@ public void setErrorCode(int errorCode) { public void setErrorKey(String errorKey) { this.errorKey = errorKey; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastResource.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastResource.java index 9c8bf0fca5..41ac303a5c 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastResource.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastResource.java @@ -26,19 +26,19 @@ * in postings via enclosures. */ public class MediacastResource { - + private String url = null; private String contentType = null; private long length = 0; - - + + public MediacastResource(String u, String c, long l) { this.setUrl(u); this.setContentType(c); this.setLength(l); } - + public String getUrl() { return url; } @@ -62,16 +62,16 @@ public long getLength() { public void setLength(long length) { this.length = length; } - - + + public String toString() { StringBuffer buf = new StringBuffer(); - + buf.append("url = ").append(getUrl()).append("\n"); buf.append("contentType = ").append(getContentType()).append("\n"); buf.append("length = ").append(getLength()).append("\n"); - + return buf.toString(); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastUtil.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastUtil.java index ac1b0996a1..5cbecf80b9 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastUtil.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/MediacastUtil.java @@ -32,51 +32,51 @@ * Utility for deailing with mediacast files. */ public final class MediacastUtil { - + private static final Log log = LogFactory.getLog(MediacastUtil.class); - + public static final int BAD_URL = 1; public static final int CHECK_FAILED = 2; public static final int BAD_RESPONSE = 3; public static final int INCOMPLETE = 4; - - + + // non-instantiable private MediacastUtil() {} - - + + /** * Validate a Mediacast resource. */ - public static final MediacastResource lookupResource(String url) + public static final MediacastResource lookupResource(String url) throws MediacastException { - + if(url == null || url.trim().length() ==0) { return null; } - + MediacastResource resource = null; try { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); int response = con.getResponseCode(); String message = con.getResponseMessage(); - + if(response != 200) { log.debug("Mediacast error "+response+":"+message+" from url "+url); throw new MediacastException(BAD_RESPONSE, "weblogEdit.mediaCastResponseError"); } else { String contentType = con.getContentType(); long length = con.getContentLength(); - + if(contentType == null || length == -1) { log.debug("Response valid, but contentType or length is invalid"); throw new MediacastException(INCOMPLETE, "weblogEdit.mediaCastLacksContentTypeOrLength"); } - + resource = new MediacastResource(url, contentType, length); log.debug("Valid mediacast resource = "+resource.toString()); - + } } catch (MalformedURLException mfue) { log.debug("Malformed MediaCast url: " + url); @@ -84,8 +84,8 @@ public static final MediacastResource lookupResource(String url) } catch (Exception e) { log.error("ERROR while checking MediaCast URL: " + url + ": " + e.getMessage()); throw new MediacastException(CHECK_FAILED, "weblogEdit.mediaCastFailedFetchingInfo", e); - } + } return resource; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/PasswordUtility.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/PasswordUtility.java index 6e7fc41493..c6c97310f3 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/PasswordUtility.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/PasswordUtility.java @@ -30,20 +30,20 @@ /** * Roller password utility: don't run this unless you know what you are doing!
    - * + * *

    Configuration:
    - * + * * Program looks in current directory for db.properties file with database - * connection properties driverClassName and connectionUrl. - * + * connection properties driverClassName and connectionUrl. + * * Program expects JDBC driver jar to be on classpath.

    - * + * *

    Usage:
    - * + * * java -cp ./WEB-INF/lib/rollerbeans.jar;./jdbc.jar org.apache.roller.weblogger.business.utils.PasswordUtility
    - * + * *
    Options:
    - * + * * -save <file-name>: Save username/passwords in property file
    * -encrypt : turn on encryption and encrypt passwords
    * -restore <file-name> : turn off encryption and restore passwords from file
    @@ -51,42 +51,42 @@ * -grant_admin <username>
    * -revoke_admin <username>

    */ -public class PasswordUtility +public class PasswordUtility { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.load(new FileInputStream("rollerdb.properties")); - + String algorithm = props.getProperty("algorithm"); - + Connection con = createConnection(props,""); - - if (args.length == 2 && args[0].equals("-save")) + + if (args.length == 2 && args[0].equals("-save")) { savePasswords(con, args[1]); } - else if (args.length == 1 && args[0].equals("-encrypt")) + else if (args.length == 1 && args[0].equals("-encrypt")) { encryptionOn(con, algorithm); } - else if (args.length == 2 && args[0].equals("-restore")) + else if (args.length == 2 && args[0].equals("-restore")) { encryptionOff(con, args[1]); } - else if (args.length == 3 && args[0].equals("-reset")) + else if (args.length == 3 && args[0].equals("-reset")) { resetPassword(con, args[1], args[2], algorithm); } - else if (args.length == 2 && args[0].equals("-grant_admin")) + else if (args.length == 2 && args[0].equals("-grant_admin")) { grantAdmin(con, args[1]); } - else if (args.length == 2 && args[0].equals("-revoke_admin")) + else if (args.length == 2 && args[0].equals("-revoke_admin")) { revokeAdmin(con, args[1]); } - else + else { System.out.println(""); System.out.println("USAGE: save passwords to a properties file"); @@ -109,19 +109,19 @@ else if (args.length == 2 && args[0].equals("-revoke_admin")) System.out.println(""); } } - - /** + + /** * Create connection based on properties:
    * - driverClassName
    * - connectionUrl
    * - userName
    * - password
    */ - public static Connection createConnection(Properties props, String prefix) + public static Connection createConnection(Properties props, String prefix) throws Exception { Connection con = null; - if (prefix == null) + if (prefix == null) { prefix = ""; } @@ -129,7 +129,7 @@ public static Connection createConnection(Properties props, String prefix) String connectionUrl = props.getProperty(prefix+"connectionUrl"); String userName = props.getProperty(prefix+"userName"); String password = props.getProperty(prefix+"password"); - + Class.forName(driverClassName); if (userName != null && password != null) { @@ -141,9 +141,9 @@ public static Connection createConnection(Properties props, String prefix) } return con; } - - /** - * Saves usernames and passwords to properties file, passwords keyed by usernames + + /** + * Saves usernames and passwords to properties file, passwords keyed by usernames */ private static void savePasswords( Connection con, String fileName) throws Exception @@ -152,7 +152,7 @@ private static void savePasswords( PreparedStatement userquery = con.prepareStatement( "select username,passphrase from rolleruser"); ResultSet users = userquery.executeQuery(); - while (users.next()) + while (users.next()) { String username = users.getString(1); String passphrase = users.getString(2); @@ -163,7 +163,7 @@ private static void savePasswords( fos.close(); } - /** + /** * Encrypt all passwords in rolleruser and turn ON encryption flag in rollerconfig */ private static void encryptionOn( @@ -195,12 +195,12 @@ private static void encryptionOn( userUpdate.executeUpdate(); System.out.println("Encrypted password for user: " + username); } - + configUpdate.setBoolean(1, true); configUpdate.executeUpdate(); } - /** + /** * Restore passwords in rolleruser and turn OFF encryption flag in rollerconfig */ private static void encryptionOff( @@ -223,34 +223,34 @@ private static void encryptionOff( userUpdate.setString(2, username); userUpdate.executeUpdate(); } - + configUpdate.setBoolean(1, false); configUpdate.executeUpdate(); } - /** - * Reset user's password to specified value using specified algorythm (if needed) + /** + * Reset user's password to specified value using specified algorythm (if needed) */ private static void resetPassword( - Connection con, String username, String password, String algorithm) + Connection con, String username, String password, String algorithm) throws Exception { - PreparedStatement encryptionQuery = + PreparedStatement encryptionQuery = con.prepareStatement("select encryptpasswords from rollerconfig"); - PreparedStatement userUpdate = + PreparedStatement userUpdate = con.prepareStatement("update rolleruser set passphrase=? where username=?"); - + ResultSet rs = encryptionQuery.executeQuery(); rs.next(); boolean encryption = rs.getBoolean(1); - - String newpassword = + + String newpassword = encryption ? Utilities.encodePassword(password, algorithm) : password; userUpdate.setString(1, newpassword); userUpdate.setString(2, username); userUpdate.executeUpdate(); - } - + } + /** * Grant admin role to user by adding admin role for user to userrole table */ @@ -259,19 +259,19 @@ private static void grantAdmin(Connection con, String userName) throws Exception // Find userid of specified user String userid = null; PreparedStatement userQuery = con.prepareStatement( - "select id from rolleruser where username=?"); + "select id from rolleruser where username=?"); userQuery.setString(1, userName); ResultSet userRS = userQuery.executeQuery(); - if (!userRS.next()) + if (!userRS.next()) { System.err.println("ERROR: username not found in database"); return; } - else + else { userid = userRS.getString(1); } - + // Is user already an admin? PreparedStatement roleQuery = con.prepareStatement( "select username from userrole where username=? and rolename='admin'"); @@ -289,7 +289,7 @@ private static void grantAdmin(Connection con, String userName) throws Exception adminInsert.executeUpdate(); System.out.println("User granted admin role"); } - else + else { System.out.println("User was already an admin"); } @@ -303,19 +303,19 @@ private static void revokeAdmin(Connection con, String userName) throws Exceptio // Find userid of specified user String userid = null; PreparedStatement userQuery = con.prepareStatement( - "select id from rolleruser where username=?"); + "select id from rolleruser where username=?"); userQuery.setString(1, userName); ResultSet userRS = userQuery.executeQuery(); - if (!userRS.next()) + if (!userRS.next()) { System.err.println("ERROR: username not found in database"); return; } - else + else { userid = userRS.getString(1); } - + // Delete user's admin entries from userrole table PreparedStatement roleDelete = con.prepareStatement( "delete from userrole where userid=? and rolename='admin'"); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/RollerMessages.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/RollerMessages.java index 12416a6428..de76722ee2 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/RollerMessages.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/RollerMessages.java @@ -29,8 +29,8 @@ public class RollerMessages { private List mErrors = new ArrayList(); private List mMessages = new ArrayList(); - - public RollerMessages() + + public RollerMessages() { } public void addError(String key) @@ -65,15 +65,15 @@ public Iterator getMessages() { return mMessages.iterator(); } - public int getErrorCount() + public int getErrorCount() { return mErrors.size(); } - public int getMessageCount() + public int getMessageCount() { return mMessages.size(); } - public String toString() + public String toString() { StringBuffer sb = new StringBuffer(); Iterator msgs = mMessages.iterator(); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/StandaloneWebappClassLoader.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/StandaloneWebappClassLoader.java index 0e920c6a34..7367b69ec0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/StandaloneWebappClassLoader.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/StandaloneWebappClassLoader.java @@ -29,23 +29,23 @@ import java.util.List; /** - * ClassLoader to enable running webapp classes outside of webapp. - * You provide webappDir and jarsDir paths and the classloader will include + * ClassLoader to enable running webapp classes outside of webapp. + * You provide webappDir and jarsDir paths and the classloader will include * webappDir/WEB-INF/classes, webappDir/WEB-INF/lib/*jar and jarsDir/*.jar. */ public class StandaloneWebappClassLoader extends URLClassLoader { public static String FS = File.separator; - + /** Use calling class's parent classloader */ public StandaloneWebappClassLoader(String webappDir, String jarsDir) throws Exception { super(buildURLsArray(webappDir, jarsDir)); } - + /** Use a specific parent classloader, or null for no parent */ public StandaloneWebappClassLoader(String webappDir, String jarsDir, ClassLoader cl) throws Exception { super(buildURLsArray(webappDir, jarsDir), cl); } - + private static URL[] buildURLsArray(String webappDir, String jarsDir) throws Exception { // Create collection of URLs needed for classloader List urlList = new ArrayList(); @@ -53,17 +53,17 @@ private static URL[] buildURLsArray(String webappDir, String jarsDir) throws Exc // Add WEB-INF/lib jars String libPath = webappDir + FS + "WEB-INF" + FS + "lib"; addURLs(libPath, urlList); - + // Added WEB-INF/classes String classesPath = webappDir + FS + "WEB-INF" + FS + "classes" + FS; urlList.add(new URL("file://" + classesPath)); - + // Add additional jars addURLs(jarsDir, urlList); - - return (URL[])urlList.toArray(new URL[urlList.size()]); + + return (URL[])urlList.toArray(new URL[urlList.size()]); } - + private static void addURLs(String dirPath, List urlList) throws Exception { File libDir = new File(dirPath); String[] libJarNames = libDir.list(new FilenameFilter() { @@ -73,7 +73,7 @@ public boolean accept(File dir, String pathname) { } return false; } - }); + }); for (int i=0; i", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_B_TAG_PATTERN = + Pattern.compile("", Pattern.CASE_INSENSITIVE); + private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("<b>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_B_TAG_PATTERN = + private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("</b>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_I_TAG_PATTERN = + private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("<i>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_I_TAG_PATTERN = + private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("</i>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern BR_TAG_PATTERN = + private static final Pattern BR_TAG_PATTERN = Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_P_TAG_PATTERN = + private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("<p>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_P_TAG_PATTERN = + private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("</p>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_PRE_TAG_PATTERN = + private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_PRE_TAG_PATTERN = + private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_UL_TAG_PATTERN = + private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_UL_TAG_PATTERN = + private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_OL_TAG_PATTERN = + private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_OL_TAG_PATTERN = + private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_LI_TAG_PATTERN = + private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("<li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_LI_TAG_PATTERN = + private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("</li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_A_TAG_PATTERN = + private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("</a>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_A_TAG_PATTERN = + private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE); - private static final Pattern QUOTE_PATTERN = + private static final Pattern QUOTE_PATTERN = Pattern.compile(""", Pattern.CASE_INSENSITIVE); - - + + //------------------------------------------------------------------------ /** Strip jsessionid off of a URL */ public static String stripJsessionId( String url ) { @@ -103,7 +103,7 @@ public static String stripJsessionId( String url ) { } return url; } - + //------------------------------------------------------------------------ /** * Escape, but do not replace HTML. @@ -112,7 +112,7 @@ public static String stripJsessionId( String url ) { public static String escapeHTML(String s) { return escapeHTML(s, true); } - + //------------------------------------------------------------------------ /** * Escape, but do not replace HTML. @@ -130,11 +130,11 @@ public static String escapeHTML(String s, boolean escapeAmpersand) { s = StringUtils.replace(s, ">", ">"); return s; } - + public static String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + //------------------------------------------------------------------------ /** * Remove occurences of html, defined as any text @@ -144,7 +144,7 @@ public static String unescapeHTML(String str) { public static String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -162,16 +162,16 @@ public static String removeHTML(String str, boolean addSpace) { int endTag = 0; if (beginTag == -1) return str; - + while (beginTag >= start) { if (beginTag > 0) { ret.append(str.substring(start, beginTag)); - + // replace each tag with a space (looks better) if (addSpace) ret.append(" "); } endTag = str.indexOf(">", beginTag); - + // if endTag found move "cursor" forward if (endTag > -1) { start = endTag + 1; @@ -189,7 +189,7 @@ public static String removeHTML(String str, boolean addSpace) { } return ret.toString().trim(); } - + //------------------------------------------------------------------------ /** Run both removeHTML and escapeHTML on a string. * @param s String to be run through removeHTML and escapeHTML. @@ -199,7 +199,7 @@ public static String removeAndEscapeHTML( String s ) { if ( s==null ) return ""; else return Utilities.escapeHTML( Utilities.removeHTML(s) ); } - + //------------------------------------------------------------------------ /** * Autoformat. @@ -208,8 +208,8 @@ public static String autoformat(String s) { String ret = StringUtils.replace(s, "\n", "
    "); return ret; } - - + + /** * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML. */ @@ -236,8 +236,8 @@ public static String addNofollow(String html) { buf.append(html); return buf.toString(); } - - + + //------------------------------------------------------------------------ /** * Replaces occurences of non-alphanumeric characters with an underscore. @@ -245,7 +245,7 @@ public static String addNofollow(String html) { public static String replaceNonAlphanumeric(String str) { return replaceNonAlphanumeric(str, '_'); } - + //------------------------------------------------------------------------ /** * Replaces occurences of non-alphanumeric characters with a @@ -263,7 +263,7 @@ public static String replaceNonAlphanumeric(String str, char subst) { } return ret.toString(); } - + //------------------------------------------------------------------------ /** * Remove occurences of non-alphanumeric characters. @@ -280,7 +280,7 @@ public static String removeNonAlphanumeric(String str) { } return ret.toString(); } - + //------------------------------------------------------------------------ /** Convert string array to string with delimeters. */ public static String stringArrayToString(String[] stringArray, String delim) { @@ -293,7 +293,7 @@ public static String stringArrayToString(String[] stringArray, String delim) { } return ret; } - + //------------------------------------------------------------------------ /** Convert string array to string with delimeters. */ public static String stringListToString(List stringList, String delim) { @@ -306,7 +306,7 @@ public static String stringListToString(List stringList, String delim) { } return ret; } - + //-------------------------------------------------------------------------- /** Convert string with delimeters to string array. */ public static String[] stringToStringArray(String instr, String delim) @@ -314,13 +314,13 @@ public static String[] stringToStringArray(String instr, String delim) StringTokenizer toker = new StringTokenizer(instr, delim); String stringArray[] = new String[toker.countTokens()]; int i = 0; - + while (toker.hasMoreTokens()) { stringArray[i++] = toker.nextToken(); } return stringArray; } - + //-------------------------------------------------------------------------- /** Convert string with delimeters to string list. */ public static List stringToStringList(String instr, String delim) @@ -332,7 +332,7 @@ public static List stringToStringList(String instr, String delim) } return stringList; } - + //-------------------------------------------------------------------------- /** Convert string to integer array. */ public static int[] stringToIntArray(String instr, String delim) @@ -340,7 +340,7 @@ public static int[] stringToIntArray(String instr, String delim) StringTokenizer toker = new StringTokenizer(instr, delim); int intArray[] = new int[toker.countTokens()]; int i = 0; - + while (toker.hasMoreTokens()) { String sInt = toker.nextToken(); int nInt = Integer.parseInt(sInt); @@ -348,7 +348,7 @@ public static int[] stringToIntArray(String instr, String delim) } return intArray; } - + //------------------------------------------------------------------- /** Convert integer array to a string. */ public static String intArrayToString(int[] intArray) { @@ -361,12 +361,12 @@ public static String intArrayToString(int[] intArray) { } return ret; } - + //------------------------------------------------------------------------ public static void copyFile(File from, File to) throws IOException { InputStream in = null; OutputStream out = null; - + try { in = new FileInputStream(from); } catch (IOException ex) { @@ -376,7 +376,7 @@ public static void copyFile(File from, File to) throws IOException { + "', " + ex.getMessage()); } - + try { out = new FileOutputStream(to); } catch (Exception ex) { @@ -390,10 +390,10 @@ public static void copyFile(File from, File to) throws IOException { + "', " + ex.getMessage()); } - + copyInputToOutput(in, out, from.length()); } - + /** * Reads an inputstream into a string */ @@ -420,16 +420,16 @@ public static void copyInputToOutput( throws IOException { int bytes; long length; - + BufferedInputStream in = new BufferedInputStream(input); BufferedOutputStream out = new BufferedOutputStream(output); - + byte[] buffer; buffer = new byte[8192]; - + for (length = byteCount; length > 0;) { bytes = (int) (length > 8192 ? 8192 : length); - + try { bytes = in.read(buffer, 0, bytes); } catch (IOException ex) { @@ -441,12 +441,12 @@ public static void copyInputToOutput( throw new IOException( "Reading input stream, " + ex.getMessage()); } - + if (bytes < 0) break; - + length -= bytes; - + try { out.write(buffer, 0, bytes); } catch (IOException ex) { @@ -459,7 +459,7 @@ public static void copyInputToOutput( "Writing output stream, " + ex.getMessage()); } } - + try { in.close(); out.close(); @@ -467,7 +467,7 @@ public static void copyInputToOutput( throw new IOException("Closing file streams, " + ex.getMessage()); } } - + //------------------------------------------------------------------------ public static void copyInputToOutput( InputStream input, @@ -481,7 +481,7 @@ public static void copyInputToOutput( if (count != -1) out.write(buffer, 0, count); } - + try { in.close(); out.close(); @@ -489,7 +489,7 @@ public static void copyInputToOutput( throw new IOException("Closing file streams, " + ex.getMessage()); } } - + /** * Encode a string using algorithm specified in web.xml and return the * resulting encrypted password. If exception, the plain credentials @@ -503,9 +503,9 @@ public static void copyInputToOutput( */ public static String encodePassword(String password, String algorithm) { byte[] unencodedPassword = password.getBytes(); - + MessageDigest md = null; - + try { // first create an instance, given the provider md = MessageDigest.getInstance(algorithm); @@ -513,29 +513,29 @@ public static String encodePassword(String password, String algorithm) { mLogger.error("Exception: " + e); return password; } - + md.reset(); - + // call the update method one or more times // (useful when you don't know the size of your data, eg. stream) md.update(unencodedPassword); - + // now calculate the hash byte[] encodedPassword = md.digest(); - + StringBuffer buf = new StringBuffer(); - + for (int i = 0; i < encodedPassword.length; i++) { if ((encodedPassword[i] & 0xff) < 0x10) { buf.append("0"); } - + buf.append(Long.toString(encodedPassword[i] & 0xff, 16)); } - + return buf.toString(); } - + /** * Encode a string using Base64 encoding. Used when storing passwords * as cookies. @@ -549,10 +549,10 @@ public static String encodePassword(String password, String algorithm) { */ public static String encodeString(String str) throws IOException { Base64 base64 = new Base64(); - String encodedStr = new String(base64.encodeBase64(str.getBytes())); + String encodedStr = new String(base64.encodeBase64(str.getBytes())); return (encodedStr.trim()); } - + /** * Decode a string using Base64 encoding. * @@ -562,10 +562,10 @@ public static String encodeString(String str) throws IOException { */ public static String decodeString(String str) throws IOException { Base64 base64 = new Base64(); - String value = new String(base64.decodeBase64(str.getBytes())); + String value = new String(base64.decodeBase64(str.getBytes())); return (value); } - + /** * Strips HTML and truncates. */ @@ -573,21 +573,21 @@ public static String truncate( String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); - + // quickly adjust the upper if it is set lower than 'lower' if (upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -597,14 +597,14 @@ public static String truncate( str2 = str2.substring(0, upper); loc = upper; } - + // the string was truncated, so we append the appendToEnd String str2 = str2 + appendToEnd; } - + return str2; } - + /** * This method based on code from the String taglib at Apache Jakarta: * http://cvs.apache.org/viewcvs/jakarta-taglibs/string/src/org/apache/taglibs/string/util/StringW.java?rev=1.16&content-type=text/vnd.viewcvs-markup @@ -621,21 +621,21 @@ public static String truncateNicely(String str, int lower, int upper, String app // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -645,29 +645,29 @@ public static String truncateNicely(String str, int lower, int upper, String app str2 = str2.substring(0, upper); loc = upper; } - + // HTML was removed from original str if (diff) { - + // location of last space in truncated string loc = str2.lastIndexOf(' ', loc); - + // get last "word" in truncated string (add 1 to loc to eliminate space String str3 = str2.substring(loc+1); - + // find this fragment in original str, from 'loc' position loc = str.indexOf(str3, loc) + str3.length(); - + // get truncated string from original str, given new 'loc' str2 = str.substring(0, loc); - + // get all the HTML from original str after loc str3 = extractHTML(str.substring(loc)); - + // remove any tags which generate visible HTML // This call is unecessary, all HTML has already been stripped //str3 = removeVisibleHTMLTags(str3); - + // append the appendToEnd String and // add extracted HTML back onto truncated string str = str2 + appendToEnd + str3; @@ -675,31 +675,31 @@ public static String truncateNicely(String str, int lower, int upper, String app // the string was truncated, so we append the appendToEnd String str = str2 + appendToEnd; } - + } - + return str; } - + public static String truncateText(String str, int lower, int upper, String appendToEnd) { // strip markup from the string String str2 = removeHTML(str, false); boolean diff = (str2.length() < str.length()); - + // quickly adjust the upper if it is set lower than 'lower' if(upper < lower) { upper = lower; } - + // now determine if the string fits within the upper limit // if it does, go straight to return, do not pass 'go' and collect $200 if(str2.length() > upper) { // the magic location int int loc; - + // first we determine where the next space appears after lower loc = str2.lastIndexOf(' ', upper); - + // now we'll see if the location is greater than the lower limit if(loc >= lower) { // yes it was, so we'll cut it off here @@ -714,7 +714,7 @@ public static String truncateText(String str, int lower, int upper, String appen } return str; } - + /** * @param str * @return @@ -729,7 +729,7 @@ private static String stripLineBreaks(String str) { str = str.replaceAll("

    ",""); return str; } - + /** * Need need to get rid of any user-visible HTML tags once all text has been * removed such as <BR>. This sounds like a better approach than removing @@ -746,7 +746,7 @@ private static String removeVisibleHTMLTags(String str) { str = stripLineBreaks(str); StringBuffer result = new StringBuffer(str); StringBuffer lcresult = new StringBuffer(str.toLowerCase()); - + // = start) { endTag = str.indexOf(">", beginTag); - + // if endTag found, keep tag if (endTag > -1) { ret.append( str.substring(beginTag, endTag+1) ); - + // move start forward and find another tag start = endTag + 1; beginTag = str.indexOf("<", start); @@ -832,14 +832,14 @@ public static String extractHTML(String str) { } return ret.toString(); } - - + + public static String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public static String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } @@ -890,37 +890,37 @@ public static int stringToInt(String string) { } return 0; } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public static String toBase64(byte[] aValue) { - + final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - + int byte1; int byte2; int byte3; int iByteLen = aValue.length; StringBuffer tt = new StringBuffer(); - + for (int i = 0; i < iByteLen; i += 3) { boolean bByte2 = (i + 1) < iByteLen; boolean bByte3 = (i + 2) < iByteLen; byte1 = aValue[i] & 0xFF; byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0; byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0; - + tt.append(m_strBase64Chars.charAt(byte1 / 4)); tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16))); tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '=')); tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '=')); } - + return tt.toString(); } - + /** * @param tag * @return @@ -948,12 +948,12 @@ public static String stripInvalidTagCharacters(String tag) { } return sb.toString(); } - + public static String normalizeTag(String tag, Locale locale) { tag = Utilities.stripInvalidTagCharacters(tag); - return locale == null ? tag.toLowerCase() : tag.toLowerCase(locale); + return locale == null ? tag.toLowerCase() : tag.toLowerCase(locale); } - + /** * @param tags * @return @@ -964,8 +964,8 @@ public static List splitStringAsTags(String tags) { return Collections.EMPTY_LIST; return Arrays.asList(tagsarr); } - - + + /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes <b>, <i>, <p>, <br>, @@ -975,11 +975,11 @@ public static List splitStringAsTags(String tags) { * @return the transformed String */ public static String transformToHTMLSubset(String s) { - + if (s == null) { return null; } - + s = replace(s, OPENING_B_TAG_PATTERN, ""); s = replace(s, CLOSING_B_TAG_PATTERN, ""); s = replace(s, OPENING_I_TAG_PATTERN, ""); @@ -998,7 +998,7 @@ public static String transformToHTMLSubset(String s) { s = replace(s, OPENING_LI_TAG_PATTERN, "

  • "); s = replace(s, CLOSING_LI_TAG_PATTERN, "
  • "); s = replace(s, QUOTE_PATTERN, "\""); - + // HTTP links s = replace(s, CLOSING_A_TAG_PATTERN, "
    "); Matcher m = OPENING_A_TAG_PATTERN.matcher(s); @@ -1010,16 +1010,16 @@ public static String transformToHTMLSubset(String s) { s = s.substring(0, start) + link + s.substring(end, s.length()); m = OPENING_A_TAG_PATTERN.matcher(s); } - + // escaped angle brackets s = s.replaceAll("&lt;", "<"); s = s.replaceAll("&gt;", ">"); s = s.replaceAll("&#", "&#"); - + return s; } - - + + private static String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); @@ -1028,7 +1028,7 @@ private static String replace(String string, Pattern pattern, String replacement public static String getContentTypeFromFileName(String fileName) { FileTypeMap map = FileTypeMap.getDefaultFileTypeMap(); - + // TODO: figure out why PNG is missing from Java MIME types if (map instanceof MimetypesFileTypeMap) { try { @@ -1038,5 +1038,5 @@ public static String getContentTypeFromFileName(String fileName) { return map.getContentType(fileName); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/WSSEUtilities.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/WSSEUtilities.java index 64a38a019a..87145cf822 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/WSSEUtilities.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/WSSEUtilities.java @@ -1,12 +1,12 @@ /* * Copyright 2005, Dave Johnson - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -52,18 +52,18 @@ public static byte[] base64Decode(String value) throws IOException { public static String base64Encode(byte[] value) { return new String(Base64.encodeBase64(value)); } - public static String generateWSSEHeader(String userName, String password) - throws UnsupportedEncodingException { - + public static String generateWSSEHeader(String userName, String password) + throws UnsupportedEncodingException { + byte[] nonceBytes = Long.toString(new Date().getTime()).getBytes(); String nonce = new String(WSSEUtilities.base64Encode(nonceBytes)); - + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); String created = sdf.format(new Date()); - + String digest = WSSEUtilities.generateDigest( nonceBytes, created.getBytes("UTF-8"), password.getBytes("UTF-8")); - + StringBuffer header = new StringBuffer("UsernameToken Username=\""); header.append(userName); header.append("\", "); diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/Cache.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/Cache.java index f1d85236b4..a3590c04b4 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/Cache.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/Cache.java @@ -26,40 +26,40 @@ * Base interface representing a cache in Roller. */ public interface Cache { - + /** * a unique identifier for the cache. */ public String getId(); - - + + /** * put an item in the cache. */ public void put(String key, Object value); - - + + /** * get an item from the cache. */ public Object get(String key); - - + + /** * remove an item from the cache. */ public void remove(String key); - - + + /** * clear the entire cache. */ public void clear(); - - + + /** * get cache stats. */ public Map getStats(); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheFactory.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheFactory.java index 4ef4f2669a..dde5bb3721 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheFactory.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheFactory.java @@ -29,7 +29,7 @@ * cache factory before starting up the application. */ public interface CacheFactory { - + public Cache constructCache(Map properties); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheHandler.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheHandler.java index dd13d159b8..a55bf5b927 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheHandler.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheHandler.java @@ -40,13 +40,13 @@ * this interface so that they can know when to remove items from their cache. */ public interface CacheHandler { - + public void invalidate(WeblogEntry entry); - + public void invalidate(Weblog website); - + public void invalidate(WeblogBookmark bookmark); - + public void invalidate(WeblogBookmarkFolder folder); public void invalidate(WeblogEntryComment comment); @@ -58,5 +58,5 @@ public interface CacheHandler { public void invalidate(WeblogCategory category); public void invalidate(WeblogTemplate template); - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheManager.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheManager.java index abae84ca14..3c1d43dc34 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheManager.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CacheManager.java @@ -43,7 +43,7 @@ * The purpose of the CacheManager is to provide a level of abstraction between * classes that use a cache and the implementations of a cache. This allows * us to create easily pluggable cache implementations. - * + * * The other purpose is to provide a single interface for interacting with all * Roller caches at the same time. This is beneficial because as data * changes in the system we often need to notify all caches that some part of @@ -51,26 +51,26 @@ * process easier. */ public class CacheManager { - + private static Log log = LogFactory.getLog(CacheManager.class); - - private static final String DEFAULT_FACTORY = + + private static final String DEFAULT_FACTORY = "org.apache.roller.weblogger.util.cache.ExpiringLRUCacheFactoryImpl"; - + // a reference to the cache factory in use private static CacheFactory cacheFactory = null; - + // a set of all registered cache handlers private static Set cacheHandlers = new HashSet(); - + // a map of all registered caches private static Map caches = new HashMap(); - - + + static { // lookup what cache factory we want to use String classname = WebloggerConfig.getProperty("cache.defaultFactory"); - + // use reflection to instantiate our factory class try { Class factoryClass = Class.forName(classname); @@ -82,7 +82,7 @@ public class CacheManager { log.error("Unable to instantiate cache factory ["+classname+"]"+ " falling back on default", e); } - + if(cacheFactory == null) try { // hmm ... failed to load the specified cache factory // lets try our default @@ -92,23 +92,23 @@ public class CacheManager { log.fatal("Failed to instantiate a cache factory", e); throw new RuntimeException(e); } - + log.info("Cache Manager Initialized."); log.info("Cache Factory = "+cacheFactory.getClass().getName()); - - + + // add custom handlers String customHandlers = WebloggerConfig.getProperty("cache.customHandlers"); if(customHandlers != null && customHandlers.trim().length() > 0) { - + String[] cHandlers = customHandlers.split(","); for(int i=0; i < cHandlers.length; i++) { // use reflection to instantiate the handler class try { Class handlerClass = Class.forName(cHandlers[i]); - CacheHandler customHandler = + CacheHandler customHandler = (CacheHandler) handlerClass.newInstance(); - + cacheHandlers.add(customHandler); } catch(ClassCastException cce) { log.error("It appears that your handler does not implement "+ @@ -119,12 +119,12 @@ public class CacheManager { } } } - - + + // a non-instantiable class private CacheManager() {} - - + + /** * Ask the CacheManager to construct a cache. * @@ -144,20 +144,20 @@ private CacheManager() {} * and have them used only by specific caches. */ public static Cache constructCache(CacheHandler handler, Map properties) { - + log.debug("Constructing new cache with props "+properties); - + Cache cache = null; - + if(properties != null && properties.containsKey("factory")) { // someone wants a custom cache instance String classname = (String) properties.get("factory"); - + try { // use reflection to instantiate the factory class Class factoryClass = Class.forName(classname); CacheFactory factory = (CacheFactory) factoryClass.newInstance(); - + // now ask for a new cache cache = factory.constructCache(properties); } catch(ClassCastException cce) { @@ -168,15 +168,15 @@ public static Cache constructCache(CacheHandler handler, Map properties) { "] falling back on default", e); } } - + if(cache == null) { // ask our default cache factory for a new cache instance cache = cacheFactory.constructCache(properties); } - + if(cache != null) { caches.put(cache.getId(), cache); - + // register the handler for this new cache if(handler != null) { cacheHandlers.add(handler); @@ -185,160 +185,160 @@ public static Cache constructCache(CacheHandler handler, Map properties) { return cache; } - - + + /** * Register a CacheHandler to listen for object invalidations. * * This is here so that it's possible to to add classes which would respond * to object invalidations without necessarily having to create a cache. * - * An example would be a handler designed to notify other machines in a + * An example would be a handler designed to notify other machines in a * cluster when an object has been invalidated, or possibly the search * index management classes are interested in knowing when objects are * invalidated. */ public static void registerHandler(CacheHandler handler) { - + log.debug("Registering handler "+handler); - + if(handler != null) { cacheHandlers.add(handler); } } - - + + public static void invalidate(WeblogEntry entry) { - + log.debug("invalidating entry = "+entry.getAnchor()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(entry); } } - - + + public static void invalidate(Weblog website) { - + log.debug("invalidating website = "+website.getHandle()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(website); } } - - + + public static void invalidate(WeblogBookmark bookmark) { - + log.debug("invalidating bookmark = "+bookmark.getId()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(bookmark); } } - - + + public static void invalidate(WeblogBookmarkFolder folder) { - + log.debug("invalidating folder = "+folder.getId()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(folder); } } - - + + public static void invalidate(WeblogEntryComment comment) { - + log.debug("invalidating comment = "+comment.getId()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(comment); } } - - + + public static void invalidate(WeblogReferrer referer) { - + log.debug("invalidating referer = "+referer.getId()); - + // NOTE: Invalidating an entire website for each referer is not // good for our caching. This may need reevaluation later. //lastExpiredCache.put(referer.getWebsite().getHandle(), new Date()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(referer); } } - - + + public static void invalidate(User user) { - + log.debug("invalidating user = "+user.getUserName()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(user); } } - - + + public static void invalidate(WeblogCategory category) { - + log.debug("invalidating category = "+category.getId()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(category); } } - - + + public static void invalidate(WeblogTemplate template) { - + log.debug("invalidating template = "+template.getId()); - + Iterator handlers = cacheHandlers.iterator(); while(handlers.hasNext()) { ((CacheHandler) handlers.next()).invalidate(template); } } - + /** * Flush the entire cache system. */ public static void clear() { - + // loop through all caches and trigger a clear Cache cache = null; Iterator cachesIT = caches.values().iterator(); while(cachesIT.hasNext()) { cache = (Cache) cachesIT.next(); - + cache.clear(); } } - - + + /** * Flush a single cache. */ public static void clear(String cacheId) { - + Cache cache = (Cache) caches.get(cacheId); if(cache != null) { cache.clear(); } } - - + + /** * Compile stats from all registered caches. * @@ -348,26 +348,26 @@ public static void clear(String cacheId) { * something a bit more elaborate, like JMX. */ public static Map getStats() { - + Map allStats = new HashMap(); - + Cache cache = null; Iterator cachesIT = caches.values().iterator(); while(cachesIT.hasNext()) { cache = (Cache) cachesIT.next(); - + allStats.put(cache.getId(), cache.getStats()); } - + return allStats; } - - + + /** * Place to do any cleanup tasks for cache system. */ public static void shutdown() { // no-op } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CachedContent.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CachedContent.java index ae7dd72131..bed38d8683 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CachedContent.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/CachedContent.java @@ -15,34 +15,34 @@ * A utility class for storing cached content written to a java.io.Writer. */ public class CachedContent implements Serializable { - + private static Log log = LogFactory.getLog(CachedContent.class); - + // default to an 8K buffered cache public static final int DEFAULT_SIZE = 8192; - + // the byte array we use to maintain the cached content private byte[] content = new byte[0]; - + // content-type of data in byte array private String contentType = null; - + // Use a byte array output stream to cached the output bytes private transient ByteArrayOutputStream outstream = null; - + // The PrintWriter that users will be writing to private transient PrintWriter cachedWriter = null; - - + + public CachedContent(int size) { - + // construct output stream if(size > 0) { this.outstream = new ByteArrayOutputStream(size); } else { this.outstream = new ByteArrayOutputStream(DEFAULT_SIZE); } - + // construct writer from output stream try { this.cachedWriter = @@ -52,13 +52,13 @@ public CachedContent(int size) { throw new RuntimeException("Encoding problem", e); } } - + public CachedContent(int size, String contentType) { this(size); this.contentType = contentType; } - - + + /** * Get the content cached in this object as a byte array. If you convert * this back to a string yourself, be sure to re-encode in "UTF-8". @@ -69,8 +69,8 @@ public CachedContent(int size, String contentType) { public byte[] getContent() { return this.content; } - - + + /** * Get the content cached in this object as a String. * @@ -85,18 +85,18 @@ public String getContentAsString() { throw new RuntimeException(uex); } } - - + + public PrintWriter getCachedWriter() { return cachedWriter; } - - + + public String getContentType() { return contentType; } - - + + /** * Called to flush any output in the cached Writer to * the cached content for more permanent storage. @@ -104,36 +104,36 @@ public String getContentType() { * @throws IllegalStateException if calling flush() after a close() */ public void flush() { - + if(this.outstream == null) { throw new IllegalStateException("Cannot flush() after a close()!"); } - + this.cachedWriter.flush(); this.content = this.outstream.toByteArray(); - + log.debug("FLUSHED "+this.content.length); } - - + + /** * Close this CachedContent from further writing. */ public void close() throws IOException { - + if(this.cachedWriter != null) { this.cachedWriter.flush(); this.cachedWriter.close(); this.cachedWriter = null; } - + if(this.outstream != null) { this.content = this.outstream.toByteArray(); this.outstream.close(); this.outstream = null; } - + log.debug("CLOSED"); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringCacheEntry.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringCacheEntry.java index d24b781b90..f19e219494 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringCacheEntry.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringCacheEntry.java @@ -28,34 +28,34 @@ * and timeout period with them so we can know when they expire. */ public class ExpiringCacheEntry implements Serializable { - + private Object value; private long timeCached = -1; private long timeout = 0; - - + + public ExpiringCacheEntry(Object value, long timeout) { this.value = value; - + // make sure that we don't support negative values if(timeout > 0) { this.timeout = timeout; } - + this.timeCached = System.currentTimeMillis(); } - - + + public long getTimeCached() { return this.timeCached; } - - + + public long getTimeout() { return this.timeout; } - - + + /** * Retrieve the value of this cache entry. * @@ -68,16 +68,16 @@ public Object getValue() { return this.value; } } - - + + /** * Determine if this cache entry has expired. */ public boolean hasExpired() { - + long now = System.currentTimeMillis(); - + return ((this.timeCached + this.timeout) < now); } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheFactoryImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheFactoryImpl.java index 960c0b4f20..82f62eb24f 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheFactoryImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheFactoryImpl.java @@ -27,45 +27,45 @@ * Roller Expiring LRU cache factory. */ public class ExpiringLRUCacheFactoryImpl implements CacheFactory { - + private static Log log = LogFactory.getLog(ExpiringLRUCacheFactoryImpl.class); - - + + // protected so only the CacheManager can instantiate us protected ExpiringLRUCacheFactoryImpl() {} - - + + /** * Construct a new instance of a Roller Expiring LRUCache. */ public Cache constructCache(Map properties) { - + int size = 100; long timeout = 15 * 60; String id = "unknown"; - + try { size = Integer.parseInt((String) properties.get("size")); } catch(Exception e) { // ignored } - + try { timeout = Long.parseLong((String) properties.get("timeout")); } catch(Exception e) { // ignored } - + String cacheId = (String) properties.get("id"); if(cacheId != null) { id = cacheId; } - + Cache cache = new ExpiringLRUCacheImpl(id, size, timeout); - + log.debug("new cache constructed. size="+size+", timeout="+timeout); - + return cache; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheImpl.java index 66692d0768..c0d1fb0375 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/ExpiringLRUCacheImpl.java @@ -26,30 +26,30 @@ * An LRU cache where entries expire after a given timeout period. */ public class ExpiringLRUCacheImpl extends LRUCacheImpl { - + private static Log log = LogFactory.getLog(ExpiringLRUCacheImpl.class); - + private long timeout = 0; - - + + protected ExpiringLRUCacheImpl(String id) { - + super(id); this.timeout = 60 * 60 * 1000; } - - + + protected ExpiringLRUCacheImpl(String id, int maxsize, long timeout) { - + super(id, maxsize); - + // timeout is specified in seconds; only positive values allowed if(timeout > 0) { this.timeout = timeout * 1000; } } - - + + /** * Store an entry in the cache. * @@ -58,12 +58,12 @@ protected ExpiringLRUCacheImpl(String id, int maxsize, long timeout) { */ @Override public synchronized void put(String key, Object value) { - + ExpiringCacheEntry entry = new ExpiringCacheEntry(value, this.timeout); super.put(key, entry); } - - + + /** * Retrieve an entry from the cache. * @@ -72,18 +72,18 @@ public synchronized void put(String key, Object value) { */ @Override public synchronized Object get(String key) { - + Object value = null; ExpiringCacheEntry entry = null; - + synchronized(this) { entry = (ExpiringCacheEntry) super.get(key); } - + if (entry != null) { - + value = entry.getValue(); - + // if the value is null then that means this entry expired if (value == null) { log.debug("EXPIRED ["+key+"]"); @@ -91,8 +91,8 @@ public synchronized Object get(String key) { super.remove(key); } } - + return value; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheFactoryImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheFactoryImpl.java index 030703f1b9..ed6b0d5db0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheFactoryImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheFactoryImpl.java @@ -27,38 +27,38 @@ * Roller LRU Cache factory. */ public class LRUCacheFactoryImpl implements CacheFactory { - + private static Log log = LogFactory.getLog(LRUCacheFactoryImpl.class); - - + + // protected so that only the CacheManager can instantiate us protected LRUCacheFactoryImpl() {} - - + + /** * Construct a new instance of a Roller LRUCache. */ public Cache constructCache(Map properties) { - + int size = 100; String id = "unknown"; - + try { size = Integer.parseInt((String) properties.get("size")); } catch(Exception e) { // ignored } - + String cacheId = (String) properties.get("id"); if(cacheId != null) { id = cacheId; } - + Cache cache = new LRUCacheImpl(id, size); - + log.debug("new cache constructed. size="+size); - + return cache; } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheImpl.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheImpl.java index dca57e07f5..5f52caf4f0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheImpl.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LRUCacheImpl.java @@ -31,78 +31,78 @@ * A simple LRU Cache. */ public class LRUCacheImpl implements Cache { - + private static Log log = LogFactory.getLog(LRUCacheImpl.class); - + private String id = null; private Map cache = null; - + // for metrics protected double hits = 0; protected double misses = 0; protected double puts = 0; protected double removes = 0; protected Date startTime = new Date(); - - + + protected LRUCacheImpl(String id) { - + this.id = id; this.cache = Collections.synchronizedMap(new LRULinkedHashMap(100)); } - - + + protected LRUCacheImpl(String id, int maxsize) { - + this.id = id; this.cache = Collections.synchronizedMap(new LRULinkedHashMap(maxsize)); } - - + + public String getId() { return this.id; } - - + + /** * Store an entry in the cache. */ public synchronized void put(String key, Object value) { - + this.cache.put(key, value); puts++; } - - + + /** * Retrieve an entry from the cache. */ public synchronized Object get(String key) { - + Object obj = this.cache.get(key); - + // for metrics if(obj == null) { misses++; } else { hits++; } - + return obj; } - - + + public synchronized void remove(String key) { - + this.cache.remove(key); removes++; } - - + + public synchronized void clear() { - + this.cache.clear(); - + // clear metrics hits = 0; misses = 0; @@ -110,39 +110,39 @@ public synchronized void clear() { removes = 0; startTime = new Date(); } - - + + public Map getStats() { - + Map stats = new HashMap(); stats.put("startTime", this.startTime); stats.put("hits", new Double(this.hits)); stats.put("misses", new Double(this.misses)); stats.put("puts", new Double(this.puts)); stats.put("removes", new Double(this.removes)); - + // calculate efficiency if((misses - removes) > 0) { double efficiency = hits / (misses + hits); stats.put("efficiency", new Double(efficiency * 100)); } - + return stats; } - - + + // David Flanaghan: http://www.davidflanagan.com/blog/000014.html private static class LRULinkedHashMap extends LinkedHashMap { protected int maxsize; - + public LRULinkedHashMap(int maxsize) { super(maxsize * 4 / 3 + 1, 0.75f, true); this.maxsize = maxsize; } - + protected boolean removeEldestEntry(Map.Entry eldest) { return this.size() > this.maxsize; } } - + } diff --git a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LazyExpiringCacheEntry.java b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LazyExpiringCacheEntry.java index fc0ea1ef1e..2e5861a8a0 100644 --- a/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LazyExpiringCacheEntry.java +++ b/weblogger-business/src/main/java/org/apache/roller/weblogger/util/cache/LazyExpiringCacheEntry.java @@ -33,7 +33,7 @@ * This essentially allows us to track when an object is cached and then before * we can retrieve that cached object we must compare it with it's last known * invalidation time to make sure it hasn't expired. This is useful because - * instead of actively purging lots of cached objects from the cache at + * instead of actively purging lots of cached objects from the cache at * invalidation time, we can now be lazy and just invalidate them when we * actually try to retrieve the cached object. * @@ -43,17 +43,17 @@ * we try to use them. */ public class LazyExpiringCacheEntry implements Serializable { - + private Object value = null; private long timeCached = -1; - - + + public LazyExpiringCacheEntry(Object item) { this.value = item; this.timeCached = System.currentTimeMillis(); } - - + + /** * Retrieve the value of this cache entry if it is still "fresh". * @@ -66,19 +66,19 @@ public Object getValue(long lastInvalidated) { return this.value; } } - - + + /** * Determine if this cache entry has expired. */ public boolean isInvalid(long lastInvalidated) { - + return (this.timeCached < lastInvalidated); } - + public long getTimeCached() { return timeCached; } - + } diff --git a/weblogger-business/src/main/resources/META-INF/persistence.xml b/weblogger-business/src/main/resources/META-INF/persistence.xml index 870fc58b94..d54eefe06b 100644 --- a/weblogger-business/src/main/resources/META-INF/persistence.xml +++ b/weblogger-business/src/main/resources/META-INF/persistence.xml @@ -1,5 +1,5 @@ - + ${datasourceName} org/apache/roller/weblogger/pojos/WeblogBookmark.orm.xml org/apache/roller/weblogger/pojos/WeblogEntryComment.orm.xml @@ -24,9 +24,9 @@ org/apache/roller/weblogger/pojos/UserAttribute.orm.xml org/apache/roller/weblogger/pojos/OAuthConsumerRecord.orm.xml org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml - org/apache/roller/weblogger/pojos/MediaFile.orm.xml - org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml + org/apache/roller/weblogger/pojos/MediaFile.orm.xml + org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml org/apache/roller/weblogger/pojos/MediaFileDirectory.orm.xml org.apache.roller.weblogger.pojos.AutoPing - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/config/runtimeConfigDefs.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/config/runtimeConfigDefs.xml index 59ebbd561b..92374e5b0a 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/config/runtimeConfigDefs.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/config/runtimeConfigDefs.xml @@ -21,21 +21,21 @@ STOP!!!! This is NOT a Roller configuration file!! Users of Roller should never need to edit this file. The properties listed here are changed on the Roller Admin Settings page. - + This file defines what properties are made available to get/set during the running of the Roller application. These properties are stored in the database and the code *must* be able to make use of changed values during runtime. - + Also included in this file is meta-data which defines what class of property we are dealing with, it's default value, and information on how to populate the display that allows for changing the value. - + NOTE: order does matter!! the display is populated in a linear fashion starting from the first display-group and moving down. --> - + - + string Roller Site @@ -59,11 +59,11 @@ text A default install of the Roller Weblogger open source blog server - + string - + boolean false @@ -86,10 +86,10 @@ - + - + boolean false @@ -114,8 +114,8 @@ - - + + @@ -137,7 +137,7 @@ - + string 30 @@ -150,13 +150,13 @@ boolean true - + - - + + - + boolean true @@ -184,7 +184,7 @@ boolean - false + false boolean @@ -200,10 +200,10 @@ - + - + boolean true @@ -226,11 +226,11 @@ - - + + - + string /themes @@ -239,13 +239,13 @@ boolean true - + - - + + - + text @@ -254,7 +254,7 @@ - + - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml index f26df9b4da..ccb20f8bb3 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileDirectory.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileDirectory.orm.xml index 86d2eae19b..3c842a5598 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileDirectory.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileDirectory.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml index e43445dea4..e5729bd82f 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/MediaFileTag.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml index 9330ec9a86..8d1f9d3885 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.orm.xml index 4a9f0a0767..5bf915c49a 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/OAuthConsumerRecord.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/ObjectPermission.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/ObjectPermission.orm.xml index 8e52b2037c..d75e4e7263 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/ObjectPermission.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/ObjectPermission.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingQueueEntry.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingQueueEntry.orm.xml index 4ad1303fc3..d608106086 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingQueueEntry.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingQueueEntry.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingTarget.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingTarget.orm.xml index 674a3579e3..618a41aa3c 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingTarget.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/PingTarget.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.orm.xml index f7b69ac982..c1947b49e2 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/RuntimeConfigProperty.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/User.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/User.orm.xml index 64bdb43c35..d6098824ad 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/User.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/User.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -70,7 +70,7 @@ DISTINCT is not required for this query as no duplicate User would be retrieved --> SELECT COUNT(u) FROM User u WHERE u.enabled = ?1 - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserAttribute.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserAttribute.orm.xml index 8d0fc0af56..7ea45ec43c 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserAttribute.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserAttribute.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -11,19 +11,19 @@ org.apache.roller.weblogger.pojos - + SELECT r FROM UserAttribute r WHERE r.userName = ?1 - + SELECT r FROM UserAttribute r WHERE r.name = ?1 AND r.value = ?2 - + SELECT r FROM UserAttribute r WHERE r.userName = ?1 AND r.name = ?2 - - + + @@ -38,6 +38,6 @@ - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserRole.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserRole.orm.xml index becd7f2f8f..fd35663be4 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserRole.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/UserRole.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -11,15 +11,15 @@ org.apache.roller.weblogger.pojos
    - + SELECT r FROM UserRole r WHERE r.userName = ?1 - + SELECT r FROM UserRole r WHERE r.userName = ?1 AND r.role = ?2 - + @@ -29,8 +29,8 @@ - + - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/Weblog.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/Weblog.orm.xml index 43b9960d59..63463b6888 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/Weblog.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/Weblog.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmark.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmark.orm.xml index f23009ef14..7579ef7332 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmark.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmark.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -50,7 +50,7 @@ - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.orm.xml index 91707699ce..b73ae0584d 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogBookmarkFolder.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogCategory.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogCategory.orm.xml index 04057c3b72..d1668c3e8d 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogCategory.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogCategory.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -51,7 +51,7 @@ - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntry.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntry.orm.xml index c3b2ac612d..2bab026072 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntry.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntry.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -168,7 +168,7 @@ - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.orm.xml index 2919eb22ca..74e58791b2 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryAttribute.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryComment.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryComment.orm.xml index 8a208cbca9..2a37e63d73 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryComment.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryComment.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -21,7 +21,7 @@ SELECT COUNT(c), c.weblogEntry.website.id, c.weblogEntry.website.handle, c.weblogEntry.website.name FROM WeblogEntryComment c WHERE c.weblogEntry.pubTime < ?1 GROUP BY c.weblogEntry.website.id, c.weblogEntry.website.handle, c.weblogEntry.website.name diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTag.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTag.orm.xml index f099c65008..ef1ec8f9c7 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTag.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTag.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.orm.xml index a46bff1922..f1d81435f3 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogEntryTagAggregate.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogHitCount.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogHitCount.orm.xml index f51e4e941b..5811ed8e0c 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogHitCount.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogHitCount.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogPermission.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogPermission.orm.xml index a1d8c36a96..e4ca7ddf15 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogPermission.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogPermission.orm.xml @@ -1,46 +1,46 @@ Persistence Metadata for Roller PROPERTY - + org.apache.roller.weblogger.pojos Weblog - + SELECT p FROM WeblogPermission p - + SELECT p FROM WeblogPermission p WHERE p.userName = ?1 AND p.pending <> TRUE - + SELECT p FROM WeblogPermission p WHERE p.objectId = ?1 AND p.pending <> TRUE - + SELECT p FROM WeblogPermission p WHERE p.userName = ?1 AND p.objectId = ?2 - + SELECT p FROM WeblogPermission p WHERE p.userName = ?1 AND p.objectId = ?2 AND p.pending <> true - + SELECT p FROM WeblogPermission p WHERE p.userName = ?1 AND p.pending = TRUE - + SELECT p FROM WeblogPermission p WHERE p.objectId = ?1 AND p.pending = true - + diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogReferrer.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogReferrer.orm.xml index aff5c4182c..628ee15c75 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogReferrer.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogReferrer.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller diff --git a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogTemplate.orm.xml b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogTemplate.orm.xml index 7d3b391963..27469cfe17 100644 --- a/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogTemplate.orm.xml +++ b/weblogger-business/src/main/resources/org/apache/roller/weblogger/pojos/WeblogTemplate.orm.xml @@ -1,6 +1,6 @@ Persistence Metadata for Roller @@ -69,7 +69,7 @@ - + diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/BookmarkTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/BookmarkTest.java index 8eed82b2e1..5af1838568 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/BookmarkTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/BookmarkTest.java @@ -38,21 +38,21 @@ * Test Weblogger Bookmark Management. */ public class BookmarkTest extends TestCase { - + public static Log log = LogFactory.getLog(BookmarkTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("bkmrkTestUser"); testWeblog = TestUtils.setupWeblog("bkmrkTestWeblog", testUser); @@ -62,9 +62,9 @@ public void setUp() throws Exception { throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -74,26 +74,26 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - + public Weblogger getRoller() { return WebloggerFactory.getWeblogger(); } - - + + public void testBookmarkCRUD() throws Exception { - + BookmarkManager bmgr = getRoller().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + WeblogBookmarkFolder folder = new WeblogBookmarkFolder(root, "TestFolder2", null, TestUtils.getManagedWebsite(testWeblog)); bmgr.saveFolder(folder); TestUtils.endSession(true); - + // query for folder again since session ended folder = bmgr.getFolder(folder.getId()); - + // Add bookmark by adding to folder WeblogBookmark bookmark1 = new WeblogBookmark( folder, @@ -106,7 +106,7 @@ public void testBookmarkCRUD() throws Exception { "test.jpg"); bookmark1.setFolder(folder); folder.addBookmark(bookmark1); - + // Add another bookmark WeblogBookmark bookmark2 = new WeblogBookmark( folder, @@ -119,51 +119,51 @@ public void testBookmarkCRUD() throws Exception { "test.jpf"); bookmark2.setFolder(folder); folder.addBookmark(bookmark2); - + TestUtils.endSession(true); - + WeblogBookmarkFolder testFolder = null; WeblogBookmark bookmarkb = null, bookmarka = null; - + // See that two bookmarks were stored testFolder = bmgr.getFolder(folder.getId()); assertEquals(2, testFolder.getBookmarks().size()); Iterator iter = testFolder.getBookmarks().iterator(); bookmarka = iter.next(); bookmarkb = iter.next(); - + // Remove one bookmark - bmgr.removeBookmark(bookmarka); - bmgr.removeBookmark(bookmarkb); + bmgr.removeBookmark(bookmarka); + bmgr.removeBookmark(bookmarkb); bmgr.saveFolder(testFolder); TestUtils.endSession(true); - + // Folder should now contain one bookmark assertNull(bmgr.getBookmark(bookmarka.getId())); assertNull(bmgr.getBookmark(bookmarkb.getId())); testFolder = bmgr.getFolder(folder.getId()); assertEquals(0, testFolder.getBookmarks().size()); - + // Remove folder bmgr.removeFolder(testFolder); TestUtils.endSession(true); - + // Folder and one remaining bookmark should be gone assertNull( bmgr.getBookmark(bookmarkb.getId()) ); assertNull( bmgr.getFolder(folder.getId()) ); } - - + + /** * Test all bookmark lookup methods. */ public void _testBookmarkLookups() throws Exception { - + BookmarkManager bmgr = getRoller().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + // add some folders WeblogBookmarkFolder f1 = new WeblogBookmarkFolder(root, "f1", null, TestUtils.getManagedWebsite(testWeblog)); bmgr.saveFolder(f1); @@ -171,11 +171,11 @@ public void _testBookmarkLookups() throws Exception { bmgr.saveFolder(f2); WeblogBookmarkFolder f3 = new WeblogBookmarkFolder(root, "f3", null, TestUtils.getManagedWebsite(testWeblog)); bmgr.saveFolder(f3); - + TestUtils.endSession(true); - - f1 = bmgr.getFolder(f1.getId()); - f2 = bmgr.getFolder(f2.getId()); + + f1 = bmgr.getFolder(f1.getId()); + f2 = bmgr.getFolder(f2.getId()); // add some bookmarks WeblogBookmark b1 = new WeblogBookmark( @@ -193,31 +193,31 @@ public void _testBookmarkLookups() throws Exception { "http://example.com", "http://example.com/rss", new Integer(1), new Integer(1), "image.gif"); bmgr.saveBookmark(b3); - + TestUtils.endSession(true); - + // test lookup by id WeblogBookmark testBookmark = bmgr.getBookmark(b1.getId()); assertNotNull(testBookmark); assertEquals("b1", testBookmark.getName()); - + // test lookup of all bookmarks in single folder WeblogBookmarkFolder testFolder = bmgr.getFolder(f1.getId()); List allBookmarks = bmgr.getBookmarks(testFolder, false); assertNotNull(allBookmarks); assertEquals(2, allBookmarks.size()); - + // getBookmarks(folder, false) should also match folder.getBookmarks() assertEquals(allBookmarks.size(), testFolder.getBookmarks().size()); - + // test lookup of all bookmarks in folder branch (including subfolders) testFolder = bmgr.getFolder(f1.getId()); allBookmarks = bmgr.getBookmarks(testFolder, true); assertNotNull(allBookmarks); assertEquals(3, allBookmarks.size()); } - - + + /** * Creates folder tree like this: * root/ @@ -235,7 +235,7 @@ public void _testBookmarkLookups() throws Exception { */ public void _testMoveFolderContents() throws Exception { BookmarkManager bmgr = getRoller().getBookmarkManager(); - try { + try { testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); @@ -315,7 +315,7 @@ public void _testMoveFolderContents() throws Exception { // check that paths and child folders are correct assertEquals("/dest/f1", f1.getPath()); assertEquals(1, dest.getFolders().size()); - + bmgr.removeFolder(f1); bmgr.removeFolder(dest); @@ -326,25 +326,25 @@ public void _testMoveFolderContents() throws Exception { TestUtils.endSession(true); } } - - + + public void _testBookmarkImport() throws Exception { - + InputStream fis = this.getClass().getResourceAsStream("/bookmarks.opml"); getRoller().getBookmarkManager().importBookmarks( TestUtils.getManagedWebsite(testWeblog), "ZZZ_imports_ZZZ", fileToString(fis)); TestUtils.endSession(true); - + WeblogBookmarkFolder fd = null; - + testWeblog = TestUtils.getManagedWebsite(testWeblog); fd = getRoller().getBookmarkManager().getFolder(testWeblog, "ZZZ_imports_ZZZ"); assertTrue(fd.retrieveBookmarks(true).size() > 0 ); getRoller().getBookmarkManager().removeFolder(fd); TestUtils.endSession(true); } - - + + private String fileToString( InputStream is ) throws java.io.IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s = null; @@ -354,5 +354,5 @@ private String fileToString( InputStream is ) throws java.io.IOException { } return sb.toString(); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/CommentTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/CommentTest.java index 4678bf231f..b1c4e8ccea 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/CommentTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/CommentTest.java @@ -40,32 +40,32 @@ * That includes: */ public class CommentTest extends TestCase { - + public static Log log = LogFactory.getLog(CommentTest.class); - + User testUser = null; Weblog testWeblog = null; WeblogEntry testEntry = null; - - + + public CommentTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(CommentTest.class); } - - + + /** * All tests in this suite require a user, weblog, and an entry. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("commentTestUser"); testWeblog = TestUtils.setupWeblog("commentTestWeblog", testUser); @@ -76,9 +76,9 @@ public void setUp() throws Exception { throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblogEntry(testEntry.getId()); TestUtils.teardownWeblog(testWeblog.getId()); @@ -89,15 +89,15 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - - + + /** * Test basic persistence operations ... Create, Update, Delete */ public void testCommentCRUD() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + WeblogEntryComment comment = new WeblogEntryComment(); comment.setName("test"); comment.setEmail("test"); @@ -107,100 +107,100 @@ public void testCommentCRUD() throws Exception { comment.setPostTime(new java.sql.Timestamp(new java.util.Date().getTime())); comment.setWeblogEntry(TestUtils.getManagedWeblogEntry(testEntry)); comment.setStatus(WeblogEntryComment.APPROVED); - + // create a comment mgr.saveComment(comment); String id = comment.getId(); TestUtils.endSession(true); - + // make sure comment was created comment = null; comment = mgr.getComment(id); assertNotNull(comment); assertEquals("this is a test comment", comment.getContent()); - + // update a comment comment.setContent("testtest"); mgr.saveComment(comment); TestUtils.endSession(true); - + // make sure comment was updated comment = null; comment = mgr.getComment(id); assertNotNull(comment); assertEquals("testtest", comment.getContent()); - + // delete a comment mgr.removeComment(comment); TestUtils.endSession(true); - + // make sure comment was deleted comment = null; comment = mgr.getComment(id); assertNull(comment); } - - + + /** - * Test lookup mechanisms ... + * Test lookup mechanisms ... */ public void testCommentLookups() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); List comments = null; - + // we need some comments to play with testEntry = TestUtils.getManagedWeblogEntry(testEntry); WeblogEntryComment comment1 = TestUtils.setupComment("comment1", testEntry); WeblogEntryComment comment2 = TestUtils.setupComment("comment2", testEntry); WeblogEntryComment comment3 = TestUtils.setupComment("comment3", testEntry); TestUtils.endSession(true); - + // get all comments comments = null; comments = mgr.getComments(null, null, null, null, null, null, false, 0, -1); assertNotNull(comments); assertEquals(3, comments.size()); - + // get all comments for entry testEntry = TestUtils.getManagedWeblogEntry(testEntry); comments = null; comments = mgr.getComments(null, testEntry, null, null, null, null, false, 0, -1); assertNotNull(comments); assertEquals(3, comments.size()); - + // make some changes comment3 = mgr.getComment(comment3.getId()); comment3.setStatus(WeblogEntryComment.PENDING); mgr.saveComment(comment3); TestUtils.endSession(true); - + // get pending comments comments = null; comments = mgr.getComments(null, null, null, null, null, WeblogEntryComment.PENDING, false, 0, -1); assertNotNull(comments); assertEquals(1, comments.size()); - + // get approved comments comments = null; comments = mgr.getComments(null, null, null, null, null, WeblogEntryComment.APPROVED, false, 0, -1); assertNotNull(comments); assertEquals(2, comments.size()); - + // get comments with offset comments = null; comments = mgr.getComments(null, null, null, null, null, null, false, 1, -1); assertNotNull(comments); assertEquals(2, comments.size()); - + // remove test comments TestUtils.teardownComment(comment1.getId()); TestUtils.teardownComment(comment2.getId()); TestUtils.teardownComment(comment3.getId()); TestUtils.endSession(true); } - - + + /** * Test that when deleting parent objects of a comment that everything * down the chain is properly deleted as well. i.e. deleting an entry @@ -208,18 +208,18 @@ public void testCommentLookups() throws Exception { * delete all comments, etc. */ public void testCommentParentDeletes() throws Exception { - + log.info("BEGIN"); - + try { - WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); - WeblogEntryManager emgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); + WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); + WeblogEntryManager emgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); // first make sure we can delete an entry with comments User user = TestUtils.setupUser("commentParentDeleteUser"); Weblog weblog = TestUtils.setupWeblog("commentParentDelete", user); - WeblogEntry entry = TestUtils.setupWeblogEntry("CommentParentDeletes1", + WeblogEntry entry = TestUtils.setupWeblogEntry("CommentParentDeletes1", weblog.getDefaultCategory(), weblog, user); TestUtils.endSession(true); @@ -242,7 +242,7 @@ public void testCommentParentDeletes() throws Exception { // now make sure we can delete a weblog with comments weblog = TestUtils.getManagedWebsite(weblog); user = TestUtils.getManagedUser(user); - entry = TestUtils.setupWeblogEntry("CommentParentDeletes2", + entry = TestUtils.setupWeblogEntry("CommentParentDeletes2", weblog.getDefaultCategory(), weblog, user); TestUtils.endSession(true); @@ -252,7 +252,7 @@ public void testCommentParentDeletes() throws Exception { TestUtils.setupComment("comment3", entry); TestUtils.endSession(true); - // now deleting the website should succeed + // now deleting the website should succeed ex = null; try { weblog = TestUtils.getManagedWebsite(weblog); @@ -260,7 +260,7 @@ public void testCommentParentDeletes() throws Exception { TestUtils.endSession(true); } catch (WebloggerException e) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.info(sw.toString()); ex = e; @@ -269,24 +269,24 @@ public void testCommentParentDeletes() throws Exception { // and delete test user as well umgr.removeUser(TestUtils.getManagedUser(user)); - + } finally { TestUtils.endSession(true); } - + log.info("END"); } - - + + /** - * Apparently, HSQL has "issues" with LIKE expressions, - * so I'm commenting this out for now. - + * Apparently, HSQL has "issues" with LIKE expressions, + * so I'm commenting this out for now. + public void _testBulkCommentDelete() throws Exception { - + WeblogManager mgr = RollerFactory.getRoller().getWeblogManager(); List comments = null; - + // we need some comments to play with WeblogEntryComment comment1 = TestUtils.setupComment("deletemeXXX", testEntry); WeblogEntryComment comment2 = TestUtils.setupComment("XXXdeleteme", testEntry); @@ -295,7 +295,7 @@ public void _testBulkCommentDelete() throws Exception { WeblogEntryComment comment5 = TestUtils.setupComment("saveme", testEntry); WeblogEntryComment comment6 = TestUtils.setupComment("saveme", testEntry); TestUtils.endSession(true); - + // get all comments comments = null; comments = mgr.getComments( @@ -312,7 +312,7 @@ public void _testBulkCommentDelete() throws Exception { -1); // length assertNotNull(comments); assertEquals(6, comments.size()); - + comments = mgr.getComments( null, // website null, // entry @@ -327,7 +327,7 @@ public void _testBulkCommentDelete() throws Exception { -1); // length assertNotNull(comments); assertEquals(3, comments.size()); - + int countDeleted = mgr.removeMatchingComments( null, // website null, // entry @@ -336,9 +336,9 @@ public void _testBulkCommentDelete() throws Exception { null, // endDate null, // pending null, // approved - null); // spam + null); // spam assertEquals(3, countDeleted); - + comments = mgr.getComments( null, // website null, // entry @@ -353,7 +353,7 @@ public void _testBulkCommentDelete() throws Exception { -1); // length assertNotNull(comments); assertEquals(3, comments.size()); - + // remove test comments countDeleted = mgr.removeMatchingComments( null, // website @@ -363,49 +363,49 @@ public void _testBulkCommentDelete() throws Exception { null, // endDate null, // pending null, // approved - null); // spam + null); // spam assertEquals(3, countDeleted); TestUtils.endSession(true); } */ - + /** * Test extra CRUD methods ... removeComments(ids), removeCommentsForEntry */ // public void testAdvancedCommentCRUD() throws Exception { -// +// // WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); // List comments = null; -// +// // // we need some comments to play with // WeblogEntryComment comment1 = TestUtils.setupComment("comment1", testEntry); // WeblogEntryComment comment2 = TestUtils.setupComment("comment2", testEntry); // WeblogEntryComment comment3 = TestUtils.setupComment("comment3", testEntry); // WeblogEntryComment comment4 = TestUtils.setupComment("comment4", testEntry); // TestUtils.endSession(true); -// +// // // remove a collection of comments // String[] delComments = new String[2]; // delComments[0] = comment1.getId(); // delComments[1] = comment2.getId(); // mgr.removeComments(delComments); // TestUtils.endSession(true); -// +// // // make sure comments were deleted // comments = null; // comments = mgr.getComments(null, null, null, null, null, null, null, null, false, 0, -1); // assertNotNull(comments); // assertEquals(2, comments.size()); -// +// // // remove all comments for entry // mgr.removeCommentsForEntry(testEntry.getId()); // TestUtils.endSession(true); -// +// // // make sure comments were deleted // comments = null; // comments = mgr.getComments(null, null, null, null, null, null, null, null, false, 0, -1); // assertNotNull(comments); // assertEquals(0, comments.size()); // } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderCRUDTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderCRUDTest.java index 863f6b9c04..9977e26ef1 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderCRUDTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderCRUDTest.java @@ -31,23 +31,23 @@ * Test basic folder operations. */ public class FolderCRUDTest extends TestCase { - + public static Log log = LogFactory.getLog(FolderCRUDTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + log.info("BEGIN"); - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("folderCRUDTestUser"); testWeblog = TestUtils.setupWeblog("folderCRUDTestWeblog", testUser); @@ -56,14 +56,14 @@ public void setUp() throws Exception { log.error(ex); throw new Exception("Test setup failed", ex); } - + log.info("END"); } - + public void tearDown() throws Exception { - + log.info("BEGIN"); - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -72,99 +72,99 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + log.info("END"); } - - + + /** * Test WeblogBookmarkFolder.equals() method. */ public void testFolderEquality() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + WeblogBookmarkFolder testFolder = new WeblogBookmarkFolder(null, "root", "root", TestUtils.getManagedWebsite(testWeblog)); assertTrue(root.equals(testFolder)); - + testFolder = new WeblogBookmarkFolder(root, "root", "root", TestUtils.getManagedWebsite(testWeblog)); assertFalse(root.equals(testFolder)); - + log.info("END"); } - - + + /** * Test add/modify/remove of folders. */ public void testBasicCRUD() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + // start out with no folders and no bookmarks assertEquals(0, root.getFolders().size()); assertEquals(0, root.getBookmarks().size()); - + // add a folder WeblogBookmarkFolder newFolder = new WeblogBookmarkFolder(root, "folderBasicCRUD", null, TestUtils.getManagedWebsite(testWeblog)); bmgr.saveFolder(newFolder); TestUtils.endSession(true); - + // check that folder was saved testWeblog = TestUtils.getManagedWebsite(testWeblog); root = bmgr.getRootFolder(testWeblog); assertEquals(1, root.getFolders().size()); WeblogBookmarkFolder folder = (WeblogBookmarkFolder) root.getFolders().iterator().next(); assertEquals(newFolder, folder); - + // modify folder folder.setName("folderTest1"); bmgr.saveFolder(folder); TestUtils.endSession(true); - + // check that folder was saved testWeblog = TestUtils.getManagedWebsite(testWeblog); root = bmgr.getRootFolder(testWeblog); folder = (WeblogBookmarkFolder) root.getFolders().iterator().next(); assertEquals("folderTest1", folder.getName()); - + // test remove folder bmgr.removeFolder(folder); TestUtils.endSession(true); - + // make sure folder was removed testWeblog = TestUtils.getManagedWebsite(testWeblog); root = bmgr.getRootFolder(testWeblog); assertEquals(0, root.getFolders().size()); folder = bmgr.getFolder(newFolder.getId()); assertNull(folder); - + log.info("END"); } - - + + /** * Make sure that deleting a folder deletes all child folders. */ public void testFolderCascadingDelete() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + // add a small tree /fold1/fold2 WeblogBookmarkFolder fold1 = new WeblogBookmarkFolder(root, "fold1", null, testWeblog); root.addFolder(fold1); @@ -173,7 +173,7 @@ public void testFolderCascadingDelete() throws Exception { fold1.addFolder(fold2); bmgr.saveFolder(fold2); TestUtils.endSession(true); - + // check that tree can be navigated testWeblog = TestUtils.getManagedWebsite(testWeblog); root = bmgr.getRootFolder(testWeblog); @@ -183,18 +183,18 @@ public void testFolderCascadingDelete() throws Exception { assertEquals(1, fold1.getFolders().size()); fold2 = (WeblogBookmarkFolder) fold1.getFolders().iterator().next(); assertEquals("fold2", fold2.getName()); - + // now delete folder and subfolders should be deleted by cascade bmgr.removeFolder(fold1); TestUtils.endSession(true); - + // verify cascading delete succeeded testWeblog = TestUtils.getManagedWebsite(testWeblog); root = bmgr.getRootFolder(testWeblog); assertEquals(0, root.getFolders().size()); assertNull(bmgr.getFolder(testWeblog, "/fold1/fold2")); - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderFunctionalityTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderFunctionalityTest.java index 2604f8ebab..b248aab756 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderFunctionalityTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderFunctionalityTest.java @@ -35,51 +35,51 @@ * Test folder business functions and lookups. */ public class FolderFunctionalityTest extends TestCase { - + public static Log log = LogFactory.getLog(FolderFunctionalityTest.class); - + User testUser = null; Weblog testWeblog = null; WeblogBookmarkFolder f1 = null; WeblogBookmarkFolder f2 = null; WeblogBookmarkFolder f3 = null; WeblogBookmarkFolder testFolder = null; - + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + log.info("BEGIN"); - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("folderFuncTestUser"); testWeblog = TestUtils.setupWeblog("folderFuncTestWeblog", testUser); - + // setup a category tree to use for testing f1 = TestUtils.setupFolder(testWeblog, "folderFuncTest-f1", null); f2 = TestUtils.setupFolder(testWeblog, "folderFuncTest-f2", f1); f3 = TestUtils.setupFolder(testWeblog, "folderFuncTest-f3", f2); - + // a simple test folder at the root level testFolder = TestUtils.setupFolder(testWeblog, "folderFuncTest-testFolder", null); - + TestUtils.endSession(true); } catch (Exception ex) { log.error(ex); throw new Exception("Test setup failed", ex); } - + log.info("END"); } - + public void tearDown() throws Exception { - + log.info("BEGIN"); - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -88,28 +88,28 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + log.info("END"); } - - + + /** * Test that we can walk a folder tree. */ public void testWalkFolderTree() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + // start at root WeblogBookmarkFolder root = bmgr.getRootFolder(TestUtils.getManagedWebsite(testWeblog)); - + // walk first level Set folders = root.getFolders(); assertEquals(2, folders.size()); assertTrue(folders.contains(testFolder)); - + // find cat1 WeblogBookmarkFolder folder = null; for(Iterator it = folders.iterator(); it.hasNext(); ) { @@ -118,55 +118,55 @@ public void testWalkFolderTree() throws Exception { break; } } - + // walk second level folders = folder.getFolders(); assertEquals(1, folders.size()); assertTrue(folders.contains(f2)); - + // find cat2 folder = (WeblogBookmarkFolder) folders.iterator().next(); - + // walk third level folders = folder.getFolders(); assertEquals(1, folders.size()); assertTrue(folders.contains(f3)); - + // find cat3 folder = (WeblogBookmarkFolder) folders.iterator().next(); - + // make sure this is the end of the tree folders = folder.getFolders(); assertEquals(0, folders.size()); - + log.info("END"); } - - + + /** * Test the hasFolder() method on WeblogBookmarkFolder. */ public void testHasFolder() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + // check that root has folder assertTrue(root.hasFolder(testFolder.getName())); - + log.info("END"); } - - - /** - * Ensure that duplicate folder name will throw WebloggerException + + + /** + * Ensure that duplicate folder name will throw WebloggerException */ public void testUniquenessOfFolderNames() throws Exception { - + log.info("BEGIN"); try { BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); @@ -185,82 +185,82 @@ public void testUniquenessOfFolderNames() throws Exception { } assertTrue(exception); - + } catch (Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(sw.toString()); - } + } TestUtils.endSession(true); log.info("END"); } - - + + /** * Test folder lookup by id. */ public void testLookupFolderById() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + // test lookup by id WeblogBookmarkFolder testFolder = bmgr.getFolder(f1.getId()); assertNotNull(testFolder); assertEquals(f1, testFolder); - + log.info("END"); } - - + + /** * Test folder lookup by id. */ public void testLookupFolderByPath() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder folder = bmgr.getFolder(testWeblog, "/folderFuncTest-f1"); assertNotNull(folder); assertEquals(f1, folder); - + folder = bmgr.getFolder(testWeblog, "/folderFuncTest-f1/folderFuncTest-f2/folderFuncTest-f3"); assertNotNull(folder); assertEquals(f3, folder); - + // test lazy lookup, with no slashes folder = bmgr.getFolder(testWeblog, "folderFuncTest-f1"); assertNotNull(folder); assertEquals(f1, folder); - + // if no path is specified then we should get root folder folder = bmgr.getFolder(testWeblog, null); assertNotNull(folder); assertEquals("/", folder.getPath()); - + log.info("END"); } - - + + public void testLookupAllFoldersByWeblog() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + // get all folders, including root testWeblog = TestUtils.getManagedWebsite(testWeblog); List allFolders = bmgr.getAllFolders(testWeblog); assertNotNull(allFolders); assertEquals(5, allFolders.size()); - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderParentDeletesTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderParentDeletesTest.java index ee8468838b..d26a5a90c5 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderParentDeletesTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/FolderParentDeletesTest.java @@ -35,22 +35,22 @@ * Test deleting of Folder parent objects to test cascading deletes. */ public class FolderParentDeletesTest extends TestCase { - + public static Log log = LogFactory.getLog(FolderFunctionalityTest.class); - + User testUser = null; Weblog testWeblog = null; - + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + log.info("BEGIN"); - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("folderParentDeletesTestUser"); testWeblog = TestUtils.setupWeblog("folderParentDeletesTestWeblog", testUser); @@ -59,14 +59,14 @@ public void setUp() throws Exception { log.error(ex); throw new Exception("Test setup failed", ex); } - + log.info("END"); } - + public void tearDown() throws Exception { - + log.info("BEGIN"); - + try { TestUtils.teardownUser(testUser.getUserName()); TestUtils.endSession(true); @@ -74,35 +74,35 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + log.info("END"); } - - + + /** * Test that deleting a folders parent object deletes all folders. */ public void testFolderParentDeletes() throws Exception { - + log.info("BEGIN"); - + BookmarkManager bmgr = WebloggerFactory.getWeblogger().getBookmarkManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogBookmarkFolder root = bmgr.getRootFolder(testWeblog); - + // add a small tree /parentDelete-fold1/parentDelete-fold2 WeblogBookmarkFolder fold1 = new WeblogBookmarkFolder( root, "parentDelete-fold1", null, TestUtils.getManagedWebsite(testWeblog)); root.addFolder(fold1); bmgr.saveFolder(fold1); - + WeblogBookmarkFolder fold2 = new WeblogBookmarkFolder( fold1, "parentDelete-fold2", null, TestUtils.getManagedWebsite(testWeblog)); fold1.addFolder(fold2); bmgr.saveFolder(fold2); TestUtils.endSession(true); - + // now delete the weblog owning these categories Exception ex = null; try { @@ -112,8 +112,8 @@ public void testFolderParentDeletes() throws Exception { ex = e; } assertNull(ex); - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/HitCountTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/HitCountTest.java index ee034b182e..4f42cdc1ca 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/HitCountTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/HitCountTest.java @@ -35,31 +35,31 @@ * Test HitCount related business operations. */ public class HitCountTest extends TestCase { - + public static Log log = LogFactory.getLog(HitCountTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + public HitCountTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(HitCountTest.class); } - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("hitCountTestUser"); testWeblog = TestUtils.setupWeblog("hitCountTestWeblog", testUser); @@ -69,9 +69,9 @@ public void setUp() throws Exception { throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -81,75 +81,75 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testHitCountCRUD() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + WeblogHitCount testCount = new WeblogHitCount(); testCount.setWeblog(testWeblog); testCount.setDailyHits(10); - + // create mgr.saveHitCount(testCount); String id = testCount.getId(); TestUtils.endSession(true); - + // make sure it was created WeblogHitCount hitCount = null; hitCount = mgr.getHitCount(id); assertNotNull(hitCount); assertEquals(testCount, hitCount); assertEquals(10, hitCount.getDailyHits()); - + // update hitCount.setDailyHits(25); mgr.saveHitCount(hitCount); TestUtils.endSession(true); - + // make sure it was updated hitCount = null; hitCount = mgr.getHitCount(id); assertNotNull(hitCount); assertEquals(testCount, hitCount); assertEquals(25, hitCount.getDailyHits()); - + // delete mgr.removeHitCount(hitCount); TestUtils.endSession(true); - + // make sure it was deleted hitCount = null; hitCount = mgr.getHitCount(id); assertNull(hitCount); } - - + + public void testHitCountLookups() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogHitCount testCount = new WeblogHitCount(); testCount.setWeblog(testWeblog); testCount.setDailyHits(10); - + // create mgr.saveHitCount(testCount); String id = testCount.getId(); TestUtils.endSession(true); - + // test lookup by id WeblogHitCount hitCount = null; hitCount = mgr.getHitCount(id); assertNotNull(hitCount); assertEquals(testCount, hitCount); assertEquals(10, hitCount.getDailyHits()); - + // test lookup by weblog hitCount = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); @@ -157,75 +157,75 @@ public void testHitCountLookups() throws Exception { assertNotNull(hitCount); assertEquals(testCount, hitCount); assertEquals(10, hitCount.getDailyHits()); - + // delete mgr.removeHitCount(hitCount); TestUtils.endSession(true); - + // make sure it was deleted hitCount = null; hitCount = mgr.getHitCount(id); assertNull(hitCount); } - - + + public void testIncrementHitCount() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + WeblogHitCount testCount = new WeblogHitCount(); testWeblog = TestUtils.getManagedWebsite(testWeblog); testCount.setWeblog(testWeblog); testCount.setDailyHits(10); - + // create mgr.saveHitCount(testCount); String id = testCount.getId(); TestUtils.endSession(true); - + // make sure it was created WeblogHitCount hitCount = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); hitCount = mgr.getHitCountByWeblog(testWeblog); assertNotNull(hitCount); assertEquals(10, hitCount.getDailyHits()); - + // increment mgr.incrementHitCount(testWeblog, 25); TestUtils.endSession(true); - + // make sure it was incremented properly hitCount = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); hitCount = mgr.getHitCountByWeblog(testWeblog); assertNotNull(hitCount); assertEquals(35, hitCount.getDailyHits()); - + // delete mgr.removeHitCount(hitCount); TestUtils.endSession(true); - + // make sure it was deleted hitCount = null; hitCount = mgr.getHitCount(id); assertNull(hitCount); } - - + + public void testResetHitCounts() throws Exception { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testUser = TestUtils.getManagedUser(testUser); Weblog blog1 = TestUtils.setupWeblog("hitCntTest1", testUser); Weblog blog2 = TestUtils.setupWeblog("hitCntTest2", testUser); Weblog blog3 = TestUtils.setupWeblog("hitCntTest3", testUser); - + WeblogHitCount cnt1 = TestUtils.setupHitCount(blog1, 10); WeblogHitCount cnt2 = TestUtils.setupHitCount(blog2, 20); WeblogHitCount cnt3 = TestUtils.setupHitCount(blog3, 30); - + TestUtils.endSession(true); - + try { // make sure data was properly initialized WeblogHitCount testCount = null; @@ -260,7 +260,7 @@ public void testResetHitCounts() throws Exception { assertEquals(0, testCount.getDailyHits()); testCount = mgr.getHitCount(cnt3.getId()); assertEquals(0, testCount.getDailyHits()); - + } finally { // cleanup TestUtils.teardownHitCount(cnt1.getId()); @@ -272,22 +272,22 @@ public void testResetHitCounts() throws Exception { } } - + public void testHotWeblogs() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testUser = TestUtils.getManagedUser(testUser); Weblog blog1 = TestUtils.setupWeblog("hitCntHotTest1", testUser); Weblog blog2 = TestUtils.setupWeblog("hitCntHotTest2", testUser); Weblog blog3 = TestUtils.setupWeblog("hitCntHotTest3", testUser); - + WeblogHitCount cnt1 = TestUtils.setupHitCount(blog1, 10); WeblogHitCount cnt2 = TestUtils.setupHitCount(blog2, 20); WeblogHitCount cnt3 = TestUtils.setupHitCount(blog3, 30); - + TestUtils.endSession(true); - + // make sure data was properly initialized WeblogHitCount testCount = null; testCount = mgr.getHitCount(cnt1.getId()); @@ -296,21 +296,21 @@ public void testHotWeblogs() throws Exception { assertEquals(20, testCount.getDailyHits()); testCount = mgr.getHitCount(cnt3.getId()); assertEquals(30, testCount.getDailyHits()); - + // get hot weblogs List hotBlogs = mgr.getHotWeblogs(1, 0, 5); assertNotNull(hotBlogs); assertEquals(3, hotBlogs.size()); - + // also check ordering and values WeblogHitCount hitCount = null; Iterator it = hotBlogs.iterator(); for(int i=3; it.hasNext(); i--) { hitCount = (WeblogHitCount) it.next(); - + assertEquals(i*10, hitCount.getDailyHits()); } - + // cleanup TestUtils.teardownHitCount(cnt1.getId()); TestUtils.teardownHitCount(cnt2.getId()); diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/IndexManagerTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/IndexManagerTest.java index 08126b6b2b..043b269976 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/IndexManagerTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/IndexManagerTest.java @@ -40,12 +40,12 @@ public class IndexManagerTest extends TestCase { User testUser = null; Weblog testWeblog = null; - public static Log log = LogFactory.getLog(IndexManagerTest.class); + public static Log log = LogFactory.getLog(IndexManagerTest.class); public IndexManagerTest(String name) { super(name); } - + public static Test suite() { return new TestSuite(IndexManagerTest.class); } @@ -54,10 +54,10 @@ public static Test suite() { * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("entryTestUser"); testWeblog = TestUtils.setupWeblog("entryTestWeblog", testUser); @@ -65,15 +65,15 @@ public void setUp() throws Exception { //WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); //assertEquals(1, wmgr.getWeblogCount()); - + } catch (Exception ex) { log.error("ERROR in test setup", ex); throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -83,11 +83,11 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - + public void testSearch() throws Exception { WeblogEntryManager wem = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - WeblogEntry wd1 = new WeblogEntry(); + WeblogEntry wd1 = new WeblogEntry(); wd1.setTitle("The Tholian Web"); wd1.setText( "When the Enterprise attempts to ascertain the fate of the " @@ -154,5 +154,5 @@ public void testSearch() throws Exception { search3.setTerm("Enterprise"); imgr.executeIndexOperationNow(search3); assertEquals(0, search3.getResultsCount()); - } + } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/MediaFileTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/MediaFileTest.java index 54ab2ee261..d215b62d4f 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/MediaFileTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/MediaFileTest.java @@ -256,9 +256,9 @@ public void testGetMediaFileDirectories() throws Exception { } /** - * Test utility to determine whether the given list of directories + * Test utility to determine whether the given list of directories * contains a directory of given path. - * + * */ private boolean containsPath(Collection directories, String path) { for (MediaFileDirectory directory : directories) { @@ -272,7 +272,7 @@ private boolean containsPath(Collection directories, String /** * Test utility to determine whether the list of files contains a file with given name. - * + * */ private boolean containsFileWithName(Collection files, String name) { for (MediaFile file : files) { @@ -432,7 +432,7 @@ public void testSearchMediaFile() throws Exception { MediaFileDirectory rootDirectory = mfMgr.getMediaFileRootDirectory(testWeblog); try { - + String id1 = null; { MediaFile mf = new MediaFile(); @@ -446,7 +446,7 @@ public void testSearchMediaFile() throws Exception { mf.setInputStream(getClass().getResourceAsStream(TEST_IMAGE)); mf.setContentType("image/jpeg"); rootDirectory.getMediaFiles().add(mf); - + mfMgr.createMediaFile(testWeblog, mf, new RollerMessages()); MediaFileTag tag = new MediaFileTag("work", mf); @@ -454,19 +454,19 @@ public void testSearchMediaFile() throws Exception { tags.add(tag); mf.setTags(tags); mfMgr.updateMediaFile(testWeblog, mf); - + mfMgr.createMediaFile(testWeblog, mf, new RollerMessages()); TestUtils.endSession(true); id1 = mf.getId(); assertNotNull(mf.getId()); assertNotNull(mf.getId().length() > 0); } - + String id2 = null; { testWeblog = TestUtils.getManagedWebsite(testWeblog); rootDirectory = mfMgr.getMediaFileDirectory(rootDirectory.getId()); - + MediaFile mf = new MediaFile(); mf = new MediaFile(); mf.setName("test_home.jpg"); @@ -479,7 +479,7 @@ public void testSearchMediaFile() throws Exception { mf.setInputStream(getClass().getResourceAsStream(TEST_IMAGE)); mf.setContentType("image/jpeg"); rootDirectory.getMediaFiles().add(mf); - + mfMgr.createMediaFile(testWeblog, mf, new RollerMessages()); MediaFileTag tag = new MediaFileTag("home", mf); @@ -487,18 +487,18 @@ public void testSearchMediaFile() throws Exception { tags.add(tag); mf.setTags(tags); mfMgr.updateMediaFile(testWeblog, mf); - + TestUtils.endSession(true); id2 = mf.getId(); assertNotNull(mf.getId()); assertNotNull(mf.getId().length() > 0); } - + String id3 = null; { testWeblog = TestUtils.getManagedWebsite(testWeblog); rootDirectory = mfMgr.getMediaFileDirectory(rootDirectory.getId()); - + MediaFile mf = new MediaFile(); mf = new MediaFile(); mf.setName("test_pers.jpg"); @@ -511,7 +511,7 @@ public void testSearchMediaFile() throws Exception { mf.setInputStream(getClass().getResourceAsStream(TEST_IMAGE)); mf.setContentType("image/jpeg"); rootDirectory.getMediaFiles().add(mf); - + mfMgr.createMediaFile(testWeblog, mf, new RollerMessages()); MediaFileTag tag = new MediaFileTag("home", mf); @@ -519,15 +519,15 @@ public void testSearchMediaFile() throws Exception { tags.add(tag); mf.setTags(tags); mfMgr.updateMediaFile(testWeblog, mf); - + TestUtils.endSession(true); id3 = mf.getId(); assertNotNull(mf.getId()); assertNotNull(mf.getId().length() > 0); } - + testWeblog = TestUtils.getManagedWebsite(testWeblog); - + List searchResults; // search by name @@ -646,19 +646,19 @@ public void testSearchMediaFilePaging() throws Exception { Weblog testWeblog = null; testUser = TestUtils.setupUser("mediaFileTestUser9"); testWeblog = TestUtils.setupWeblog("mediaFileTestWeblog9", testUser); - + try { MediaFileManager mfMgr = WebloggerFactory.getWeblogger().getMediaFileManager(); - + // no need to create root directory, that is done automatically now MediaFileDirectory rootDirectory = mfMgr.getMediaFileRootDirectory(testWeblog); - + //MediaFileDirectory rootDirectory = new MediaFileDirectory(null, "root", "root d", testWeblog); //mfMgr.createMediaFileDirectory(rootDirectory); //TestUtils.endSession(true); - + for (int i = 0; i < 15; i++) { - rootDirectory = mfMgr.getMediaFileDirectory(rootDirectory.getId()); + rootDirectory = mfMgr.getMediaFileDirectory(rootDirectory.getId()); testWeblog = TestUtils.getManagedWebsite(testWeblog); MediaFile mediaFile = new MediaFile(); mediaFile.setName("test_file.jpg".replace("", i + "")); @@ -676,7 +676,7 @@ public void testSearchMediaFilePaging() throws Exception { assertNotNull(mediaFile.getId().length() > 0); TestUtils.endSession(true); } - + testWeblog = TestUtils.getManagedWebsite(testWeblog); MediaFileFilter filter1 = new MediaFileFilter(); filter1.setSize(1000); @@ -684,7 +684,7 @@ public void testSearchMediaFilePaging() throws Exception { List searchResults1 = mfMgr.searchMediaFiles(testWeblog, filter1); assertFalse(searchResults1.isEmpty()); assertEquals(15, searchResults1.size()); - + MediaFileFilter filter2 = new MediaFileFilter(); filter2.setSize(1000); filter2.setSizeFilterType(SizeFilterType.GT); @@ -694,7 +694,7 @@ public void testSearchMediaFilePaging() throws Exception { assertFalse(searchResults2.isEmpty()); assertEquals(3, searchResults2.size()); assertEquals("test_file13.jpg", searchResults2.get(0).getName()); - + MediaFileFilter filter3 = new MediaFileFilter(); filter3.setSize(1000); filter3.setSizeFilterType(SizeFilterType.GT); @@ -704,7 +704,7 @@ public void testSearchMediaFilePaging() throws Exception { assertFalse(searchResults3.isEmpty()); assertEquals(2, searchResults3.size()); assertEquals("test_file8.jpg", searchResults3.get(0).getName()); - + MediaFileFilter filter4 = new MediaFileFilter(); filter4.setSize(1000); filter4.setSizeFilterType(SizeFilterType.GT); @@ -714,7 +714,7 @@ public void testSearchMediaFilePaging() throws Exception { assertFalse(searchResults4.isEmpty()); assertEquals(1, searchResults4.size()); assertEquals("test_file9.jpg", searchResults4.get(0).getName()); - + TestUtils.endSession(true); } finally { TestUtils.teardownWeblog(testWeblog.getId()); @@ -1040,7 +1040,7 @@ public void testMoveDirectoryContents() throws Exception { mediaFiles = rootDirectory.getMediaFiles(); assertEquals(0, mediaFiles.size()); - + } finally { TestUtils.endSession(true); TestUtils.teardownWeblog(testWeblog.getId()); @@ -1094,7 +1094,7 @@ public void testStorageUpgrade() throws Exception { } finally { - File statusFile = new File(WebloggerConfig.getProperty("uploads.dir") + File statusFile = new File(WebloggerConfig.getProperty("uploads.dir") + File.separator + JPAMediaFileManagerImpl.MIGRATION_STATUS_FILENAME); statusFile.delete(); diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java index 162f4aa1fa..5ca41bff66 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java @@ -37,33 +37,33 @@ * Test User/Weblog Permissions related business operations. */ public class PermissionTest extends TestCase { - + public static Log log = LogFactory.getLog(PermissionTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + public PermissionTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(PermissionTest.class); } - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + log.info("BEGIN"); - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("permsTestUser"); testWeblog = TestUtils.setupWeblog("permsTestWeblog", testUser); @@ -72,14 +72,14 @@ public void setUp() throws Exception { log.error("ERROR in setup", ex); throw new Exception("Test setup failed", ex); } - + log.info("END"); } - + public void tearDown() throws Exception { - + log.info("BEGIN"); - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -88,34 +88,34 @@ public void tearDown() throws Exception { log.error("ERROR in tear down", ex); throw new Exception("Test teardown failed", ex); } - + log.info("END"); } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testPermissionsCRUD() throws Exception { - + log.info("BEGIN"); - + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); - - WeblogPermission p1 = new WeblogPermission(testWeblog, testUser, + + WeblogPermission p1 = new WeblogPermission(testWeblog, testUser, WeblogPermission.ADMIN + "," + WeblogPermission.POST); assertTrue(p1.hasAction(WeblogPermission.POST)); assertTrue(p1.hasAction(WeblogPermission.ADMIN)); assertEquals(2, p1.getActionsAsList().size()); - - WeblogPermission p2 = new WeblogPermission(testWeblog, testUser, + + WeblogPermission p2 = new WeblogPermission(testWeblog, testUser, WeblogPermission.EDIT_DRAFT); p1.addActions(p2); assertEquals(3, p1.getActionsAsList().size()); - - + + WeblogPermission perm = null; - + // delete permissions testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); @@ -123,21 +123,21 @@ public void testPermissionsCRUD() throws Exception { assertNotNull(perm); mgr.revokeWeblogPermission(testWeblog, testUser, WeblogPermission.ALL_ACTIONS); TestUtils.endSession(true); - + // check that delete was successful perm = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); perm = mgr.getWeblogPermission(testWeblog, testUser); assertNull(perm); - + // create permissions List actions = new ArrayList(); actions.add(WeblogPermission.ADMIN); actions.add(WeblogPermission.POST); mgr.grantWeblogPermission(testWeblog, testUser, actions); TestUtils.endSession(true); - + // check that create was successful testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); @@ -147,13 +147,13 @@ public void testPermissionsCRUD() throws Exception { assertTrue(perm.hasAction(WeblogPermission.POST)); assertTrue(perm.hasAction(WeblogPermission.ADMIN)); TestUtils.endSession(true); - + // revoke those same permissions mgr.revokeWeblogPermission(perm.getWeblog(), perm.getUser(), WeblogPermission.ALL_ACTIONS); TestUtils.endSession(true); - + // add only draft permission - mgr.grantWeblogPermission(testWeblog, testUser, + mgr.grantWeblogPermission(testWeblog, testUser, Collections.singletonList(WeblogPermission.EDIT_DRAFT)); TestUtils.endSession(true); @@ -166,18 +166,18 @@ public void testPermissionsCRUD() throws Exception { assertTrue(perm.hasAction(WeblogPermission.EDIT_DRAFT)); assertFalse(perm.hasAction(WeblogPermission.POST)); assertFalse(perm.hasAction(WeblogPermission.ADMIN)); - + log.info("END"); - } - - + } + + /** * Test lookup mechanisms. */ public void testPermissionsLookups() throws Exception { - + log.info("BEGIN"); - + // we need a second user for this test User user = TestUtils.setupUser("testPermissionsLookups"); TestUtils.endSession(true); @@ -209,12 +209,12 @@ public void testPermissionsLookups() throws Exception { // get pending permissions for a weblog perms = mgr.getWeblogPermissionsPending(TestUtils.getManagedWebsite(testWeblog)); - assertEquals(1, perms.size()); + assertEquals(1, perms.size()); // get permissions for a specific user/weblog perm = null; perm = mgr.getWeblogPermission( - TestUtils.getManagedWebsite(testWeblog), + TestUtils.getManagedWebsite(testWeblog), TestUtils.getManagedUser(testUser)); assertNotNull(perm); assertTrue(perm.hasAction(WeblogPermission.ADMIN)); @@ -222,17 +222,17 @@ public void testPermissionsLookups() throws Exception { // pending permissions should not be visible perm = null; perm = mgr.getWeblogPermission( - TestUtils.getManagedWebsite(testWeblog), + TestUtils.getManagedWebsite(testWeblog), TestUtils.getManagedUser(user)); assertNull(perm); - + List pendings = mgr.getWeblogPermissionsPending(user); // cleanup TestUtils.teardownPermissions(pendings.get(0)); TestUtils.teardownUser(user.getUserName()); TestUtils.endSession(true); - + log.info("END"); } @@ -241,9 +241,9 @@ public void testPermissionsLookups() throws Exception { * Tests weblog invitation process. */ public void testInvitations() throws Exception { - + log.info("BEGIN"); - + // we need a second user for this test User user = TestUtils.setupUser("testInvitations"); TestUtils.endSession(true); @@ -294,33 +294,33 @@ public void testInvitations() throws Exception { // cleanup the extra test user TestUtils.teardownUser(user.getUserName()); TestUtils.endSession(true); - + log.info("END"); } - - + + /** * Tests weblog invitation process. */ public void testPermissionChecks() throws Exception { - + log.info("BEGIN"); - - WeblogPermission perm = + + WeblogPermission perm = new WeblogPermission(testWeblog, testUser, WeblogPermission.POST); UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); assertTrue(umgr.checkPermission(perm, testUser)); - + // we need a second user for this test User adminUser = TestUtils.setupUser("adminUser"); umgr.grantRole("admin", adminUser); TestUtils.endSession(true); // because adminUser is a global admin, they should have POST perm - WeblogPermission perm2 = + WeblogPermission perm2 = new WeblogPermission(testWeblog, testUser, WeblogPermission.POST); assertTrue(umgr.checkPermission(perm, testUser)); - + log.info("END"); } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PingsTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PingsTest.java index 3acc3c1784..ffe748bc85 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PingsTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PingsTest.java @@ -43,33 +43,33 @@ * Test Pings related business operations. */ public class PingsTest extends TestCase { - + public static Log log = LogFactory.getLog(PingsTest.class); - + User testUser = null; Weblog testWeblog = null; PingTarget testCommonPing = null; PingTarget testCustomPing = null; - - + + public PingsTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(PingsTest.class); } - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("wtTestUser"); testWeblog = TestUtils.setupWeblog("wtTestWeblog", testUser); @@ -78,18 +78,18 @@ public void setUp() throws Exception { log.error(ex); throw new Exception("Test setup failed", ex); } - + testCommonPing = new PingTarget(); testCommonPing.setName("testCommonPing"); testCommonPing.setPingUrl("http://localhost/testCommonPing"); - + testCustomPing = new PingTarget(); testCustomPing.setName("testCustomPing"); testCustomPing.setPingUrl("http://localhost/testCustomPing"); } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -98,214 +98,214 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + testCommonPing = null; testCustomPing = null; } - - + + /** * Test basic persistence operations ... Create, Update, Delete */ public void testPingTargetCRUD() throws Exception { - + PingTargetManager mgr = WebloggerFactory.getWeblogger().getPingTargetManager(); PingTarget ping = null; - + // create common ping mgr.savePingTarget(testCommonPing); String commonId = testCommonPing.getId(); TestUtils.endSession(true); - + // make sure common ping was stored ping = null; ping = mgr.getPingTarget(commonId); assertNotNull(ping); assertEquals(testCommonPing.getPingUrl(), ping.getPingUrl()); - + // create custom ping testCustomPing.setWebsite(TestUtils.getManagedWebsite(testWeblog)); mgr.savePingTarget(testCustomPing); String customId = testCustomPing.getId(); TestUtils.endSession(true); - + // make sure custom ping was stored ping = null; ping = mgr.getPingTarget(customId); assertNotNull(ping); assertEquals(testCustomPing.getPingUrl(), ping.getPingUrl()); - + // update common ping ping = null; ping = mgr.getPingTarget(commonId); ping.setName("testtestCommon"); mgr.savePingTarget(ping); TestUtils.endSession(true); - + // make sure common ping was updated ping = null; ping = mgr.getPingTarget(commonId); assertNotNull(ping); assertEquals("testtestCommon", ping.getName()); - + // update custom ping ping = null; ping = mgr.getPingTarget(customId); ping.setName("testtestCustom"); mgr.savePingTarget(ping); TestUtils.endSession(true); - + // make sure custom ping was updated ping = null; ping = mgr.getPingTarget(customId); assertNotNull(ping); assertEquals("testtestCustom", ping.getName()); - + // delete common ping ping = null; ping = mgr.getPingTarget(commonId); mgr.removePingTarget(ping); TestUtils.endSession(true); - + // make sure common ping was deleted ping = null; ping = mgr.getPingTarget(commonId); assertNull(ping); - + // delete custom ping ping = null; ping = mgr.getPingTarget(customId); mgr.removePingTarget(ping); TestUtils.endSession(true); - + // make sure custom ping was deleted ping = null; ping = mgr.getPingTarget(customId); assertNull(ping); } - - + + /** * Test lookup mechanisms ... id, all common, all custom for weblog */ public void testPingTargetLookups() throws Exception { - + PingTargetManager mgr = WebloggerFactory.getWeblogger().getPingTargetManager(); PingTarget ping = null; - + // create common ping mgr.savePingTarget(testCommonPing); String commonId = testCommonPing.getId(); TestUtils.endSession(true); - + // create custom ping testWeblog = TestUtils.getManagedWebsite(testWeblog); testCustomPing.setWebsite(testWeblog); mgr.savePingTarget(testCustomPing); String customId = testCustomPing.getId(); TestUtils.endSession(true); - + // lookup by id ping = null; ping = mgr.getPingTarget(commonId); assertNotNull(ping); assertEquals(testCommonPing.getName(), ping.getName()); - + // lookup all common pings List commonPings = mgr.getCommonPingTargets(); assertNotNull(commonPings); // correct answer is: 6 pings in config + 1 new one = 7 assertEquals(7, commonPings.size()); - + // lookup all custom pings for weblog testWeblog = TestUtils.getManagedWebsite(testWeblog); List customPings = mgr.getCustomPingTargets(testWeblog); assertNotNull(customPings); assertEquals(1, customPings.size()); - + // delete common ping ping = null; ping = mgr.getPingTarget(commonId); mgr.removePingTarget(ping); TestUtils.endSession(true); - + // delete custom ping ping = null; ping = mgr.getPingTarget(customId); mgr.removePingTarget(ping); TestUtils.endSession(true); } - - + + /** * Test basic persistence operations ... Create, Update, Delete */ public void testAutoPingCRUD() throws Exception { - + AutoPingManager mgr = WebloggerFactory.getWeblogger().getAutopingManager(); PingTargetManager pingMgr = WebloggerFactory.getWeblogger().getPingTargetManager(); AutoPing autoPing = null; - + // create ping target to use for tests PingTarget pingTarget = TestUtils.setupPingTarget("fooPing", "http://foo/null"); PingTarget pingTarget2 = TestUtils.setupPingTarget("blahPing", "http://blah/null"); TestUtils.endSession(true); - + // create autoPing autoPing = new AutoPing(null, pingTarget, testWeblog); mgr.saveAutoPing(autoPing); String id = autoPing.getId(); TestUtils.endSession(true); - + // make sure autoPing was stored autoPing = null; autoPing = mgr.getAutoPing(id); assertNotNull(autoPing); assertEquals(pingTarget, autoPing.getPingTarget()); - + // update autoPing autoPing.setPingTarget(pingMgr.getPingTarget(pingTarget2.getId())); mgr.saveAutoPing(autoPing); TestUtils.endSession(true); - + // make sure autoPing was updated autoPing = null; autoPing = mgr.getAutoPing(id); assertNotNull(autoPing); assertEquals(pingTarget2, autoPing.getPingTarget()); - + // delete autoPing mgr.removeAutoPing(autoPing); TestUtils.endSession(true); - + // make sure common autoPing was deleted autoPing = null; autoPing = mgr.getAutoPing(id); assertNull(autoPing); - + // teardown test ping target TestUtils.teardownPingTarget(pingTarget.getId()); TestUtils.teardownPingTarget(pingTarget2.getId()); TestUtils.endSession(true); } - - + + /** * Test special ping target removal methods ... by weblog/target, collection, all */ public void testPingTargetRemovals() throws Exception { - + AutoPingManager mgr = WebloggerFactory.getWeblogger().getAutopingManager(); PingTargetManager ptmgr = WebloggerFactory.getWeblogger().getPingTargetManager(); AutoPing testAutoPing = null; - + // create ping target to use for tests PingTarget pingTarget = TestUtils.setupPingTarget("fooPing", "http://foo/null"); PingTarget pingTarget2 = TestUtils.setupPingTarget("blahPing", "http://blah/null"); PingTarget pingTarget3 = TestUtils.setupPingTarget("gahPing", "http://gah/null"); - + try { - + // create auto pings for test testWeblog = TestUtils.getManagedWebsite(testWeblog); AutoPing autoPing = TestUtils.setupAutoPing(pingTarget, testWeblog); @@ -354,7 +354,7 @@ public void testPingTargetRemovals() throws Exception { autoPings = mgr.getAutoPingsByWebsite(testWeblog); assertNotNull(autoPings); assertEquals(0, autoPings.size()); - + } finally { // teardown test ping target TestUtils.teardownPingTarget(pingTarget.getId()); @@ -362,21 +362,21 @@ public void testPingTargetRemovals() throws Exception { TestUtils.endSession(true); } } - - + + /** * Test lookup mechanisms ... id, ping target, weblog */ public void testAutoPingLookups() throws Exception { - + AutoPingManager mgr = WebloggerFactory.getWeblogger().getAutopingManager(); PingTargetManager ptmgr = WebloggerFactory.getWeblogger().getPingTargetManager(); AutoPing autoPing = null; - + // create autoPing target to use for tests PingTarget pingTarget = TestUtils.setupPingTarget("fooPing", "http://foo/null"); TestUtils.endSession(true); - + // create autoPing testWeblog = TestUtils.getManagedWebsite(testWeblog); pingTarget = ptmgr.getPingTarget(pingTarget.getId()); @@ -384,42 +384,42 @@ public void testAutoPingLookups() throws Exception { mgr.saveAutoPing(autoPing); String id = autoPing.getId(); TestUtils.endSession(true); - + // lookup by id autoPing = null; autoPing = mgr.getAutoPing(id); assertNotNull(autoPing); assertEquals(pingTarget, autoPing.getPingTarget()); - + // lookup by ping target pingTarget = ptmgr.getPingTarget(pingTarget.getId()); List autoPings = mgr.getAutoPingsByTarget(pingTarget); assertNotNull(autoPings); assertEquals(1, autoPings.size()); - + // lookup by weblog autoPings = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); autoPings = mgr.getAutoPingsByWebsite(testWeblog); assertNotNull(autoPing); assertEquals(1, autoPings.size()); - + // delete autoPing autoPing = mgr.getAutoPing(autoPing.getId()); mgr.removeAutoPing(autoPing); TestUtils.endSession(true); - + // teardown test ping target TestUtils.teardownPingTarget(pingTarget.getId()); TestUtils.endSession(true); } - - + + public void testApplicableAutoPings() throws Exception { - + } - - + + /** * Test that we can properly remove a ping target when it has * associated elements like auto pings and ping queue entries. @@ -427,5 +427,5 @@ public void testApplicableAutoPings() throws Exception { public void testRemoveLoadedPingTarget() throws Exception { // TODO: implement this test } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java index 144cf149f3..1fe1bb6c8d 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java @@ -43,19 +43,19 @@ */ public class PlanetManagerLocalTest extends TestCase { public static Log log = LogFactory.getLog(PlanetManagerLocalTest.class); - + User testUser = null; Weblog testWeblog = null; - + public static void main(String[] args) { TestRunner.run(PlanetManagerLocalTest.class); } - + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + try { TestUtils.setupWeblogger(); TestUtils.setupPlanet(); @@ -102,20 +102,20 @@ public void setUp() throws Exception { testEntry3.setUpdateTime(new Timestamp(new Date().getTime())); testEntry3.setWebsite(testWeblog); testEntry3.setCreatorUserName(testUser.getUserName()); - testEntry3.setCategory(testWeblog.getDefaultCategory()); + testEntry3.setCategory(testWeblog.getDefaultCategory()); testEntry3.setStatus(WeblogEntry.PUBLISHED); WebloggerFactory.getWeblogger().getWeblogEntryManager().saveWeblogEntry(testEntry3); TestUtils.endSession(true); - + } catch (Exception ex) { log.error(ex); throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -125,16 +125,16 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - + public void testRefreshEntries() { - try { + try { PlanetManager planet = PlanetFactory.getPlanet().getPlanetManager(); - + // run sync task to fill aggregator with websites created by super SyncWebsitesTask syncTask = new SyncWebsitesTask(); syncTask.init(); syncTask.runTask(); - + Planet planetObject = planet.getPlanetById("zzz_default_planet_zzz"); assertNotNull(planetObject); PlanetGroup group = planet.getGroup(planetObject, "all"); @@ -142,7 +142,7 @@ public void testRefreshEntries() { RefreshRollerPlanetTask refreshTask = new RefreshRollerPlanetTask(); refreshTask.runTask(); - + planetObject = planet.getPlanet("default"); group = planet.getGroup(planetObject, "all"); List agg = planet.getEntries(group, 0, -1); @@ -153,11 +153,11 @@ public void testRefreshEntries() { fail(); } } - + public static Test suite() { return new TestSuite(PlanetManagerLocalTest.class); } - - + + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java index 0df6e83bfb..b5a15954ae 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java @@ -34,57 +34,57 @@ * Test Properties related business operations. */ public class PropertiesTest extends TestCase { - + public static Log log = LogFactory.getLog(PropertiesTest.class); - - + + public PropertiesTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(PropertiesTest.class); } - - + + public void setUp() throws Exception { // setup weblogger TestUtils.setupWeblogger(); } - + public void tearDown() throws Exception { } - - + + public void testProperiesCRUD() throws Exception { - + // remember, the properties table is initialized during Roller startup PropertiesManager mgr = WebloggerFactory.getWeblogger().getPropertiesManager(); TestUtils.endSession(true); - + RuntimeConfigProperty prop = null; - + // get a property by name prop = mgr.getProperty("site.name"); assertNotNull(prop); - + // update a property prop.setValue("testtest"); mgr.saveProperty(prop); TestUtils.endSession(true); - + // make sure property was updated prop = null; prop = mgr.getProperty("site.name"); assertNotNull(prop); assertEquals("testtest", prop.getValue()); - + // get all properties Map props = mgr.getProperties(); assertNotNull(props); assertTrue(props.containsKey("site.name")); - + // update multiple properties prop = (RuntimeConfigProperty) props.get("site.name"); prop.setValue("foofoo"); @@ -92,12 +92,12 @@ public void testProperiesCRUD() throws Exception { prop.setValue("blahblah"); mgr.saveProperties(props); TestUtils.endSession(true); - + // make sure all properties were updated props = mgr.getProperties(); assertNotNull(props); assertEquals("foofoo", ((RuntimeConfigProperty)props.get("site.name")).getValue()); assertEquals("blahblah", ((RuntimeConfigProperty)props.get("site.description")).getValue()); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/SQLScriptRunnerTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/SQLScriptRunnerTest.java index 2d7d7a81da..e1431eefd2 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/SQLScriptRunnerTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/SQLScriptRunnerTest.java @@ -42,10 +42,10 @@ public void setUp() { } } - public void testParseOnly() throws Exception { + public void testParseOnly() throws Exception { DatabaseProvider dbp = WebloggerStartup.getDatabaseProvider(); - Connection con = dbp.getConnection(); - + Connection con = dbp.getConnection(); + // normaly tests run against Derby String databaseProductName = con.getMetaData().getDatabaseProductName(); String dbname = "derby"; @@ -53,17 +53,17 @@ public void testParseOnly() throws Exception { // but some folks test against MySQL dbname = "mysql"; } - + String scriptPath = System.getProperty("project.build.directory") + "/test-classes/WEB-INF/dbscripts/dummydb/createdb-"+dbname+".sql"; SQLScriptRunner runner = new SQLScriptRunner(scriptPath); assertTrue(runner != null); - assertTrue(runner.getCommandCount() == 5); - } - + assertTrue(runner.getCommandCount() == 5); + } + public void testSimpleRun() throws Exception { DatabaseProvider dbp = WebloggerStartup.getDatabaseProvider(); - Connection con = dbp.getConnection(); + Connection con = dbp.getConnection(); // normaly tests run against Derby String databaseProductName = con.getMetaData().getDatabaseProductName(); @@ -72,19 +72,19 @@ public void testSimpleRun() throws Exception { // but some folks test against MySQL dbname = "mysql"; } - + // run script to create tables - SQLScriptRunner create = + SQLScriptRunner create = new SQLScriptRunner(System.getProperty("project.build.directory") + "/test-classes/WEB-INF/dbscripts/dummydb/createdb-"+dbname+".sql"); create.runScript(con, true); - + // check to ensure tables were created assertTrue(tableExists(con, "testrolleruser")); assertTrue(tableExists(con, "testuserrole")); - + // drop tables - SQLScriptRunner drop = + SQLScriptRunner drop = new SQLScriptRunner(System.getProperty("project.build.directory") + "/test-classes/WEB-INF/dbscripts/dummydb/droptables.sql"); drop.runScript(con, false); @@ -92,7 +92,7 @@ public void testSimpleRun() throws Exception { assertFalse(tableExists(con, "testrolleruser")); assertFalse(tableExists(con, "testuserrole")); } - + public static boolean tableExists(Connection con, String tableName) throws SQLException { String[] types = {"TABLE"}; ResultSet rs = con.getMetaData().getTables(null, null, "%", null); @@ -102,5 +102,5 @@ public static boolean tableExists(Connection con, String tableName) throws SQLEx } } return false; - } + } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/TaskLockTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/TaskLockTest.java index 16d391bcbe..66196f0d4f 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/TaskLockTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/TaskLockTest.java @@ -32,50 +32,50 @@ * Test TaskLock related business operations. */ public class TaskLockTest extends TestCase { - + public static Log log = LogFactory.getLog(TaskLockTest.class); - - + + public TaskLockTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(TaskLockTest.class); } - - + + public void setUp() throws Exception { // setup weblogger TestUtils.setupWeblogger(); } - + public void tearDown() throws Exception { } - - + + /** * Test basic persistence operations ... Create, Update, Delete. * @throws Exception if one is raised */ public void testTaskLockCRUD() throws Exception { - + ThreadManager mgr = WebloggerFactory.getWeblogger().getThreadManager(); - + // need a test task to play with TestTask task = new TestTask(); task.init(); - + // try to acquire a lock assertTrue("Failed to acquire lease.",mgr.registerLease(task)); // We don't flush here because registerLease should flush on its own TestUtils.endSession(false); - + // make sure task is locked assertFalse("Acquired lease a second time when we shouldn't have been able to.",mgr.registerLease(task)); TestUtils.endSession(false); - + // try to release a lock assertTrue("Release of lease failed.",mgr.unregisterLease(task)); // We don't flush here because unregisterLease should flush on its own @@ -86,5 +86,5 @@ public void testTaskLockCRUD() throws Exception { assertTrue("Second release failed.", mgr.unregisterLease(task)); TestUtils.endSession(false); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserAttributeTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserAttributeTest.java index 3dc125c70d..e5ed740074 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserAttributeTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserAttributeTest.java @@ -29,29 +29,29 @@ /** * Test User related business operations. */ -public class UserAttributeTest extends TestCase { +public class UserAttributeTest extends TestCase { public static Log log = LogFactory.getLog(UserAttributeTest.class); - - + + public UserAttributeTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(UserAttributeTest.class); } - - + + public void setUp() throws Exception { // setup weblogger TestUtils.setupWeblogger(); } - + public void tearDown() throws Exception { } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ @@ -62,20 +62,20 @@ public void testUserAttributeCRUD() throws Exception { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); umgr.setUserAttribute(user.getUserName(), "testattname", "testattvalue"); TestUtils.endSession(true); - + assertEquals(user.getId(), umgr.getUserByAttribute("testattname", "testattvalue").getId()); - + user = TestUtils.getManagedUser(user); user.setEnabled(Boolean.FALSE); umgr.saveUser(user); TestUtils.endSession(true); - + assertNull(umgr.getUserByAttribute("testattname", "testattvalue")); - + TestUtils.teardownUser("auser"); assertEquals(0, umgr.getUserAttributes("auser").size()); - + log.debug("END"); } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserTest.java index b1e20fbfc9..4228847da6 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/UserTest.java @@ -33,37 +33,37 @@ * Test User related business operations. */ public class UserTest extends TestCase { - + public static Log log = LogFactory.getLog(UserTest.class); - - + + public UserTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(UserTest.class); } - - + + public void setUp() throws Exception { // setup weblogger TestUtils.setupWeblogger(); } - + public void tearDown() throws Exception { } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testUserCRUD() throws Exception { - + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); User user = null; - + User testUser = new User(); testUser.setUserName("testUser"); testUser.setPassword("password"); @@ -74,28 +74,28 @@ public void testUserCRUD() throws Exception { testUser.setTimeZone("America/Los_Angeles"); testUser.setDateCreated(new java.util.Date()); testUser.setEnabled(Boolean.TRUE); - + // make sure test user does not exist user = mgr.getUserByUserName(testUser.getUserName()); assertNull(user); - + // add test user mgr.addUser(testUser); String userName = testUser.getUserName(); TestUtils.endSession(true); - + // make sure test user exists user = null; user = mgr.getUserByUserName(userName); assertNotNull(user); assertEquals(testUser, user); - + // modify user and save user.setScreenName("testtesttest"); user.setFullName("testtesttest"); mgr.saveUser(user); TestUtils.endSession(true); - + // make sure changes were saved user = null; user = mgr.getUserByUserName(userName); @@ -106,38 +106,38 @@ public void testUserCRUD() throws Exception { // remove test user mgr.removeUser(user); TestUtils.endSession(true); - + // make sure user no longer exists user = null; user = mgr.getUserByUserName(userName); assertNull(user); } - - + + /** * Test lookup mechanisms. */ public void testUserLookups() throws Exception { - + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); User user = null; - + // add test user User testUser = TestUtils.setupUser("userTestUser"); TestUtils.endSession(true); - + // lookup by username user = mgr.getUserByUserName(testUser.getUserName()); assertNotNull(user); assertEquals(testUser.getUserName(), user.getUserName()); - + // lookup by id String userName = user.getUserName(); user = null; user = mgr.getUserByUserName(userName); assertNotNull(user); assertEquals(testUser.getUserName(), user.getUserName()); - + // lookup by UserName (part) user = null; List users1 = mgr.getUsersStartingWith(testUser.getUserName().substring(0, 3), Boolean.TRUE, 0, 1); @@ -145,7 +145,7 @@ public void testUserLookups() throws Exception { user = (User) users1.get(0); assertNotNull(user); assertEquals(testUser.getUserName(), user.getUserName()); - + // lookup by Email (part) user = null; List users2 = mgr.getUsersStartingWith(testUser.getEmailAddress().substring(0, 3), Boolean.TRUE, 0, 1); @@ -153,7 +153,7 @@ public void testUserLookups() throws Exception { user = (User) users2.get(0); assertNotNull(user); assertEquals(testUser.getUserName(), user.getUserName()); - + // make sure disable users are not returned user.setEnabled(Boolean.FALSE); mgr.saveUser(user); @@ -161,28 +161,28 @@ public void testUserLookups() throws Exception { user = null; user = mgr.getUserByUserName(testUser.getUserName()); assertNull(user); - + // remove test user TestUtils.teardownUser(testUser.getUserName()); TestUtils.endSession(true); } - - + + /** * Test basic user role persistence ... Add, Remove */ public void testRoleCRUD() throws Exception { - + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); User user = null; - + // add test user User testUser = TestUtils.setupUser("roleTestUser"); TestUtils.endSession(true); - + user = mgr.getUserByUserName(testUser.getUserName()); assertNotNull(user); - + if (WebloggerConfig.getBooleanProperty("users.firstUserAdmin")) { assertEquals(2, mgr.getRoles(user).size()); assertTrue(mgr.hasRole("editor", user)); @@ -192,12 +192,12 @@ public void testRoleCRUD() throws Exception { assertTrue(mgr.hasRole("editor", user)); assertFalse(mgr.hasRole("admin", user)); } - + // remove role mgr.revokeRole("editor",user); mgr.saveUser(user); TestUtils.endSession(true); - + // check that role was removed user = null; user = mgr.getUserByUserName(testUser.getUserName()); @@ -215,7 +215,7 @@ public void testRoleCRUD() throws Exception { mgr.grantRole("editor", user); mgr.saveUser(user); TestUtils.endSession(true); - + // check that role was added user = null; user = mgr.getUserByUserName(testUser.getUserName()); @@ -234,12 +234,12 @@ public void testRoleCRUD() throws Exception { TestUtils.endSession(true); } - + /** * Test ability to remove a user with a full set of data. */ public void testRemoveLoadedUser() throws Exception { // TODO: implement testRemoveLoadedUser } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryCRUDTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryCRUDTest.java index d9d826d301..bc6d1bbb80 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryCRUDTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryCRUDTest.java @@ -33,38 +33,38 @@ * Test WeblogCategory CRUD actions. */ public class WeblogCategoryCRUDTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogCategoryCRUDTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() { - + log.info("BEGIN"); - + try { // setup weblogger TestUtils.setupWeblogger(); - + testUser = TestUtils.setupUser("categoryCRUDTestUser"); testWeblog = TestUtils.setupWeblog("categoryCRUDTestWeblog", testUser); TestUtils.endSession(true); } catch (Exception ex) { log.error(ex); } - + log.info("END"); } - + public void tearDown() { - + log.info("BEGIN"); - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -72,109 +72,109 @@ public void tearDown() { } catch (Exception ex) { log.error(ex); } - + log.info("END"); } - - + + /** * Test WeblogCategory.equals() method. */ public void testWeblogCategoryEquality() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogCategory root = mgr.getRootWeblogCategory(testWeblog); - + WeblogCategory testCat = new WeblogCategory(testWeblog, null, "root", "root", null); assertTrue(root.equals(testCat)); - + testCat = new WeblogCategory(testWeblog, root, "root", "root", null); assertFalse(root.equals(testCat)); - + log.info("END"); } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testBasicCRUD() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogCategory cat = null; List cats = null; - + // root category is always available testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogCategory root = mgr.getRootWeblogCategory(testWeblog); - + // make sure we are starting with 0 categories (beneath root) assertEquals(0, root.getWeblogCategories().size()); - + // add a new category WeblogCategory newCat = new WeblogCategory(testWeblog, root, "catTestCategory", null, null); mgr.saveWeblogCategory(newCat); TestUtils.endSession(true); - + // make sure category was added cat = null; cat = mgr.getWeblogCategory(newCat.getId()); assertNotNull(cat); assertEquals(newCat, cat); - + // make sure category count increased testWeblog = TestUtils.getManagedWebsite(testWeblog); root = mgr.getRootWeblogCategory(testWeblog); assertEquals(1, root.getWeblogCategories().size()); - + // update category cat.setName("testtest"); mgr.saveWeblogCategory(cat); TestUtils.endSession(true); - + // verify category was updated cat = null; cat = mgr.getWeblogCategory(newCat.getId()); assertNotNull(cat); assertEquals("testtest", cat.getName()); - + // remove category mgr.removeWeblogCategory(cat); TestUtils.endSession(true); - + // make sure cat was removed cat = null; cat = mgr.getWeblogCategory(newCat.getId()); assertNull(cat); - + // make sure category count decreased testWeblog = TestUtils.getManagedWebsite(testWeblog); root = mgr.getRootWeblogCategory(testWeblog); assertEquals(0, root.getWeblogCategories().size()); - + log.info("END"); } - - + + /** * Make sure that deleting a category deletes all child categories. */ public void testCategoryCascadingDelete() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + // root category is always available testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogCategory root = mgr.getRootWeblogCategory(testWeblog); - + // add a small category tree /subcat/subcat2 WeblogCategory subcat = new WeblogCategory(testWeblog, root, "subcatTest1", null, null); root.addCategory(subcat); @@ -183,7 +183,7 @@ public void testCategoryCascadingDelete() throws Exception { subcat.addCategory(subcat2); mgr.saveWeblogCategory(subcat2); TestUtils.endSession(true); - + // check that subcat tree can be navigated testWeblog = TestUtils.getManagedWebsite(testWeblog); root = mgr.getRootWeblogCategory(testWeblog); @@ -193,18 +193,18 @@ public void testCategoryCascadingDelete() throws Exception { assertEquals(1, subcat.getWeblogCategories().size()); subcat2 = (WeblogCategory) subcat.getWeblogCategories().iterator().next(); assertEquals("subcatTest2", subcat2.getName()); - + // now delete category and subcats should be deleted by cascade mgr.removeWeblogCategory(subcat); TestUtils.endSession(true); - + // verify cascading delete succeeded testWeblog = TestUtils.getManagedWebsite(testWeblog); root = mgr.getRootWeblogCategory(testWeblog); assertEquals(0, root.getWeblogCategories().size()); assertNull(mgr.getWeblogCategoryByPath(TestUtils.getManagedWebsite(testWeblog), "/subcatTest1/subcatTest2")); - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryFunctionalityTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryFunctionalityTest.java index fa3ae7acda..b63e177f67 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryFunctionalityTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryFunctionalityTest.java @@ -35,51 +35,51 @@ * Test Weblog Category related business operations. */ public class WeblogCategoryFunctionalityTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogCategoryFunctionalityTest.class); - + User testUser = null; Weblog testWeblog = null; WeblogCategory cat1 = null; WeblogCategory cat2 = null; WeblogCategory cat3 = null; WeblogCategory testCat = null; - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() { - + log.info("BEGIN"); - + try { // setup weblogger TestUtils.setupWeblogger(); - + testUser = TestUtils.setupUser("categoryTestUser"); testWeblog = TestUtils.setupWeblog("categoryTestWeblog", testUser); - + // setup a category tree to use for testing cat1 = TestUtils.setupWeblogCategory(testWeblog, "catTest-cat1", null); cat2 = TestUtils.setupWeblogCategory(testWeblog, "catTest-cat2", cat1); cat3 = TestUtils.setupWeblogCategory(testWeblog, "catTest-cat3", cat2); - + // a simple test cat at the root level testCat = TestUtils.setupWeblogCategory(testWeblog, "catTest-testCat", null); - + TestUtils.endSession(true); } catch (Throwable t) { log.error("ERROR in setup", t); } - + log.info("END"); } - + public void tearDown() { - + log.info("BEGIN"); - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -87,28 +87,28 @@ public void tearDown() { } catch (Throwable t) { log.error("ERROR in teardown", t); } - + log.info("END"); } - - + + /** * Test that we can walk a category tree. */ public void testWalkCategoryTree() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + // start at root WeblogCategory root = mgr.getRootWeblogCategory(TestUtils.getManagedWebsite(testWeblog)); - + // walk first level Set cats = root.getWeblogCategories(); assertEquals(2, cats.size()); assertTrue(cats.contains(testCat)); - + // find cat1 WeblogCategory cat = null; for(Iterator it = cats.iterator(); it.hasNext(); ) { @@ -117,137 +117,137 @@ public void testWalkCategoryTree() throws Exception { break; } } - + // walk second level cats = cat.getWeblogCategories(); assertEquals(1, cats.size()); assertTrue(cats.contains(cat2)); - + // find cat2 cat = (WeblogCategory) cats.iterator().next(); - + // walk third level cats = cat.getWeblogCategories(); assertEquals(1, cats.size()); assertTrue(cats.contains(cat3)); - + // find cat3 cat = (WeblogCategory) cats.iterator().next(); - + // make sure this is the end of the tree cats = cat.getWeblogCategories(); assertEquals(0, cats.size()); - + log.info("END"); } - - + + /** * Test the hasCategory() method on WeblogCategory. */ public void testHasCategory() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + WeblogCategory root = mgr.getRootWeblogCategory(TestUtils.getManagedWebsite(testWeblog)); - + // check that root has category assertTrue(root.hasCategory(testCat.getName())); - + log.info("END"); } - - + + /** * Lookup category by id. */ public void testLookupCategoryById() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + WeblogCategory cat = mgr.getWeblogCategory(testCat.getId()); assertNotNull(cat); assertEquals(cat, testCat); - + log.info("END"); } - - + + /** * Lookup category by path. */ public void testLookupCategoryByPath() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); WeblogCategory cat = mgr.getWeblogCategoryByPath(testWeblog, "/catTest-cat1"); assertNotNull(cat); assertEquals(cat, cat1); - + cat = mgr.getWeblogCategoryByPath(testWeblog, "/catTest-cat1/catTest-cat2/catTest-cat3"); assertNotNull(cat); assertEquals(cat, cat3); - + // test lazy lookup, specifying just a name without slashes cat = mgr.getWeblogCategoryByPath(testWeblog, "catTest-cat1"); assertNotNull(cat); assertEquals(cat, cat1); - + // if no path is specified we should get the root category cat = mgr.getWeblogCategoryByPath(testWeblog, null); assertNotNull(cat); assertEquals(cat.getPath(), "/"); - + log.info("END"); } - - + + /** * Lookup all categories for a weblog. */ public void testLookupAllCategoriesByWeblog() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + // including root testWeblog = TestUtils.getManagedWebsite(testWeblog); List cats = mgr.getWeblogCategories(testWeblog, true); assertNotNull(cats); assertEquals(5, cats.size()); - + // not including root cats = mgr.getWeblogCategories(testWeblog, false); assertNotNull(cats); assertEquals(4, cats.size()); - + log.info("END"); } - - + + /** * Test moving one category into another. */ public void testMoveWeblogCategory() throws Exception { log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); WeblogCategory root = mgr.getRootWeblogCategory(testWeblog); WeblogEntry e1 = null; - WeblogEntry e2 = null; - WeblogEntry e3 = null; - + WeblogEntry e2 = null; + WeblogEntry e3 = null; + try { // add some categories and entries to test with WeblogCategory dest = new WeblogCategory(testWeblog, root, "c0", null, null); @@ -318,8 +318,8 @@ public void testMoveWeblogCategory() throws Exception { } log.info("END"); } - - + + /** * Test moving entries in category to new category. */ @@ -327,8 +327,8 @@ public void testMoveWeblogCategoryContents() throws Exception { log.info("BEGIN"); WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry e1 = null; - WeblogEntry e2 = null; - WeblogEntry e3 = null; + WeblogEntry e2 = null; + WeblogEntry e3 = null; try { testWeblog = TestUtils.getManagedWebsite(testWeblog); @@ -384,20 +384,20 @@ public void testMoveWeblogCategoryContents() throws Exception { dest = mgr.getWeblogCategory(dest.getId()); c1 = mgr.getWeblogCategory(c1.getId()); - // Hierarchy is flattened under dest + // Hierarchy is flattened under dest assertEquals(3, dest.retrieveWeblogEntries(true).size()); assertEquals(3, dest.retrieveWeblogEntries(false).size()); // c1 category should be empty now assertEquals(0, c1.retrieveWeblogEntries(false).size()); - + } finally { mgr.removeWeblogEntry(TestUtils.getManagedWeblogEntry(e1)); mgr.removeWeblogEntry(TestUtils.getManagedWeblogEntry(e2)); mgr.removeWeblogEntry(TestUtils.getManagedWeblogEntry(e3)); } - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryParentDeletesTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryParentDeletesTest.java index 0b38831ac5..f7fecb35ff 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryParentDeletesTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogCategoryParentDeletesTest.java @@ -32,73 +32,73 @@ * Test deleting of WeblogCategory parent objects to test cascading deletes. */ public class WeblogCategoryParentDeletesTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogCategoryParentDeletesTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() { - + log.info("BEGIN"); - + try { // setup weblogger TestUtils.setupWeblogger(); - + testUser = TestUtils.setupUser("categoryParentDeletesTestUser"); testWeblog = TestUtils.setupWeblog("categoryParentDeletesTestWeblog", testUser); TestUtils.endSession(true); } catch (Exception ex) { log.error(ex); } - + log.info("END"); } - + public void tearDown() { - + log.info("BEGIN"); - + try { TestUtils.teardownUser(testUser.getUserName()); TestUtils.endSession(true); } catch (Exception ex) { log.error(ex); } - + log.info("END"); } - - + + /** * Test that deleting a categories parent object deletes all categories. */ public void testCategoryParentDeletes() throws Exception { - + log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); - + // root category is always available WeblogCategory root = mgr.getRootWeblogCategory(TestUtils.getManagedWebsite(testWeblog)); - + // add a small category tree /subcat/subcat2 WeblogCategory subcat = new WeblogCategory( TestUtils.getManagedWebsite(testWeblog), root, "categoryParentDeletes1", null, null); root.addCategory(subcat); mgr.saveWeblogCategory(subcat); - + WeblogCategory subcat2 = new WeblogCategory( TestUtils.getManagedWebsite(testWeblog), subcat, "categoryParentDeletes2", null, null); subcat.addCategory(subcat2); mgr.saveWeblogCategory(subcat2); TestUtils.endSession(true); - + // now delete the weblog owning these categories Exception ex = null; try { @@ -108,8 +108,8 @@ public void testCategoryParentDeletes() throws Exception { ex = e; } assertNull(ex); - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogEntryTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogEntryTest.java index 74d6def2fa..2068e779b0 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogEntryTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogEntryTest.java @@ -47,23 +47,23 @@ * Test WeblogEntry related business operations. */ public class WeblogEntryTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogEntryTest.class); - + User testUser = null; Weblog testWeblog = null; - - + + public WeblogEntryTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(WeblogEntryTest.class); } - - + + /** * All tests in this suite require a user and a weblog. */ @@ -71,7 +71,7 @@ public void setUp() throws Exception { // setup weblogger TestUtils.setupWeblogger(); - + assertEquals(0L, WebloggerFactory.getWeblogger().getWeblogManager().getWeblogCount()); @@ -82,15 +82,15 @@ public void setUp() throws Exception { //WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); //assertEquals(1, wmgr.getWeblogCount()); - + } catch (Exception ex) { log.error("ERROR in test setup", ex); throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -100,16 +100,16 @@ public void tearDown() throws Exception { throw new Exception("Test teardown failed", ex); } } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testWeblogEntryCRUD() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry entry = null; - + WeblogEntry testEntry = new WeblogEntry(); testEntry.setTitle("entryTestEntry"); testEntry.setLink("testEntryLink"); @@ -119,52 +119,52 @@ public void testWeblogEntryCRUD() throws Exception { testEntry.setUpdateTime(new java.sql.Timestamp(new java.util.Date().getTime())); testEntry.setWebsite(testWeblog); testEntry.setCreatorUserName(testUser.getUserName()); - + WeblogCategory cat = mgr.getWeblogCategory(testWeblog.getDefaultCategory().getId()); testEntry.setCategory(cat); - + // create a weblog entry mgr.saveWeblogEntry(testEntry); String id = testEntry.getId(); TestUtils.endSession(true); - + // make sure entry was created entry = mgr.getWeblogEntry(id); assertNotNull(entry); assertEquals(testEntry, entry); - + // update a weblog entry entry.setTitle("testtest"); mgr.saveWeblogEntry(entry); TestUtils.endSession(true); - + // make sure entry was updated entry = null; entry = mgr.getWeblogEntry(id); assertNotNull(entry); assertEquals("testtest", entry.getTitle()); - + // delete a weblog entry mgr.removeWeblogEntry(entry); TestUtils.endSession(true); - + // make sure entry was deleted entry = null; entry = mgr.getWeblogEntry(id); assertNull(entry); } - - + + /** - * Test lookup mechanisms ... + * Test lookup mechanisms ... */ public void testWeblogEntryLookups() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry entry = null; List entries = null; Map entryMap = null; - + // setup some test entries to use testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); @@ -173,179 +173,179 @@ public void testWeblogEntryLookups() throws Exception { WeblogEntry entry3 = TestUtils.setupWeblogEntry("entry3", testWeblog.getDefaultCategory(), testWeblog, testUser); WeblogEntry entry4 = TestUtils.setupWeblogEntry("entry4", testWeblog.getDefaultCategory(), testWeblog, testUser); WeblogEntry entry5 = TestUtils.setupWeblogEntry("entry5", testWeblog.getDefaultCategory(), testWeblog, testUser); - + // make a couple changes entry1.setLocale("en_US"); entry1.setStatus(WeblogEntry.PUBLISHED); entry1.setPinnedToMain(Boolean.TRUE); mgr.saveWeblogEntry(entry1); - + entry2.setLocale("ja_JP"); entry2.setStatus(WeblogEntry.PUBLISHED); entry2.setUpdateTime(new java.sql.Timestamp(entry2.getUpdateTime().getTime()+8822384)); entry2.setPubTime(entry2.getUpdateTime()); mgr.saveWeblogEntry(entry2); - + entry3.setStatus(WeblogEntry.DRAFT); entry3.setUpdateTime(new java.sql.Timestamp(entry3.getUpdateTime().getTime()+348829384)); entry3.setPubTime(entry3.getUpdateTime()); mgr.saveWeblogEntry(entry3); - + entry4.setPubTime(new java.sql.Timestamp(entry1.getPubTime().getTime() - 348829384)); entry5.setPubTime(new java.sql.Timestamp(entry1.getPubTime().getTime() - 8822384)); - + TestUtils.endSession(true); - + testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); log.debug("entry1 = "+entry1.getUpdateTime()); log.debug("entry2 = "+entry2.getUpdateTime()); log.debug("entry3 = "+entry3.getUpdateTime()); - + entry1 = TestUtils.getManagedWeblogEntry(entry1); entry2 = TestUtils.getManagedWeblogEntry(entry2); entry3 = TestUtils.getManagedWeblogEntry(entry3); entry4 = TestUtils.getManagedWeblogEntry(entry4); entry5 = TestUtils.getManagedWeblogEntry(entry5); - + // get entry by id entry = null; entry = mgr.getWeblogEntry(entry1.getId()); assertNotNull(entry); assertEquals(entry1.getAnchor(), entry.getAnchor()); - + // get entry by anchor entry = null; entry = mgr.getWeblogEntryByAnchor(testWeblog, entry1.getAnchor()); assertNotNull(entry); assertEquals(entry1.getTitle(), entry.getTitle()); - + // get all entries for weblog entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, null, null, null, null, null, null, null, 0, -1); assertNotNull(entries); assertEquals(5, entries.size()); assertEquals(entry3, entries.get(0)); - - // get all (non-future) PUBLISHED entries in category + + // get all (non-future) PUBLISHED entries in category entries = null; entries = mgr.getWeblogEntries(testWeblog.getDefaultCategory(), false); assertNotNull(entries); assertEquals(3, entries.size()); - - // get all (non-future) PUBLISHED entries only + + // get all (non-future) PUBLISHED entries only entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, null, null, WeblogEntry.PUBLISHED, null, null, null, null, 0, -1); assertNotNull(entries); assertEquals(3, entries.size()); - + // get all entries in date range entries = null; entries = mgr.getWeblogEntries(testWeblog, null, entry2.getPubTime(), entry2.getPubTime(), null, null, null, null, null, null, null, 0, -1); assertNotNull(entries); assertEquals(1, entries.size()); assertEquals(entry2, entries.get(0)); - + // get all entries, limited to maxSize entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, null, null, null, null, null, null, null, 0, 2); assertNotNull(entries); assertEquals(2, entries.size()); - + // get all entries in category entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, testWeblog.getDefaultCategory().getName(), null, null, null, null, null, null, 0, -1); assertNotNull(entries); assertEquals(5, entries.size()); - + // get all entries, limited by offset/range entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, null, null, null, null, null, null, null, 1, 1); assertNotNull(entries); assertEquals(1, entries.size()); assertEquals(entry2, entries.get(0)); - + // get all entries, limited by locale entries = null; entries = mgr.getWeblogEntries(testWeblog, null, null, null, null, null, null, null, null, null, "en_US", 0, -1); assertNotNull(entries); assertEquals(4, entries.size()); assertEquals(entry3, entries.get(0)); - + // get pinned entries only entries = null; entries = mgr.getWeblogEntriesPinnedToMain(new Integer(5)); assertNotNull(entries); assertEquals(1, entries.size()); assertEquals(entry1, entries.get(0)); - + // get next entry entry = null; entry = mgr.getNextEntry(entry4, null, null); assertNotNull(entry); assertEquals(entry5, entry); - + // get previous entry entry = null; entry = mgr.getPreviousEntry(entry5, null, null); assertNotNull(entry); assertEquals(entry4, entry); - + // get object map entryMap = null; entryMap = mgr.getWeblogEntryObjectMap(testWeblog, null, null, null, null, null, null, 0, -1); assertNotNull(entryMap); assertTrue(entryMap.keySet().size() > 1); - + // get string map entryMap = null; entryMap = mgr.getWeblogEntryStringMap(testWeblog, null, null, null, null, null, null, 0, -1); assertNotNull(entryMap); assertTrue(entryMap.keySet().size() > 1); - + // teardown our test entries TestUtils.teardownWeblogEntry(entry1.getId()); TestUtils.teardownWeblogEntry(entry2.getId()); TestUtils.teardownWeblogEntry(entry3.getId()); TestUtils.endSession(true); } - - + + /** * Test that the createAnchor() method actually ensures unique anchors. */ public void testCreateAnchor() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry entry = null; List entries = null; - + // setup some test entries to use testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); WeblogEntry entry1 = TestUtils.setupWeblogEntry("entry1", testWeblog.getDefaultCategory(), testWeblog, testUser); TestUtils.endSession(true); - + // make sure createAnchor gives us a new anchor value entry1 = TestUtils.getManagedWeblogEntry(entry1); String anchor = mgr.createAnchor(entry1); assertNotNull(anchor); assertNotSame("entry1", anchor); - + // make sure we can create a new entry with specified anchor testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); WeblogEntry entry2 = TestUtils.setupWeblogEntry(anchor, testWeblog.getDefaultCategory(), testWeblog, testUser); TestUtils.endSession(true); assertNotNull(entry2); - + // teardown our test entries TestUtils.teardownWeblogEntry(entry1.getId()); TestUtils.teardownWeblogEntry(entry2.getId()); TestUtils.endSession(true); } - + public void testCreateAnEntryWithTagsShortcut() throws Exception { try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -387,15 +387,15 @@ public void testCreateAnEntryWithTagsShortcut() throws Exception { // teardown our test entry TestUtils.teardownWeblogEntry(id); TestUtils.endSession(true); - + } catch (Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(sw.toString()); } } - + public void testAddMultipleTags() throws Exception { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -423,7 +423,7 @@ public void testAddMultipleTags() throws Exception { TestUtils.teardownWeblogEntry(id); TestUtils.endSession(true); } - + public void testAddMultipleIdenticalTags() throws Exception { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -449,8 +449,8 @@ public void testAddMultipleIdenticalTags() throws Exception { // teardown our test entry TestUtils.teardownWeblogEntry(id); TestUtils.endSession(true); - } - + } + public void testRemoveTagsViaShortcut() throws Exception { try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -483,58 +483,58 @@ public void testRemoveTagsViaShortcut() throws Exception { // teardown our test entry TestUtils.teardownWeblogEntry(id); TestUtils.endSession(true); - + } catch (Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(sw.toString()); } } - + public void testTagsExist() throws Exception { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); Weblog weblog = TestUtils.setupWeblog("tagsExistWeblog1", testUser); String wid = weblog.getId(); - + // setup some test entries to use - WeblogEntry entry = TestUtils.setupWeblogEntry("tagsExistEntry1", + WeblogEntry entry = TestUtils.setupWeblogEntry("tagsExistEntry1", testWeblog.getDefaultCategory(), testWeblog, testUser); String id1 = entry.getId(); entry.addTag("blahTag"); entry.addTag("fooTag"); mgr.saveWeblogEntry(entry); - WeblogEntry entry2 = TestUtils.setupWeblogEntry("tagsExistEntry2", + WeblogEntry entry2 = TestUtils.setupWeblogEntry("tagsExistEntry2", weblog.getDefaultCategory(), weblog, testUser); String id2 = entry2.getId(); entry2.addTag("aaaTag"); entry2.addTag("bbbTag"); mgr.saveWeblogEntry(entry2); TestUtils.endSession(true); - + // we'll need these List tags1 = new ArrayList(); tags1.add("nonExistTag"); - + List tags2 = new ArrayList(); tags2.add("blahtag"); - + // test site-wide this.assertTrue(mgr.getTagComboExists(tags2, null)); this.assertFalse(mgr.getTagComboExists(tags1, null)); - + // test weblog specific testWeblog = TestUtils.getManagedWebsite(testWeblog); weblog = TestUtils.getManagedWebsite(weblog); this.assertTrue(mgr.getTagComboExists(tags2, testWeblog)); this.assertFalse(mgr.getTagComboExists(tags1, testWeblog)); this.assertFalse(mgr.getTagComboExists(tags2, weblog)); - + // teardown our test data TestUtils.teardownWeblogEntry(id1); TestUtils.teardownWeblogEntry(id2); @@ -543,7 +543,7 @@ public void testTagsExist() throws Exception { TestUtils.teardownWeblog(wid); TestUtils.endSession(true); } - + public void testGetEntriesByTag() throws Exception { try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -551,7 +551,7 @@ public void testGetEntriesByTag() throws Exception { // setup some test entries to use testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); - WeblogEntry entry = TestUtils.setupWeblogEntry("entry1", + WeblogEntry entry = TestUtils.setupWeblogEntry("entry1", testWeblog.getDefaultCategory(), testWeblog, testUser); String id = entry.getId(); entry.addTag("testTag"); @@ -565,20 +565,20 @@ public void testGetEntriesByTag() throws Exception { assertEquals(1, results.size()); WeblogEntry testEntry = (WeblogEntry) results.iterator().next(); assertEquals(entry, testEntry); - + // teardown our test entry TestUtils.teardownWeblogEntry(id); TestUtils.endSession(true); - + } catch (Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(sw.toString()); } } - - + + public void testRemoveEntryTagCascading() throws Exception { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -611,8 +611,8 @@ public void testRemoveEntryTagCascading() throws Exception { // terminate TestUtils.endSession(true); - } - + } + public void testUpdateTags() throws Exception { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -660,7 +660,7 @@ public void testUpdateTags() throws Exception { /** * We want to make sure that the first time placed on the tag remains * through consequent updates. - * + * * @throws Exception */ public void testUpdateTagTime() throws Exception { @@ -720,13 +720,13 @@ public void testUpdateTagTime() throws Exception { public void testTagAggregates() throws Exception { log.info("BEGIN"); - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); testWeblog = TestUtils.getManagedWebsite(testWeblog); testUser = TestUtils.getManagedUser(testUser); Weblog testWeblog2 = TestUtils.setupWeblog("entryTestWeblog2", testUser); - + try { // let's make sure we are starting from scratch @@ -743,13 +743,13 @@ public void testTagAggregates() throws Exception { assertEquals(0, tags.size()); // setup some test entries to use - WeblogEntry entry = TestUtils.setupWeblogEntry("entry1", + WeblogEntry entry = TestUtils.setupWeblogEntry("entry1", testWeblog.getDefaultCategory(), testWeblog, testUser); entry.addTag("one"); entry.addTag("two"); mgr.saveWeblogEntry(entry); - entry = TestUtils.setupWeblogEntry("entry2", + entry = TestUtils.setupWeblogEntry("entry2", testWeblog.getDefaultCategory(), testWeblog, testUser); entry.addTag("one"); entry.addTag("two"); @@ -779,7 +779,7 @@ public void testTagAggregates() throws Exception { // now add another entry in another blog testWeblog2 = TestUtils.getManagedWebsite(testWeblog2); testUser = TestUtils.getManagedUser(testUser); - entry = TestUtils.setupWeblogEntry("entry3", + entry = TestUtils.setupWeblogEntry("entry3", testWeblog2.getDefaultCategory(), testWeblog2, testUser); entry.addTag("one"); entry.addTag("three"); @@ -835,9 +835,9 @@ public void testTagAggregates() throws Exception { if (!expectedWeblogTags.containsKey(stat.getName())) fail("Unexpected tagName."); - Integer expectedCount = + Integer expectedCount = (Integer)expectedWeblogTags.get(stat.getName()); - assertEquals(stat.getName(), + assertEquals(stat.getName(), expectedCount.intValue(), stat.getCount()); } @@ -859,17 +859,17 @@ public void testTagAggregates() throws Exception { Integer expectedCount = (Integer)expectedSiteTags.get(stat.getName()); assertEquals(stat.getName(), expectedCount.intValue(), stat.getCount()); } - + TestUtils.teardownWeblog(testWeblog2.getId()); TestUtils.endSession(true); - + } catch (Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(sw.toString()); } - + log.info("END"); } @@ -928,9 +928,9 @@ public void testTagAggregatesCaseSensitivity() throws Exception { entry.addTag("ONE"); entry.addTag("three"); mgr.saveWeblogEntry(entry); - + TestUtils.endSession(true); - + // let's fetch "site" tags now tags = mgr.getTags(null, null, null, 0, -1); assertEquals(3, tags.size()); @@ -955,18 +955,18 @@ public void testTagAggregatesCaseSensitivity() throws Exception { TestUtils.teardownWeblog(testWeblog2.getId()); TestUtils.endSession(true); } - - - + + + /** * Test that we can add and remove entry attributes for an entry. */ public void testEntryAttributeCRUD() throws Exception { - + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); WeblogEntryManager emgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogEntry entry = null; - + WeblogEntry testEntry = new WeblogEntry(); testEntry.setTitle("entryTestEntry"); testEntry.setLink("testEntryLink"); @@ -979,7 +979,7 @@ public void testEntryAttributeCRUD() throws Exception { WeblogCategory cat = emgr.getWeblogCategory(testWeblog.getDefaultCategory().getId()); testEntry.setCategory(cat); - + // create a weblog entry emgr.saveWeblogEntry(testEntry); String id = testEntry.getId(); @@ -989,9 +989,9 @@ public void testEntryAttributeCRUD() throws Exception { testEntry.putEntryAttribute("att_mediacast_url", "http://podcast-schmodcast.com"); testEntry.putEntryAttribute("att_mediacast_type", "application/drivel"); testEntry.putEntryAttribute("att_mediacast_length", "3141592654"); - + TestUtils.endSession(true); - + // make sure entry was created entry = emgr.getWeblogEntry(id); assertNotNull(entry); @@ -1004,38 +1004,38 @@ public void testEntryAttributeCRUD() throws Exception { assertEquals("http://podcast-schmodcast.com", entry.findEntryAttribute("att_mediacast_url")); assertEquals("application/drivel", entry.findEntryAttribute("att_mediacast_type")); assertEquals("3141592654", entry.findEntryAttribute("att_mediacast_length")); - + // update a weblog entry entry.setTitle("testtest"); emgr.saveWeblogEntry(entry); TestUtils.endSession(true); - + // make sure entry was updated entry = null; entry = emgr.getWeblogEntry(id); assertNotNull(entry); assertEquals("testtest", entry.getTitle()); - + // delete a weblog entry emgr.removeWeblogEntry(entry); TestUtils.endSession(true); - + // make sure entry was deleted entry = null; entry = emgr.getWeblogEntry(id); assertNull(entry); } - - + + public void testWeblogStats() throws Exception { - - + + WeblogEntryManager emgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - + long existingUserCount = umgr.getUserCount() - 1; - + User user1 = TestUtils.setupUser("statuser1"); Weblog blog1 = TestUtils.setupWeblog("statblog1", user1); Weblog blog2 = TestUtils.setupWeblog("statblog2", user1); @@ -1044,21 +1044,21 @@ public void testWeblogStats() throws Exception { blog3.setEnabled(Boolean. FALSE); wmgr.saveWeblog(blog3); - WeblogEntry entry1 = TestUtils.setupWeblogEntry("entry1", + WeblogEntry entry1 = TestUtils.setupWeblogEntry("entry1", testWeblog.getDefaultCategory(), blog1, user1); - WeblogEntry entry2 = TestUtils.setupWeblogEntry("entry2", + WeblogEntry entry2 = TestUtils.setupWeblogEntry("entry2", testWeblog.getDefaultCategory(), blog1, user1); - - WeblogEntry entry3 = TestUtils.setupWeblogEntry("entry3", + + WeblogEntry entry3 = TestUtils.setupWeblogEntry("entry3", testWeblog.getDefaultCategory(), blog2, user1); - WeblogEntry entry4 = TestUtils.setupWeblogEntry("entry4", + WeblogEntry entry4 = TestUtils.setupWeblogEntry("entry4", testWeblog.getDefaultCategory(), blog2, user1); - WeblogEntry entry5 = TestUtils.setupWeblogEntry("entry5", + WeblogEntry entry5 = TestUtils.setupWeblogEntry("entry5", testWeblog.getDefaultCategory(), blog2, user1); - + WeblogEntryComment comment1 = TestUtils.setupComment("comment1", entry1); WeblogEntryComment comment2 = TestUtils.setupComment("comment2", entry1); - + WeblogEntryComment comment3 = TestUtils.setupComment("comment3", entry3); WeblogEntryComment comment4 = TestUtils.setupComment("comment4", entry3); WeblogEntryComment comment5 = TestUtils.setupComment("comment5", entry3); @@ -1067,7 +1067,7 @@ public void testWeblogStats() throws Exception { try { blog1 = wmgr.getWeblog(blog1.getId()); blog2 = wmgr.getWeblog(blog2.getId()); - + assertEquals(2L, blog1.getEntryCount()); assertEquals(3L, blog2.getEntryCount()); assertEquals(5L, emgr.getEntryCount()); @@ -1078,9 +1078,9 @@ public void testWeblogStats() throws Exception { assertEquals(4L, wmgr.getWeblogCount()); assertEquals(existingUserCount + 2L, umgr.getUserCount()); - + } finally { - + TestUtils.teardownComment(comment1.getId()); TestUtils.teardownComment(comment2.getId()); TestUtils.teardownComment(comment3.getId()); @@ -1097,8 +1097,8 @@ public void testWeblogStats() throws Exception { TestUtils.teardownWeblog(blog2.getId()); TestUtils.teardownWeblog(blog3.getId()); - TestUtils.teardownUser(user1.getUserName()); - + TestUtils.teardownUser(user1.getUserName()); + TestUtils.endSession(true); } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogPageTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogPageTest.java index 5024fadd42..55de0e02b6 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogPageTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogPageTest.java @@ -36,32 +36,32 @@ * Test Weblog Page related business operations. */ public class WeblogPageTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogPageTest.class); - + User testUser = null; Weblog testWeblog = null; WeblogTemplate testPage = null; - - + + public WeblogPageTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(WeblogPageTest.class); } - - + + /** * All tests in this suite require a user and a weblog. */ public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("wtTestUser"); testWeblog = TestUtils.setupWeblog("wtTestWeblog", testUser); @@ -70,7 +70,7 @@ public void setUp() throws Exception { log.error(ex); throw new Exception("Test setup failed", ex); } - + testPage = new WeblogTemplate(); testPage.setAction(WeblogTemplate.ACTION_WEBLOG); testPage.setName("testTemplate"); @@ -81,9 +81,9 @@ public void setUp() throws Exception { testPage.setWebsite(TestUtils.getManagedWebsite(testWeblog)); testPage.setTemplateLanguage("velocity"); } - + public void tearDown() throws Exception { - + try { TestUtils.teardownWeblog(testWeblog.getId()); TestUtils.teardownUser(testUser.getUserName()); @@ -92,99 +92,99 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + testPage = null; } - - + + /** * Test basic persistence operations ... Create, Update, Delete */ public void testTemplateCRUD() throws Exception { - + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); WeblogTemplate template = null; - + // create template mgr.savePage(testPage); TestUtils.endSession(true); - + // check that create was successful testWeblog = TestUtils.getManagedWebsite(testWeblog); template = null; template = mgr.getPageByName(testWeblog, testPage.getName()); assertNotNull(template); assertEquals(testPage.getContents(), template.getContents()); - + // update template template.setName("testtesttest"); mgr.savePage(template); TestUtils.endSession(true); - + // check that update was successful template = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); template = mgr.getPageByName(testWeblog, "testtesttest"); assertNotNull(template); assertEquals(testPage.getContents(), template.getContents()); - + // delete template mgr.removePage(template); TestUtils.endSession(true); - + // check that delete was successful template = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); template = mgr.getPageByName(testWeblog, testPage.getName()); assertNull(template); } - - + + /** * Test lookup mechanisms ... id, name, link, weblog */ public void testPermissionsLookups() throws Exception { - + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); WeblogTemplate page = null; - + // create page mgr.savePage(testPage); String id = testPage.getId(); TestUtils.endSession(true); - + // lookup by id page = mgr.getPage(id); assertNotNull(page); assertEquals(testPage.getContents(), page.getContents()); - + // lookup by action page = null; testWeblog = TestUtils.getManagedWebsite(testWeblog); page = mgr.getPageByAction(testWeblog, testPage.getAction()); assertNotNull(page); assertEquals(testPage.getContents(), page.getContents()); - + // lookup by name page = null; page = mgr.getPageByName(testWeblog, testPage.getName()); assertNotNull(page); assertEquals(testPage.getContents(), page.getContents()); - + // lookup by link page = null; page = mgr.getPageByLink(testWeblog, testPage.getLink()); assertNotNull(page); assertEquals(testPage.getContents(), page.getContents()); - + // lookup all pages for weblog List pages = mgr.getPages(testWeblog); assertNotNull(pages); assertEquals(1, pages.size()); - + // delete page mgr.removePage(page); TestUtils.endSession(true); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogStatsTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogStatsTest.java index 9e1a0c5431..179619ccbe 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogStatsTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogStatsTest.java @@ -14,9 +14,9 @@ * */ public class WeblogStatsTest extends TestCase { - + private User user1, user2; - + private Weblog website1; private WeblogEntry entry11; private WeblogEntryComment comment11; @@ -26,15 +26,15 @@ public class WeblogStatsTest extends TestCase { private Weblog website2; private WeblogEntry entry21; - private WeblogEntryComment comment21; - + private WeblogEntryComment comment21; + public WeblogStatsTest() { - } + } protected void setUp() throws Exception { // create weblog with three entries and two comments per entry user1 = TestUtils.setupUser("a_commentCountTestUser"); user2 = TestUtils.setupUser("b_commentCountTestUser"); - + website1 = TestUtils.setupWeblog("a_testWebsite1", user1); entry11 = TestUtils.setupWeblogEntry( "anchor11", website1.getDefaultCategory(), website1, user1); @@ -43,7 +43,7 @@ protected void setUp() throws Exception { entry12 = TestUtils.setupWeblogEntry( "anchor12", website1.getDefaultCategory(), website1, user1); comment13 = TestUtils.setupComment("Comment13", entry12); - + website2 = TestUtils.setupWeblog("b_testWebsite2", user1); entry21 = TestUtils.setupWeblogEntry( "anchor21", website2.getDefaultCategory(), website2, user1); @@ -52,67 +52,67 @@ protected void setUp() throws Exception { Thread.sleep(1000); } - public void testGetMostCommentedWeblogs() throws Exception { - WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); - List list = mgr.getMostCommentedWeblogs(null, null, 0, -1); - + public void testGetMostCommentedWeblogs() throws Exception { + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); + List list = mgr.getMostCommentedWeblogs(null, null, 0, -1); + assertNotNull(list); assertEquals(2, list.size()); - + StatCount s1 = (StatCount)list.get(0); assertEquals(website1.getId(), s1.getSubjectId()); - assertEquals(3L, s1.getCount()); + assertEquals(3L, s1.getCount()); assertEquals(website1.getHandle(), s1.getSubjectNameShort()); assertEquals(website1.getHandle(), s1.getWeblogHandle()); - + StatCount s2 = (StatCount)list.get(1); assertEquals(website2.getId(), s2.getSubjectId()); - assertEquals(1L, s2.getCount()); + assertEquals(1L, s2.getCount()); } public void testGetMostCommentedWeblogEntries() throws Exception { - - WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); + + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); List list = mgr.getMostCommentedWeblogEntries(null, null, null, 0, -1); - + assertNotNull(list); assertEquals(3, list.size()); - + StatCount s1 = (StatCount)list.get(0); - assertEquals(2L, s1.getCount()); + assertEquals(2L, s1.getCount()); assertEquals(entry11.getAnchor(), s1.getSubjectNameShort()); assertEquals(entry11.getWebsite().getHandle(), s1.getWeblogHandle()); - + StatCount s2 = (StatCount)list.get(1); - assertEquals(1L, s2.getCount()); + assertEquals(1L, s2.getCount()); } - public void testGetUserNameLetterMap() throws Exception { - UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); - Map map = mgr.getUserNameLetterMap(); + public void testGetUserNameLetterMap() throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + Map map = mgr.getUserNameLetterMap(); assertNotNull(map.get("A")); assertNotNull(map.get("B")); assertNotNull(map.get("C")); } - public void testGetWeblogLetterMap() throws Exception { + public void testGetWeblogLetterMap() throws Exception { WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); - Map map = mgr.getWeblogHandleLetterMap(); + Map map = mgr.getWeblogHandleLetterMap(); assertNotNull(map.get("A")); assertNotNull(map.get("B")); assertNotNull(map.get("C")); } protected void tearDown() throws Exception { - + // TODO: ATLAS figure out why comments must be torn down first TestUtils.teardownComment(comment11.getId()); TestUtils.teardownComment(comment12.getId()); TestUtils.teardownComment(comment13.getId()); TestUtils.teardownWeblog(website1.getId()); - + TestUtils.teardownComment(comment21.getId()); - TestUtils.teardownWeblog(website2.getId()); - - TestUtils.teardownUser(user1.getUserName()); - TestUtils.teardownUser(user2.getUserName()); - + TestUtils.teardownWeblog(website2.getId()); + + TestUtils.teardownUser(user1.getUserName()); + TestUtils.teardownUser(user2.getUserName()); + TestUtils.endSession(true); } } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogTest.java index ea59d9b595..92cd50b158 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/WeblogTest.java @@ -35,32 +35,32 @@ * Test Weblog related business operations. */ public class WeblogTest extends TestCase { - + public static Log log = LogFactory.getLog(WeblogTest.class); - + User testUser = null; - - + + public WeblogTest(String name) { super(name); } - - + + public static Test suite() { return new TestSuite(WeblogTest.class); } - - + + /** * All tests in this suite require a user. */ public void setUp() throws Exception { - + log.info("BEGIN"); - + // setup weblogger TestUtils.setupWeblogger(); - + try { testUser = TestUtils.setupUser("weblogTestUser"); TestUtils.endSession(true); @@ -68,14 +68,14 @@ public void setUp() throws Exception { log.error(ex); throw new Exception("Test setup failed", ex); } - + log.info("END"); } - + public void tearDown() throws Exception { - + log.info("BEGIN"); - + try { TestUtils.teardownUser(testUser.getUserName()); TestUtils.endSession(true); @@ -83,20 +83,20 @@ public void tearDown() throws Exception { log.error(ex); throw new Exception("Test teardown failed", ex); } - + log.info("END"); } - - + + /** * Test basic persistence operations ... Create, Update, Delete. */ public void testWeblogCRUD() throws Exception { - + log.info("BEGIN"); - + try { - + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); Weblog weblog = null; @@ -150,20 +150,20 @@ public void testWeblogCRUD() throws Exception { weblog = null; weblog = mgr.getWeblog(id); assertNull(weblog); - + } catch(Throwable t) { log.error("Exception running test", t); throw (Exception) t; } log.info("END"); } - - + + /** * Test lookup mechanisms. */ public void testWeblogLookups() throws Exception { - + log.info("BEGIN"); Weblog testWeblog1 = null; Weblog testWeblog2 = null; @@ -171,23 +171,23 @@ public void testWeblogLookups() throws Exception { WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); Weblog weblog = null; - + // add test weblogs testWeblog1 = TestUtils.setupWeblog("testWeblog1", testUser); testWeblog2 = TestUtils.setupWeblog("testWeblog2", testUser); TestUtils.endSession(true); - + // lookup by id weblog = mgr.getWeblog(testWeblog1.getId()); assertNotNull(weblog); assertEquals(testWeblog1.getHandle(), weblog.getHandle()); - + // lookup by weblog handle weblog = null; weblog = mgr.getWeblogByHandle(testWeblog1.getHandle()); assertNotNull(weblog); assertEquals(testWeblog1.getHandle(), weblog.getHandle()); - + // make sure disable weblogs are not returned weblog.setEnabled(Boolean.FALSE); mgr.saveWeblog(weblog); @@ -195,7 +195,7 @@ public void testWeblogLookups() throws Exception { weblog = null; weblog = mgr.getWeblogByHandle(testWeblog1.getHandle()); assertNull(weblog); - + // restore enabled state weblog = mgr.getWeblogByHandle(testWeblog1.getHandle(), Boolean.FALSE); weblog.setEnabled(Boolean.TRUE); @@ -204,14 +204,14 @@ public void testWeblogLookups() throws Exception { weblog = null; weblog = mgr.getWeblogByHandle(testWeblog1.getHandle()); assertNotNull(weblog); - + // get all weblogs for user weblog = null; List weblogs1 = mgr.getUserWeblogs(TestUtils.getManagedUser(testUser), true); assertEquals(2, weblogs1.size()); weblog = (Weblog) weblogs1.get(0); - assertNotNull(weblog); - + assertNotNull(weblog); + // make sure disabled weblogs are not returned weblog.setEnabled(Boolean.FALSE); mgr.saveWeblog(weblog); @@ -220,22 +220,22 @@ public void testWeblogLookups() throws Exception { assertEquals(1, weblogs2.size()); weblog = (Weblog) weblogs2.get(0); assertNotNull(weblog); - + // make sure inactive weblogs are not returned weblog.setActive(Boolean.FALSE); mgr.saveWeblog(weblog); TestUtils.endSession(true); List weblogs3 = mgr.getUserWeblogs(TestUtils.getManagedUser(testUser), true); assertEquals(0, weblogs3.size()); - + } finally { TestUtils.teardownWeblog(testWeblog1.getId()); TestUtils.teardownWeblog(testWeblog2.getId()); TestUtils.endSession(true); } - + log.info("END"); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java index d94d5b3dfc..0881d23761 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java @@ -30,14 +30,14 @@ /** * Test Weblogger Bookmark Management. */ -public class JPAOAuthManagerTest extends TestCase { +public class JPAOAuthManagerTest extends TestCase { public static Log log = LogFactory.getLog(JPAOAuthManagerTest.class); public void setUp() throws Exception { - + // setup weblogger TestUtils.setupWeblogger(); - + try { TestUtils.endSession(true); } catch (Exception ex) { @@ -45,9 +45,9 @@ public void setUp() throws Exception { throw new Exception("Test setup failed", ex); } } - + public void tearDown() throws Exception { - + try { TestUtils.endSession(true); } catch (Exception ex) { diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/plugins/CommentPluginsTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/plugins/CommentPluginsTest.java index ec4b0003cf..9281d51f95 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/business/plugins/CommentPluginsTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/business/plugins/CommentPluginsTest.java @@ -31,31 +31,31 @@ public class CommentPluginsTest extends TestCase { private String convertLinesStart = "paragraph1\n\nparagraph2\nline2\nline3\n\nparagraph3"; private String convertLinesFormatted = "\n

    paragraph1

    \n\n\n

    paragraph2
    \nline2
    \nline3

    \n\n\n

    paragraph3

    \n\n"; - - + + protected void setUp() throws Exception { TestUtils.setupWeblogger(); } - + protected void tearDown() throws Exception { // no-op } - - + + public void testAutoFormatPlugin() { - + PluginManager pmgr = WebloggerFactory.getWeblogger().getPluginManager(); - + // setup test comment WeblogEntryComment comment = new WeblogEntryComment(); - comment.setContent(convertLinesStart); + comment.setContent(convertLinesStart); comment.setPlugins("AutoFormat Plugin"); - + // reformat String output = pmgr.applyCommentPlugins(comment, comment.getContent()); - + // make sure it turned out how we planned - assertEquals(convertLinesFormatted, output); + assertEquals(convertLinesFormatted, output); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/BlacklistTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/BlacklistTest.java index 702da0d865..7830c4ba88 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/BlacklistTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/BlacklistTest.java @@ -29,23 +29,23 @@ * Test blacklist functionality. */ public class BlacklistTest extends TestCase { - public static Log log = - LogFactory.getLog(BlacklistTest.class); - + public static Log log = + LogFactory.getLog(BlacklistTest.class); + private Blacklist blacklist; - - + + public BlacklistTest() { super(); } - + /** * @param arg0 */ public BlacklistTest(String arg0) { super(arg0); } - + /** * @see TestCase#setUp() */ @@ -57,7 +57,7 @@ protected void setUp() throws Exception { log.info("Processing Blacklist file: " + blacklistName); blacklist.loadBlacklistFromFile(blacklistName); } - + /** * @see TestCase#tearDown() */ @@ -65,53 +65,53 @@ protected void tearDown() throws Exception { super.tearDown(); //System.out.println(blacklist); } - + public void testIsBlacklisted0() { assertFalse(blacklist.isBlacklisted("four score and seven years ago.com")); } - + // test non-regex public void testIsBlacklisted1() { assertTrue(blacklist.isBlacklisted("00000-online-casino.com")); } - + // test the regex patterns public void testIsBlacklisted2() { assertTrue(blacklist.isBlacklisted("www.lsotr.com")); } - + // test the regex patterns public void testIsBlacklisted3() { assertTrue(blacklist.isBlacklisted("www.lsotr.com")); } - + // test the regex patterns public void testIsBlacklisted4() { assertTrue(blacklist.isBlacklisted("blow-job.com")); } - + // test the regex patterns public void testIsBlacklisted5() { assertTrue(blacklist.isBlacklisted("buymoreonline.com")); } - + // test the regex patterns public void testIsBlacklisted6() { assertTrue(blacklist.isBlacklisted("diet-enlargement.com")); } - + // test the regex patterns public void testIsBlacklisted7() { assertTrue(blacklist.isBlacklisted("viagra.com")); } - + // test the regex patterns public void testIsBlacklisted8() { assertTrue(blacklist.isBlacklisted("ragazze-something.com")); } - + public static Test suite() { return new TestSuite(BlacklistTest.class); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LRUCache2Test.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LRUCache2Test.java index 585e1e8546..74c0496910 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LRUCache2Test.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LRUCache2Test.java @@ -27,7 +27,7 @@ * Test LRUCache2. */ public class LRUCache2Test extends TestCase { - + /** * @see junit.framework.TestCase#setUp() */ @@ -35,12 +35,12 @@ protected void setUp() throws Exception { // TODO Auto-generated method stub super.setUp(); } - + public void testTimeout() { // Create cache with 100 item limit and 15 second timeout TestEnvironment env = new TestEnvironment(); LRUCache2 cache = new LRUCache2(env, 100, 15000); - + env.time = 1000; cache.put("key1", "string1"); cache.put("key2", "string2"); @@ -48,18 +48,18 @@ public void testTimeout() { assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); assertNotNull(cache.get("key3")); - + env.time = 16000; assertNull(cache.get("key1")); assertNull(cache.get("key2")); assertNull(cache.get("key3")); } - + public void testLRU() { // Create cache with 3 item limit and 15 second timeout TestEnvironment env = new TestEnvironment(); LRUCache2 cache = new LRUCache2(env, 3, 15000); - + env.time = 1000; cache.put("key1", "string1"); cache.put("key2", "string2"); @@ -67,23 +67,23 @@ public void testLRU() { assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); assertNotNull(cache.get("key3")); - + try { Thread.sleep(200); } catch (InterruptedException ignored) {} - + // accessing key1 and key2 will make key3 LRU cache.get("key1"); cache.get("key2"); - + // adding a forth key will push out the LRU entry cache.put("key4", "string4"); assertNull(cache.get("key3")); } - + public void testPurge() { // Create cache with 100 item limit and 15 second timeout TestEnvironment env = new TestEnvironment(); LRUCache2 cache = new LRUCache2(env, 100, 15000); - + env.time = 1000; cache.put("key1", "string1"); cache.put("key2", "string2"); @@ -91,14 +91,14 @@ public void testPurge() { assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); assertNotNull(cache.get("key3")); - + cache.purge(new String[] {"key1", "key2"}); assertEquals(1, cache.size()); - + cache.purge(); assertEquals(0, cache.size()); } - + /** * @see junit.framework.TestCase#tearDown() */ @@ -106,16 +106,16 @@ protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); } - + public static class TestEnvironment implements LRUCache2.Environment { public long time = 0; public long getCurrentTimeInMillis() { return time; } } - + public static Test suite() { return new TestSuite(LRUCache2Test.class); } - + } diff --git a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LinkbackExtractorTest.java b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LinkbackExtractorTest.java index 068df35586..3299cad7c8 100644 --- a/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LinkbackExtractorTest.java +++ b/weblogger-business/src/test/java/org/apache/roller/weblogger/util/LinkbackExtractorTest.java @@ -26,7 +26,7 @@ * Test linkback extractor. */ public class LinkbackExtractorTest extends TestCase { - + /** * Constructor for LinkbackExtractorTest. * @param arg0 @@ -34,24 +34,24 @@ public class LinkbackExtractorTest extends TestCase { public LinkbackExtractorTest(String arg0) { super(arg0); } - + public static void main(String[] args) { } - + /** * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } - + /** * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } - + public void testLinkbackExtractor() throws Exception { String[][] testrefs = new String[][] { @@ -64,7 +64,7 @@ public void testLinkbackExtractor() throws Exception { "http://www.rollerweblogger.org/page/roller/20030125" } }; - + for ( int i=0; ilink

    "; String expect = "a bold sentence with a link"; String result = Utilities.removeHTML(test, false); assertEquals(expect, result); } - + public void testTruncateNicely1() { String test = "blah blah blah blah blah"; String expect = "blah blah blah"; String result = Utilities.truncateNicely(test, 11, 15, ""); assertEquals(expect, result); } - + public void testTruncateNicely2() { String test = "

    blah1 blah2 blah3 blah4 blah5

    "; String expect = "

    blah1 blah2 blah3

    "; @@ -81,24 +81,24 @@ public void testTruncateNicely2() { //System.out.println(result); assertEquals(expect, result); } - + /* broken because it uses UtilitiesModel which is part of .ui.* package public void testAddNoFollow() { String test1 = "

    this some text with a link"; String expect1 = "

    this some text with a link"; String result1 = UtilitiesModel.addNofollow(test1); assertEquals(expect1, result1); - + String test2 = "

    this some text with a link"; String expect2 = "

    this some text with a link"; String result2 = UtilitiesModel.addNofollow(test2); assertEquals(expect2, result2); - + } */ - + public static Test suite() { return new TestSuite(UtilitiesTest.class); } - + } diff --git a/weblogger-business/src/test/resources/WEB-INF/security.xml b/weblogger-business/src/test/resources/WEB-INF/security.xml index 68255fdb76..b8ce7c4636 100644 --- a/weblogger-business/src/test/resources/WEB-INF/security.xml +++ b/weblogger-business/src/test/resources/WEB-INF/security.xml @@ -36,7 +36,7 @@ - @@ -60,5 +60,5 @@ - + diff --git a/weblogger-docs/README.txt b/weblogger-docs/README.txt index 2516eda70a..443a7ed02a 100644 --- a/weblogger-docs/README.txt +++ b/weblogger-docs/README.txt @@ -5,6 +5,6 @@ In this directory you'll find: installguide/ - User guide in Open Office 2.0 ODT and PDF formats examples/ - example configuration and script files testing/ - Test plans (under development) - - + + diff --git a/weblogger-docs/examples/configs/wbloggar/wbloggar.txt b/weblogger-docs/examples/configs/wbloggar/wbloggar.txt index 4d2db0f58e..0bb4035e8a 100644 --- a/weblogger-docs/examples/configs/wbloggar/wbloggar.txt +++ b/weblogger-docs/examples/configs/wbloggar/wbloggar.txt @@ -7,7 +7,7 @@ Like this: Count=11 Then add following to the end of the CMS.ini file. Change 'yourserver.com' -to the address of your Roller server. If you want the icon to work then drop +to the address of your Roller server. If you want the icon to work then drop rollerbadge.jpg in the same directory as CMS.ini. [CMS-11] @@ -24,7 +24,7 @@ rollerbadge.jpg in the same directory as CMS.ini. PostMethod=3 GetPostsMethod=3 TemplateMethod=1 - + If you are a FreeRoller user, then here are your settings: [CMS-11] diff --git a/weblogger-docs/examples/plugins/pluginmodel/build.xml b/weblogger-docs/examples/plugins/pluginmodel/build.xml index a98bbe7fdb..8e1265dce7 100644 --- a/weblogger-docs/examples/plugins/pluginmodel/build.xml +++ b/weblogger-docs/examples/plugins/pluginmodel/build.xml @@ -1,9 +1,9 @@ - + - + @@ -24,5 +24,5 @@ - + diff --git a/weblogger-docs/examples/plugins/pluginmodel/src/org/apache/roller/examples/plugins/pagemodel/AuthenticatedUserModel.java b/weblogger-docs/examples/plugins/pluginmodel/src/org/apache/roller/examples/plugins/pagemodel/AuthenticatedUserModel.java index 54ed56b5fa..3e56195c69 100644 --- a/weblogger-docs/examples/plugins/pluginmodel/src/org/apache/roller/examples/plugins/pagemodel/AuthenticatedUserModel.java +++ b/weblogger-docs/examples/plugins/pluginmodel/src/org/apache/roller/examples/plugins/pagemodel/AuthenticatedUserModel.java @@ -14,9 +14,9 @@ public class AuthenticatedUserModel implements Model { - private static Log log = LogFactory.getLog(AuthenticatedUserModel.class); + private static Log log = LogFactory.getLog(AuthenticatedUserModel.class); private HttpServletRequest request = null; - + public String getModelName() { return "authenticated"; } @@ -25,7 +25,7 @@ public void init(Map params) throws WebloggerException { PageContext context = (PageContext)params.get("pageContext"); this.request = (HttpServletRequest) context.getRequest(); } - + public UserWrapper getUser() { try { RollerSession rses = RollerSession.getRollerSession(request); diff --git a/weblogger-docs/examples/rollertask/README.txt b/weblogger-docs/examples/rollertask/README.txt index 7b29b2f81b..39a029bb0b 100644 --- a/weblogger-docs/examples/rollertask/README.txt +++ b/weblogger-docs/examples/rollertask/README.txt @@ -1,8 +1,8 @@ README for rollertask -rollertask.sh is a script that can be used to run the Roller tasks. Because +rollertask.sh is a script that can be used to run the Roller tasks. Because rollertask.sh runs outside of the Roller application, you have to put some -files into place before you can run it. +files into place before you can run it. Here are the steps I used to setup rollertask.sh to run on my UNIX based system. diff --git a/weblogger-docs/examples/scripting/bsf/README.txt b/weblogger-docs/examples/scripting/bsf/README.txt index 3ceb14107e..ed291d8918 100644 --- a/weblogger-docs/examples/scripting/bsf/README.txt +++ b/weblogger-docs/examples/scripting/bsf/README.txt @@ -16,7 +16,7 @@ To use it in Roller: 4) Restart Roller -5) Create a new Weblog Template and set the Template Language to either +5) Create a new Weblog Template and set the Template Language to either "groovy", "jruby" or "javascript" 6) In your page template you'll have access to all normal Roller models diff --git a/weblogger-docs/examples/scripting/bsf/build.xml b/weblogger-docs/examples/scripting/bsf/build.xml index e3c709727d..df8d8083d0 100644 --- a/weblogger-docs/examples/scripting/bsf/build.xml +++ b/weblogger-docs/examples/scripting/bsf/build.xml @@ -1,22 +1,22 @@ - Build Roller-Groovy integration classes + Build Roller-Groovy integration classes - + - - - - - + + + + + - + - - + + @@ -29,7 +29,7 @@ @@ -27,8 +27,8 @@ war false - - + + ../weblogger-webapp/target/roller @@ -38,9 +38,9 @@ **/geronimo** - **/jetty-env** + **/jetty-env** - + diff --git a/weblogger-war-assembly/src/main/assembly/for-jboss.xml b/weblogger-war-assembly/src/main/assembly/for-jboss.xml index e2e5122a7e..5464a58293 100644 --- a/weblogger-war-assembly/src/main/assembly/for-jboss.xml +++ b/weblogger-war-assembly/src/main/assembly/for-jboss.xml @@ -18,7 +18,7 @@ --> @@ -27,7 +27,7 @@ war false - + @@ -37,7 +37,7 @@ **/openjpa** **/xml-apis** **/geronimo** - + **/javassist** **/xercesImpl** @@ -48,5 +48,5 @@ - + diff --git a/weblogger-war-assembly/src/main/assembly/for-tomcat.xml b/weblogger-war-assembly/src/main/assembly/for-tomcat.xml index 5f034ef9ba..439fb5b86f 100644 --- a/weblogger-war-assembly/src/main/assembly/for-tomcat.xml +++ b/weblogger-war-assembly/src/main/assembly/for-tomcat.xml @@ -18,7 +18,7 @@ --> @@ -27,7 +27,7 @@ war false - + @@ -38,5 +38,5 @@ - + diff --git a/weblogger-web/pom.xml b/weblogger-web/pom.xml index b8cb167cfb..094cd89905 100644 --- a/weblogger-web/pom.xml +++ b/weblogger-web/pom.xml @@ -105,7 +105,7 @@ javax.activation activation - 1.1.1 + 1.1.1 test @@ -412,14 +412,14 @@ - + maven-resources-plugin 2.4.3 - + @@ -475,9 +475,9 @@ - + - + true @@ -490,7 +490,7 @@ once -javaagent:${user.home}/.m2/repository/org/apache/openjpa/openjpa/2.0.1/openjpa-2.0.1.jar - + catalina.base diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetConfig.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetConfig.java index 48c65e386a..2b6c938d37 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetConfig.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetConfig.java @@ -41,37 +41,37 @@ * Handles editing of planet global runtime properties. */ public class PlanetConfig extends PlanetUIAction implements ParameterAware { - + private static Log log = LogFactory.getLog(PlanetConfig.class); - + // original request parameters private Map parameters = Collections.EMPTY_MAP; - + // runtime properties data private Map properties = Collections.EMPTY_MAP; - + // the runtime config def used to populate the display private ConfigDef globalConfigDef = null; - - + + public PlanetConfig() { this.actionName = "planetConfig"; this.desiredMenu = "admin"; this.pageTitle = "planetConfig.title"; } - - + + public List requiredGlobalPermissionActions() { return Collections.singletonList(GlobalPermission.ADMIN); } - + @Override public boolean isWeblogRequired() { return false; } - - + + @Override public void myPrepare() { try { @@ -81,7 +81,7 @@ public void myPrepare() { } catch (RollerException ex) { log.error("Error loading planet properties"); } - + // set config def used to draw the view RuntimeConfigDefs defs = PlanetRuntimeConfig.getRuntimeConfigDefs(); List configDefs = defs.getConfigDefs(); @@ -92,14 +92,14 @@ public void myPrepare() { } } - + public String execute() { return INPUT; } - - + + public String save() { - + try { // only set values for properties that are already defined String propName = null; @@ -108,53 +108,53 @@ public String save() { Iterator propsIT = getProperties().keySet().iterator(); while(propsIT.hasNext()) { propName = (String) propsIT.next(); - + log.debug("Checking property ["+propName+"]"); - + updProp = (RuntimeConfigProperty) getProperties().get(propName); String[] propValues = (String[]) getParameters().get(updProp.getName()); if(propValues != null && propValues.length > 0) { // we don't deal with multi-valued props incomingProp = propValues[0]; } - + // some special treatment for booleans // this is a bit hacky since we are assuming that any prop // with a value of "true" or "false" is meant to be a boolean // it may not always be the case, but we should be okay for now if( updProp.getValue() != null // null check needed w/Oracle && (updProp.getValue().equals("true") || updProp.getValue().equals("false"))) { - + if(incomingProp == null || !incomingProp.equals("on")) incomingProp = "false"; else incomingProp = "true"; } - + // only work on props that were submitted with the request if(incomingProp != null) { log.debug("Setting new value for ["+propName+"]"); - + updProp.setValue(incomingProp.trim()); } } - + // save it PropertiesManager pMgr = PlanetFactory.getPlanet().getPropertiesManager(); pMgr.saveProperties(this.properties); PlanetFactory.getPlanet().flush(); - + addMessage("ConfigForm.message.saveSucceeded"); - + } catch (RollerException e) { log.error(e); addError("ConfigForm.error.saveFailed"); } - + return INPUT; } - + public Map getParameters() { return parameters; } @@ -170,7 +170,7 @@ public Map getProperties() { public void setProperties(Map properties) { this.properties = properties; } - + public ConfigDef getGlobalConfigDef() { return globalConfigDef; } @@ -178,5 +178,5 @@ public ConfigDef getGlobalConfigDef() { public void setGlobalConfigDef(ConfigDef globalConfigDef) { this.globalConfigDef = globalConfigDef; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroups.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroups.java index ce211b38be..b44e8e0f67 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroups.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroups.java @@ -33,37 +33,37 @@ * Manage planet groups. */ public class PlanetGroups extends PlanetUIAction { - + private static Log log = LogFactory.getLog(PlanetGroups.class); - + // a bean to manage submitted data private PlanetGroupsBean bean = new PlanetGroupsBean(); - + // the planet group we are working on private PlanetGroup group = null; - - + + public PlanetGroups() { this.actionName = "planetGroups"; this.desiredMenu = "admin"; this.pageTitle = "planetGroups.pagetitle"; } - - + + @Override public List requiredWeblogPermissionActions() { return Collections.singletonList(WeblogPermission.ADMIN); } - + @Override public boolean isWeblogRequired() { return false; } - - + + @Override public void myPrepare() { - + if(getPlanet() != null && getBean().getId() != null) try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); setGroup(pmgr.getGroupById(getBean().getId())); @@ -72,30 +72,30 @@ public void myPrepare() { } } - - /** + + /** * Show planet groups page. */ public String execute() { - + // if we are loading an existing group then populate the bean if(getGroup() != null) { getBean().copyFrom(getGroup()); } - + return LIST; } - - - /** + + + /** * Save group. */ public String save() { - + myValidate(); - + if (!hasActionErrors()) try { - + PlanetGroup group = getGroup(); if(group == null) { log.debug("Adding New Group"); @@ -104,38 +104,38 @@ public String save() { } else { log.debug("Updating Existing Group"); } - + // copy in submitted data getBean().copyTo(group); - + // save and flush PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); pmgr.saveGroup(group); PlanetFactory.getPlanet().flush(); - + addMessage("planetGroups.success.saved"); - + } catch(Exception ex) { log.error("Error saving planet group - "+getBean().getId(), ex); // TODO: i18n addError("Error saving planet group"); } - + return LIST; } - - /** - * Delete group, reset form + + /** + * Delete group, reset form */ public String delete() { - + if(getGroup() != null) { try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); pmgr.deleteGroup(getGroup()); PlanetFactory.getPlanet().flush(); - + addMessage("planetSubscription.success.deleted"); } catch(Exception ex) { log.error("Error deleting planet group - "+getBean().getId()); @@ -143,51 +143,51 @@ public String delete() { addError("Error deleting planet group"); } } - + return LIST; } - - - /** - * Validate posted group + + + /** + * Validate posted group */ private void myValidate() { - + if(StringUtils.isEmpty(getBean().getTitle())) { addError("planetGroups.error.title"); } - + if(StringUtils.isEmpty(getBean().getHandle())) { addError("planetGroups.error.handle"); } - + if(getBean().getHandle() != null && "all".equals(getBean().getHandle())) { addError("planetGroups.error.nameReserved"); } - + // make sure duplicate group handles are prevented } - - + + public List getGroups() { - + List displayGroups = new ArrayList(); - + Iterator allgroups = getPlanet().getGroups().iterator(); while (allgroups.hasNext()) { PlanetGroup agroup = (PlanetGroup) allgroups.next(); - + // The "all" group is considered a special group and cannot be // managed independently if (!agroup.getHandle().equals("all")) { displayGroups.add(agroup); } } - + return displayGroups; } - - + + public PlanetGroupsBean getBean() { return bean; } @@ -195,7 +195,7 @@ public PlanetGroupsBean getBean() { public void setBean(PlanetGroupsBean bean) { this.bean = bean; } - + public PlanetGroup getGroup() { return group; } @@ -203,5 +203,5 @@ public PlanetGroup getGroup() { public void setGroup(PlanetGroup group) { this.group = group; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupsBean.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupsBean.java index 10ef516fb6..e234339932 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupsBean.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupsBean.java @@ -25,12 +25,12 @@ * A simple bean for managing the form data used by the PlanetGroups. */ public class PlanetGroupsBean { - + private String id = null; private String title = null; private String handle = null; - - + + public String getId() { return id; } @@ -54,20 +54,20 @@ public String getHandle() { public void setHandle(String handle) { this.handle = handle; } - - + + public void copyTo(PlanetGroup dataHolder) { - + dataHolder.setTitle(getTitle()); dataHolder.setHandle(getHandle()); } - - + + public void copyFrom(PlanetGroup dataHolder) { - + setId(dataHolder.getId()); setTitle(dataHolder.getTitle()); setHandle(dataHolder.getHandle()); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetSubscriptions.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetSubscriptions.java index 1ac36c1995..2e56080ff9 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetSubscriptions.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetSubscriptions.java @@ -36,55 +36,55 @@ * Manage planet group subscriptions, default group is "all". */ public class PlanetSubscriptions extends PlanetUIAction { - + private static final Log log = LogFactory.getLog(PlanetSubscriptions.class); - + // id of the group we are working in private String groupHandle = null; - + // the planet group we are working in private PlanetGroup group = null; - + // the subscription to deal with private String subUrl = null; - - + + public PlanetSubscriptions() { this.actionName = "planetSubscriptions"; this.desiredMenu = "admin"; this.pageTitle = "planetSubscriptions.title"; } - - + + @Override public List requiredGlobalPermissionActions() { return Collections.singletonList(GlobalPermission.ADMIN); } - + @Override public boolean isWeblogRequired() { return false; } - - + + @Override public void myPrepare() { - + PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + // lookup group we are operating on, if none specified then use default if (getGroupHandle() == null) { setGroupHandle("all"); } - + try { setGroup(pmgr.getGroup(getPlanet(), getGroupHandle())); } catch (RollerException ex) { log.error("Error looking up planet group - "+getGroupHandle(), ex); } } - - + + /** * Populate page model and forward to subscription page */ @@ -92,78 +92,78 @@ public String execute() { return LIST; } - - /** - * Save subscription, add to current group + + /** + * Save subscription, add to current group */ public String save() { - + myValidate(); - + if(!hasActionErrors()) try { PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + // check if this subscription already exists before adding it Subscription sub = pmgr.getSubscription(getSubUrl()); if(sub == null) { log.debug("Adding New Subscription - "+getSubUrl()); - + // sub doesn't exist yet, so we need to fetch it FeedFetcher fetcher = PlanetFactory.getPlanet().getFeedFetcher(); sub = fetcher.fetchSubscription(getSubUrl()); - + // save new sub pmgr.saveSubscription(sub); } else { log.debug("Adding Existing Subscription - "+getSubUrl()); - + // Subscription already exists addMessage("planetSubscription.foundExisting", sub.getTitle()); } - + // add the sub to the group group.getSubscriptions().add(sub); sub.getGroups().add(group); pmgr.saveGroup(group); - + // flush changes PlanetFactory.getPlanet().flush(); - + // clear field after success setSubUrl(null); - + addMessage("planetSubscription.success.saved"); - + } catch (RollerException ex) { log.error("Unexpected error saving subscription", ex); addError("planetSubscriptions.error.duringSave", ex.getRootCauseMessage()); } - + return LIST; } - - /** - * Delete subscription, reset form + + /** + * Delete subscription, reset form */ public String delete() { - + if(getSubUrl() != null) try { - + PlanetManager pmgr = PlanetFactory.getPlanet().getPlanetManager(); - + // remove subscription Subscription sub = pmgr.getSubscription(getSubUrl()); getGroup().getSubscriptions().remove(sub); sub.getGroups().remove(getGroup()); pmgr.saveGroup(getGroup()); PlanetFactory.getPlanet().flush(); - + // clear field after success setSubUrl(null); - + addMessage("planetSubscription.success.deleted"); - + } catch (RollerException ex) { log.error("Error removing planet subscription", ex); addError("planetSubscription.error.deleting"); @@ -171,25 +171,25 @@ public String delete() { return LIST; } - - - /** - * Validate posted subscription, fill in blanks via Technorati + + + /** + * Validate posted subscription, fill in blanks via Technorati */ private void myValidate() { - + if(StringUtils.isEmpty(getSubUrl())) { addError("planetSubscription.error.feedUrl"); } } - - + + public List getSubscriptions() { - + List subs = Collections.EMPTY_LIST; if(getGroup() != null) { Set subsSet = getGroup().getSubscriptions(); - + // iterate over list and build display list subs = new ArrayList(); for( Subscription sub : subsSet ) { @@ -199,11 +199,11 @@ public List getSubscriptions() { } } } - + return subs; } - - + + public String getGroupHandle() { return groupHandle; } @@ -211,7 +211,7 @@ public String getGroupHandle() { public void setGroupHandle(String groupHandle) { this.groupHandle = groupHandle; } - + public PlanetGroup getGroup() { return group; } @@ -226,5 +226,5 @@ public String getSubUrl() { public void setSubUrl(String subUrl) { this.subUrl = subUrl; - } + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetUIAction.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetUIAction.java index 1829aa0ea1..e6262acbb0 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetUIAction.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetUIAction.java @@ -28,15 +28,15 @@ * An extension of the UIAction class specific to the Planet actions. */ public abstract class PlanetUIAction extends UIAction { - + private static Log log = LogFactory.getLog(PlanetUIAction.class); - + public static final String DEFAULT_PLANET_HANDLE = "default"; - + // the planet used by all Planet actions private Planet planet = null; - - + + public Planet getPlanet() { if(planet == null) { try { @@ -48,5 +48,5 @@ public Planet getPlanet() { } return planet; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/CmaRollerContext.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/CmaRollerContext.java index 9df9e9aa3f..505209fff9 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/CmaRollerContext.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/CmaRollerContext.java @@ -29,18 +29,18 @@ * * @author Shing Wai Chan */ -public class CmaRollerContext extends RollerContext { - +public class CmaRollerContext extends RollerContext { + private static Log log = LogFactory.getLog(CmaRollerContext.class); - + public CmaRollerContext() { super(); } - + /** * Setup Acegi security features. */ - protected void initializeSecurityFeatures(ServletContext context) { + protected void initializeSecurityFeatures(ServletContext context) { // no need to setup Acegi security } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java index a9fdfe4a84..16d7499bcf 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java @@ -60,38 +60,38 @@ /** * Initialize the Roller web application/context. */ -public class RollerContext extends ContextLoaderListener - implements ServletContextListener { - +public class RollerContext extends ContextLoaderListener + implements ServletContextListener { + private static Log log = LogFactory.getLog(RollerContext.class); - + private static ServletContext servletContext = null; - + public RollerContext() { super(); } - - + + /** - * Access to the plugin manager for the UI layer. TODO: we may want - * something similar to the Roller interface for the UI layer if we dont + * Access to the plugin manager for the UI layer. TODO: we may want + * something similar to the Roller interface for the UI layer if we dont * want methods like this here in RollerContext. */ public static UIPluginManager getUIPluginManager() { return UIPluginManagerImpl.getInstance(); } - - + + /** * Get the ServletContext. * @return ServletContext */ public static ServletContext getServletContext() { return servletContext; - } - - + } + + /** * Responds to app-init event and triggers startup procedures. */ @@ -101,19 +101,19 @@ public void contextInitialized(ServletContextEvent sce) { // Keep a reverence to ServletContext object this.servletContext = sce.getServletContext(); - + // Call Spring's context ContextLoaderListener to initialize all the // context files specified in web.xml. This is necessary because // listeners don't initialize in the order specified in 2.3 containers super.contextInitialized(sce); - + // get the *real* path to /resources String ctxPath = servletContext.getRealPath("/"); if(!ctxPath.endsWith(File.separator)) ctxPath += File.separator + "resources"; else ctxPath += "resources"; - + // try setting the uploads path to /resources // NOTE: this should go away at some point // we leave it here for now to allow users to keep writing @@ -123,7 +123,7 @@ public void contextInitialized(ServletContextEvent sce) { // enough to disregard this call unless the uploads.path // is set to ${webapp.context} WebloggerConfig.setUploadsDir(ctxPath); - + // try setting the themes path to /themes // NOTE: this should go away at some point // we leave it here for now to allow users to keep using @@ -133,8 +133,8 @@ public void contextInitialized(ServletContextEvent sce) { // enough to disregard this call unless the themes.dir // is set to ${webapp.context} WebloggerConfig.setThemesDir(servletContext.getRealPath("/")+File.separator+"themes"); - - + + // Now prepare the core services of the app so we can bootstrap try { WebloggerStartup.prepare(); @@ -142,8 +142,8 @@ public void contextInitialized(ServletContextEvent sce) { log.fatal("Roller Weblogger startup failed during app preparation", ex); return; } - - + + // if preparation failed or is incomplete then we are done, // otherwise try to bootstrap the business tier if (!WebloggerStartup.isPrepared()) { @@ -156,20 +156,20 @@ public void contextInitialized(ServletContextEvent sce) { try { // trigger bootstrapping process WebloggerFactory.bootstrap(); - + // trigger initialization process WebloggerFactory.getWeblogger().initialize(); - + } catch (BootstrapException ex) { log.fatal("Roller Weblogger bootstrap failed", ex); } catch (WebloggerException ex) { log.fatal("Roller Weblogger initialization failed", ex); } - + // Initialize Planet if necessary if (WebloggerFactory.isBootstrapped()) { if (WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) { - + // Now prepare the core services of planet so we can bootstrap it try { PlanetStartup.prepare(); @@ -177,87 +177,87 @@ public void contextInitialized(ServletContextEvent sce) { log.fatal("Roller Planet startup failed during app preparation", ex); return; } - + try { // trigger planet bootstrapping process // we need to use our own planet provider for integration String guiceModule = WebloggerConfig.getProperty("planet.aggregator.guice.module"); PlanetProvider provider = new GuicePlanetProvider(guiceModule); PlanetFactory.bootstrap(provider); - + // and now initialize planet PlanetFactory.getPlanet().initialize(); - + } catch (Throwable t) { log.fatal("Roller Planet initialization failed", t); } } } } - - + + // do a small amount of work to initialize the web tier try { // Initialize Acegi based on Roller configuration initializeSecurityFeatures(servletContext); - + // Setup Velocity template engine setupVelocity(); } catch (WebloggerException ex) { log.fatal("Error initializing Roller Weblogger web tier", ex); } - + } - - - /** + + + /** * Responds to app-destroy event and triggers shutdown sequence. */ - public void contextDestroyed(ServletContextEvent sce) { - WebloggerFactory.getWeblogger().shutdown(); + public void contextDestroyed(ServletContextEvent sce) { + WebloggerFactory.getWeblogger().shutdown(); // do we need a more generic mechanism for presentation layer shutdown? CacheManager.shutdown(); } - - + + /** * Initialize the Velocity rendering engine. */ - private void setupVelocity() throws WebloggerException { + private void setupVelocity() throws WebloggerException { log.info("Initializing Velocity"); - + // initialize the Velocity engine Properties velocityProps = new Properties(); - + try { InputStream instream = servletContext.getResourceAsStream("/WEB-INF/velocity.properties"); - + velocityProps.load(instream); - + // need to dynamically add old macro libraries if they are enabled if(WebloggerConfig.getBooleanProperty("rendering.legacyModels.enabled")) { String macroLibraries = (String) velocityProps.get("velocimacro.library"); String oldLibraries = WebloggerConfig.getProperty("velocity.oldMacroLibraries"); - + // set the new value velocityProps.setProperty("velocimacro.library", oldLibraries+","+macroLibraries); } - + log.debug("Velocity props = "+velocityProps); - + // init velocity RuntimeSingleton.init(velocityProps); - + } catch (Exception e) { throw new WebloggerException(e); } - + } - + /** * Setup Spring Security security features. */ - protected void initializeSecurityFeatures(ServletContext context) { + protected void initializeSecurityFeatures(ServletContext context) { ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); @@ -265,14 +265,14 @@ protected void initializeSecurityFeatures(ServletContext context) { /*String[] beanNames = ctx.getBeanDefinitionNames(); for (String name : beanNames) System.out.println(name);*/ - + String rememberMe = WebloggerConfig.getProperty("rememberme.enabled"); boolean rememberMeEnabled = Boolean.valueOf(rememberMe).booleanValue(); - + log.info("Remember Me enabled: " + rememberMeEnabled); - + context.setAttribute("rememberMeEnabled", rememberMe); - + if (!rememberMeEnabled) { ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager"); for (Iterator it = provider.getProviders().iterator(); it.hasNext();) { @@ -282,10 +282,10 @@ protected void initializeSecurityFeatures(ServletContext context) { } } } - + String encryptPasswords = WebloggerConfig.getProperty("passwds.encryption.enabled"); boolean doEncrypt = Boolean.valueOf(encryptPasswords).booleanValue(); - + if (doEncrypt) { DaoAuthenticationProvider provider = (DaoAuthenticationProvider) ctx.getBean("org.springframework.security.providers.dao.DaoAuthenticationProvider#0"); String algorithm = WebloggerConfig.getProperty("passwds.encryption.algorithm"); @@ -308,10 +308,10 @@ protected void initializeSecurityFeatures(ServletContext context) { (AuthenticationProcessingFilterEntryPoint) ctx.getBean("_formLoginEntryPoint"); entryPoint.setForceHttps(true); } - + /* if (WebloggerConfig.getBooleanProperty("schemeenforcement.enabled")) { - + ChannelProcessingFilter procfilter = (ChannelProcessingFilter)ctx.getBean("channelProcessingFilter"); ConfigAttributeDefinition secureDef = new ConfigAttributeDefinition(); @@ -320,7 +320,7 @@ protected void initializeSecurityFeatures(ServletContext context) { insecureDef.addConfigAttribute(new SecurityConfig("REQUIRES_INSECURE_CHANNEL")); PathBasedFilterInvocationDefinitionMap defmap = (PathBasedFilterInvocationDefinitionMap)procfilter.getFilterInvocationDefinitionSource(); - + // add HTTPS URL path patterns to Acegi config String httpsUrlsProp = WebloggerConfig.getProperty("schemeenforcement.https.urls"); if (httpsUrlsProp != null) { @@ -334,13 +334,13 @@ protected void initializeSecurityFeatures(ServletContext context) { } */ } - - + + /** * Flush user from any caches maintained by security system. */ - public static void flushAuthenticationUserCache(String userName) { - ApplicationContext ctx = + public static void flushAuthenticationUserCache(String userName) { + ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); try { UserCache userCache = (UserCache) ctx.getBean("userCache"); @@ -351,19 +351,19 @@ public static void flushAuthenticationUserCache(String userName) { log.debug("No userCache bean in context", exc); } } - - + + /** * Get an instance of AutoProvision, if available in roller.properties * @return AutoProvision */ - public static AutoProvision getAutoProvision() { + public static AutoProvision getAutoProvision() { String clazzName = WebloggerConfig.getProperty("users.sso.autoProvision.className"); - + if (null == clazzName) { return null; } - + Class clazz; try { clazz = Class.forName(clazzName); @@ -371,11 +371,11 @@ public static AutoProvision getAutoProvision() { log.warn("Unable to found specified Auto Provision class.", e); return null; } - + if(null == clazz) { return null; } - + Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(AutoProvision.class)) { @@ -387,7 +387,7 @@ public static AutoProvision getAutoProvision() { log.warn("IllegalAccessException while creating: " + clazzName, e); } } - } - return null; - } + } + return null; + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 95a00d3699..e144621738 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -42,21 +42,21 @@ * * @web.listener */ -public class RollerSession +public class RollerSession implements HttpSessionListener, HttpSessionActivationListener, Serializable { - + static final long serialVersionUID = 5890132909166913727L; - + // the id of the user represented by this session private String userName = null; - + private static Log log = LogFactory.getLog(RollerSession.class); - + public static final String ROLLER_SESSION = "org.apache.roller.weblogger.rollersession"; public static final String ERROR_MESSAGE = "rollererror_message"; public static final String STATUS_MESSAGE = "rollerstatus_message"; - - + + /** * Get RollerSession from request (and add user if not already present). */ @@ -65,26 +65,26 @@ public static RollerSession getRollerSession(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session != null) { rollerSession = (RollerSession)session.getAttribute(ROLLER_SESSION); - + if (rollerSession == null) { // HttpSession with no RollerSession? // Must be a session that was de-serialized from a previous run. rollerSession = new RollerSession(); session.setAttribute(ROLLER_SESSION, rollerSession); } - + Principal principal = request.getUserPrincipal(); // If we've got a principal but no user object, then attempt to get - // user object from user manager but *only* do this if we have been - // bootstrapped because under an SSO scenario we may have a + // user object from user manager but *only* do this if we have been + // bootstrapped because under an SSO scenario we may have a // principal even before we have been bootstrapped. - if (rollerSession.getAuthenticatedUser() == null && principal != null && WebloggerFactory.isBootstrapped()) { + if (rollerSession.getAuthenticatedUser() == null && principal != null && WebloggerFactory.isBootstrapped()) { try { - + UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); User user = umgr.getUserByUserName(principal.getName()); - + // check for OpenID username (in the form of a URL) if (user == null && principal.getName() != null && principal.getName().startsWith("http://")) { String openidurl = principal.getName(); @@ -92,14 +92,14 @@ public static RollerSession getRollerSession(HttpServletRequest request) { openidurl = openidurl.substring(0, openidurl.length() - 1); } user = umgr.getUserByAttribute( - UserAttribute.Attributes.OPENID_URL.toString(), + UserAttribute.Attributes.OPENID_URL.toString(), openidurl); } - + // try one time to auto-provision, only happens if user==null // which means installation has SSO-enabled in security.xml if (user == null && WebloggerConfig.getBooleanProperty("users.sso.autoProvision.enabled")) { - + // provisioning enabled, get provisioner and execute AutoProvision provisioner = RollerContext.getAutoProvision(); if(provisioner != null) { @@ -114,35 +114,35 @@ public static RollerSession getRollerSession(HttpServletRequest request) { if (user != null && user.getEnabled().booleanValue()) { rollerSession.setAuthenticatedUser(user); } - + } catch (WebloggerException e) { log.error("ERROR: getting user object",e); } } } - + return rollerSession; } - - + + /** Create session's Roller instance */ public void sessionCreated(HttpSessionEvent se) { RollerSession rollerSession = new RollerSession(); se.getSession().setAttribute(ROLLER_SESSION, rollerSession); } - - + + public void sessionDestroyed(HttpSessionEvent se) { clearSession(se); } - - + + /** Init session as if it was new */ public void sessionDidActivate(HttpSessionEvent se) { } - - - /** + + + /** * Purge session before passivation. Because Roller currently does not * support session recovery, failover, migration, or whatever you want * to call it when sessions are saved and then restored at some later @@ -151,13 +151,13 @@ public void sessionDidActivate(HttpSessionEvent se) { public void sessionWillPassivate(HttpSessionEvent se) { clearSession(se); } - - + + /** * Authenticated user associated with this session. */ public User getAuthenticatedUser() { - + User authenticUser = null; if(userName != null) { try { @@ -167,19 +167,19 @@ public User getAuthenticatedUser() { log.warn("Error looking up authenticated user "+userName, ex); } } - + return authenticUser; } - - + + /** * Authenticated user associated with this session. */ public void setAuthenticatedUser(User authenticatedUser) { this.userName = authenticatedUser.getUserName(); } - - + + private void clearSession(HttpSessionEvent se) { HttpSession session = se.getSession(); try { @@ -191,5 +191,5 @@ private void clearSession(HttpSessionEvent se) { } } } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java index 979b1181fa..4ff274efee 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java @@ -42,48 +42,48 @@ public class BootstrapFilter implements Filter { private ServletContext context = null; private static Log log = LogFactory.getLog(BootstrapFilter.class); - - + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.debug("Entered "+request.getRequestURI()); - + if ("auto".equals(WebloggerConfig.getProperty("installation.type")) - && !WebloggerFactory.isBootstrapped() + && !WebloggerFactory.isBootstrapped() && !isInstallUrl(request.getRequestURI())) { - + log.debug("Forwarding to install page"); - + // we doing an install, so forward to installer RequestDispatcher rd = context.getRequestDispatcher( "/roller-ui/install/install.rol"); rd.forward(req, res); - + } else { chain.doFilter(request, response); } - + log.debug("Exiting "+request.getRequestURI()); } - - + + private boolean isInstallUrl(String uri) { return (uri != null && ( uri.endsWith("bootstrap.rol") - || uri.endsWith("create.rol") - || uri.endsWith("upgrade.rol") - || uri.endsWith(".js") + || uri.endsWith("create.rol") + || uri.endsWith("upgrade.rol") + || uri.endsWith(".js") || uri.endsWith(".css"))); } - - + + public void init(FilterConfig filterConfig) throws ServletException { context = filterConfig.getServletContext(); } - - public void destroy() {} + + public void destroy() {} } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CharEncodingFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CharEncodingFilter.java index 5560478537..32d32c2e70 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CharEncodingFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CharEncodingFilter.java @@ -31,32 +31,32 @@ /** - * Entry point filter for all requests. This filter ensures that the request - * encoding is set to UTF-8 before any other processing forces request parsing - * using a default encoding. It also syncs up the Struts and JSTL locales. + * Entry point filter for all requests. This filter ensures that the request + * encoding is set to UTF-8 before any other processing forces request parsing + * using a default encoding. It also syncs up the Struts and JSTL locales. * This filter should normally be first and last in the chain. * * @author Anil Gangolli */ public class CharEncodingFilter implements Filter { - + private FilterConfig mFilterConfig = null; private static Log mLogger = LogFactory.getFactory().getInstance(CharEncodingFilter.class); - + /** * init */ public void init(FilterConfig filterConfig) throws ServletException { mFilterConfig = filterConfig; } - + /** * destroy */ public void destroy() { } - + /** * Set the character encoding and sync up Struts and JSTL locales. This filter should normally be first (and last) * in the chain. @@ -65,16 +65,16 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (mLogger.isDebugEnabled()) mLogger.debug("Processing CharEncodingFilter"); try { - - req.setCharacterEncoding("UTF-8"); + + req.setCharacterEncoding("UTF-8"); if (mLogger.isDebugEnabled()) mLogger.debug("Set request character encoding to UTF-8"); - + } catch (UnsupportedEncodingException e) { // This should never happen since UTF-8 is a Java-specified required encoding. throw new ServletException("Can't set incoming encoding to UTF-8"); } - + chain.doFilter(req, res); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CompressionFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CompressionFilter.java index 0b524c5ccf..f4d368c33f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CompressionFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CompressionFilter.java @@ -39,82 +39,82 @@ import org.apache.roller.weblogger.config.WebloggerConfig; -/** +/** * Filter that compresses output with gzip (assuming that browser supports gzip). *

    - * Taken from More Servlets and JavaServer Pages from Prentice Hall and + * Taken from More Servlets and JavaServer Pages from Prentice Hall and * Sun Microsystems Press, http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */ public class CompressionFilter implements Filter { - + private static Log log = LogFactory.getLog(CompressionFilter.class); - + private boolean enabled = true; - - - /** - * If browser does not support gzip, invoke resource normally. If browser - * does support gzip, set the Content-Encoding response header and invoke - * resource with a wrapped response that collects all the output. Extract - * the output and write it into a gzipped byte array. Finally, write that + + + /** + * If browser does not support gzip, invoke resource normally. If browser + * does support gzip, set the Content-Encoding response header and invoke + * resource with a wrapped response that collects all the output. Extract + * the output and write it into a gzipped byte array. Finally, write that * array to the client's output stream. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { - + HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; - + if (!this.enabled || !isGzipSupported(req)) { // Invoke resource normally. chain.doFilter(req, res); } else { // Tell browser we are sending it gzipped data. res.setHeader("Content-Encoding", "gzip"); - + // Invoke resource, accumulating output in the wrapper. ByteArrayResponseWrapper responseWrapper = new ByteArrayResponseWrapper(response); - + chain.doFilter(req, responseWrapper); - + ByteArrayOutputStream outputStream = responseWrapper.getByteArrayOutputStream(); - + // Get character array representing output. log.debug("Pre-zip size:" + outputStream.size()); - + // Make a writer that compresses data and puts // it into a byte array. ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); GZIPOutputStream zipOut = new GZIPOutputStream(byteStream); - + // Compress original output and put it into byte array. zipOut.write(responseWrapper.getByteArrayOutputStream().toByteArray()); - + // Gzip streams must be explicitly closed. zipOut.close(); - + log.debug("Gzip size:" + byteStream.size()); - + // Update the Content-Length header. res.setContentLength(byteStream.size()); - + ByteArrayOutputStreamWrapper newOut = (ByteArrayOutputStreamWrapper) responseWrapper.getOutputStream(); newOut.clear(); newOut.setFinallized(); - + /* now force close of OutputStream */ newOut.write(byteStream.toByteArray()); newOut.close(); } - + } - + public void init(FilterConfig config) throws ServletException { - + // is compression enabled? if(WebloggerConfig.getBooleanProperty("compression.gzipResponse.enabled")) { this.enabled = true; @@ -124,103 +124,103 @@ public void init(FilterConfig config) throws ServletException { log.info("Compressed Output DISABLED"); } } - - + + public void destroy() {} - - + + private boolean isGzipSupported(HttpServletRequest req) { String browserEncodings = req.getHeader("Accept-Encoding"); return ((browserEncodings != null) && (browserEncodings.indexOf("gzip") != -1)); } - - + + /** * Implementation of HttpServletResponseWrapper that supports caching. */ private class ByteArrayResponseWrapper extends HttpServletResponseWrapper { - + private PrintWriter tpWriter; private ByteArrayOutputStreamWrapper tpStream; - - + + public ByteArrayResponseWrapper(ServletResponse inResp) throws IOException { super((HttpServletResponse) inResp); tpStream = new ByteArrayOutputStreamWrapper(inResp.getOutputStream()); tpWriter = new PrintWriter(new OutputStreamWriter(tpStream,"UTF-8")); } - - + + public ServletOutputStream getOutputStream() throws IOException { return tpStream; } - + public PrintWriter getWriter() throws IOException { return tpWriter; } - + /** * Get a String representation of the entire buffer. */ public String toString() { return tpStream.getByteArrayStream().toString(); } - + public ByteArrayOutputStream getByteArrayOutputStream() throws IOException { return tpStream.getByteArrayStream(); } - + } - - + + /** * Implementation of ServletOutputStream that allows the filter to hold the * Response content for insertion into the cache. */ private class ByteArrayOutputStreamWrapper extends ServletOutputStream { - + protected OutputStream intStream; protected ByteArrayOutputStream baStream; protected boolean finallized = false; protected boolean flushOnFinalizeOnly = true; - - + + public ByteArrayOutputStreamWrapper(OutputStream outStream) { intStream = outStream; baStream = new ByteArrayOutputStream(); } - + public ByteArrayOutputStreamWrapper() { intStream = System.out; baStream = new ByteArrayOutputStream(); } - - + + public ByteArrayOutputStream getByteArrayStream() { return baStream; } - + public void setFinallized() { finallized = true; } - + public boolean isFinallized() { return finallized; } - - + + public void write(int i) throws java.io.IOException { baStream.write(i); } - + public void close() throws java.io.IOException { if (finallized) { processStream(); intStream.close(); } } - + public void flush() throws java.io.IOException { if (baStream.size() != 0) { if (!flushOnFinalizeOnly || finallized) { @@ -229,16 +229,16 @@ public void flush() throws java.io.IOException { } } } - + protected void processStream() throws java.io.IOException { intStream.write(baStream.toByteArray()); intStream.flush(); } - + public void clear() { baStream = new ByteArrayOutputStream(); } - + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CustomOpenIDAuthenticationProcessingFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CustomOpenIDAuthenticationProcessingFilter.java index 66ade3b6d7..f683497820 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CustomOpenIDAuthenticationProcessingFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/CustomOpenIDAuthenticationProcessingFilter.java @@ -35,7 +35,7 @@ * Handle response from OpenID provider. * @author Tatyana Tokareva */ -public class CustomOpenIDAuthenticationProcessingFilter +public class CustomOpenIDAuthenticationProcessingFilter extends OpenIDAuthenticationProcessingFilter implements Filter { private OpenIDConsumer consumer; @@ -46,28 +46,28 @@ public class CustomOpenIDAuthenticationProcessingFilter public Authentication attemptAuthentication(HttpServletRequest req) throws AuthenticationException { OpenIDAuthenticationToken auth = null; - // Processing standard OpenId user authentication + // Processing standard OpenId user authentication auth = (OpenIDAuthenticationToken) super.attemptAuthentication(req); if (auth.getAuthorities()[0].getAuthority().equals("openidLogin")) { - /* TODO: when Spring Security 2.1 is released, we can uncomment - * this code, which will allow us to pre-populate the new user + /* TODO: when Spring Security 2.1 is released, we can uncomment + * this code, which will allow us to pre-populate the new user * registration form with information from the OpenID Provider. - * + * Collection sREGAttributesList = auth.getAttributes(); OpenIDUserAttribute openidName = new OpenIDUserAttribute( OpenIDUserAttribute.Attributes.openidname.toString(), ""); openidName.setValue(auth.getIdentityUrl()); sREGAttributesList.add(openidName); - + // TODO: find a better place to stash attributes - UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); mgr.userAttributes.put( UserAttribute.Attributes.openidUrl.toString(), sREGAttributesList); */ - + // Username not found in Roller for this user, so throw exception // which will route user to the new user registration page. throw new UsernameNotFoundException("ERROR no user: new openid user"); diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/DebugFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/DebugFilter.java index 6d56454432..05f8ac41ef 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/DebugFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/DebugFilter.java @@ -40,39 +40,39 @@ * @web.filter name="DebugFilter" */ public class DebugFilter implements Filter { - + private static Log log = LogFactory.getLog(DebugFilter.class); - - + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.info("ENTERING "+request.getRequestURL()); - + // some info about the request and response log.info("Response Object:"); log.info(" isCommited = "+response.isCommitted()); log.info(" bufferSize = "+response.getBufferSize()); log.info(""); - + chain.doFilter(request, response); - + log.info("EXITING "+request.getRequestURL()); - + // some info about the request and response log.info("Response Object:"); log.info(" isCommited = "+response.isCommitted()); log.info(" bufferSize = "+response.getBufferSize()); log.info(""); } - - + + public void destroy() {} - - + + public void init(FilterConfig filterConfig) {} - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/IPBanFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/IPBanFilter.java index 6caa1a6be1..5c6254bdf6 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/IPBanFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/IPBanFilter.java @@ -38,22 +38,22 @@ * @web.filter name="IPBanFilter" */ public class IPBanFilter implements Filter { - + private static Log log = LogFactory.getLog(IPBanFilter.class); - - + + public void init(FilterConfig filterConfig) throws ServletException { - + log.info("INIT IPBanFilter"); } - - + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + // check if client is allowed if(IPBanList.getInstance().isBanned(request.getRemoteAddr())) { log.debug("BANNED "+request.getRemoteAddr()); @@ -63,8 +63,8 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) chain.doFilter(request, response); } } - - + + public void destroy() {} - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java index 9b86ee1061..1d08c69a8c 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java @@ -40,70 +40,70 @@ * @web.filter name="InitFilter" */ public class InitFilter implements Filter { - + private static Log log = LogFactory.getLog(InitFilter.class); - + private boolean initialized = false; - - + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + if(!initialized) { // first request, lets do our initialization HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + // determine absolute and relative url paths to the app String relPath = request.getContextPath(); String absPath = this.getAbsoluteUrl(request); - + // set them in our config WebloggerRuntimeConfig.setAbsoluteContextURL(absPath); WebloggerRuntimeConfig.setRelativeContextURL(relPath); - + log.debug("relPath = "+relPath); log.debug("absPath = "+absPath); - + this.initialized = true; } - + chain.doFilter(req, res); } - - + + private String getAbsoluteUrl(HttpServletRequest request) { - + String url = null; - + String fullUrl = request.getRequestURL().toString(); - + // if the uri is only "/" then we are basically done if("/".equals(request.getRequestURI())) { log.info(fullUrl.substring(0, fullUrl.length()-1)); return fullUrl.substring(0, fullUrl.length()-1); } - + // find first "/" starting after hostname is specified int index = fullUrl.indexOf("/", fullUrl.indexOf(request.getServerName())); - + // extract just the part leading up to uri url = fullUrl.substring(0, index); - + // then just add on the context path url += request.getContextPath(); - + // make certain that we don't end with a / if(url.endsWith("/")) { url = url.substring(0, url.length()-1); } - + return url; } - - + + public void init(FilterConfig filterConfig) throws ServletException {} - + public void destroy() {} - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java index 30a338aa77..61ee87201e 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java @@ -41,28 +41,28 @@ * @web.filter name="PersistenceSessionFilter" */ public class PersistenceSessionFilter implements Filter { - + private static Log log = LogFactory.getLog(PersistenceSessionFilter.class); - - + + /** * Release Roller persistence session at end of request processing. */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.debug("Entered "+request.getRequestURI()); - + try { chain.doFilter(request, response); } finally { if (WebloggerFactory.isBootstrapped()) { log.debug("Releasing Roller Session"); WebloggerFactory.getWeblogger().release(); - + // if planet is enabled then release planet backend as well if (WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) { if (PlanetFactory.isBootstrapped()) { @@ -70,16 +70,16 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) } } } - + } - + log.debug("Exiting "+request.getRequestURI()); } - - + + public void init(FilterConfig filterConfig) throws ServletException {} - + public void destroy() {} - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/RoleAssignmentFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/RoleAssignmentFilter.java index 7eac7358a7..ce740f7d7d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/RoleAssignmentFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/RoleAssignmentFilter.java @@ -37,28 +37,28 @@ /** * Enable Roller's User Roles to work in CMA setup without a JDBC realm. - * - * If you're using Container Manager Authenticaton (CMA) and you're not using + * + * If you're using Container Manager Authenticaton (CMA) and you're not using * the a JDBC realm that can add the User Roles defined by Roller, then you can * use this class to ensure that the request Role methods operate against the * User Roles as defined by Roller's User Manager. */ public class RoleAssignmentFilter implements Filter { - + private static Log log = LogFactory.getLog(RoleAssignmentFilter.class); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; - log.debug("Entered "+request.getRequestURI()); + log.debug("Entered "+request.getRequestURI()); chain.doFilter(new RoleAssignmentRequestWrapper(request), res); log.debug("Exiting "+request.getRequestURI()); } - - + + public void init(FilterConfig filterConfig) throws ServletException {} - - public void destroy() {} + + public void destroy() {} } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/SchemeEnforcementFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/SchemeEnforcementFilter.java index 5152695613..5441e39109 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/SchemeEnforcementFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/filters/SchemeEnforcementFilter.java @@ -49,22 +49,22 @@ * @web.filter name="SchemeEnforcementFilter" */ public class SchemeEnforcementFilter implements Filter { - - private static Log mLogger = + + private static Log mLogger = LogFactory.getLog(SchemeEnforcementFilter.class); - + private FilterConfig filterConfig = null; - + private boolean schemeEnforcementEnabled = false; private boolean secureLoginEnabled = false; private int httpPort = 80; private int httpsPort = 443; private String httpsHeaderName = null; private String httpsHeaderValue = null; - + private Set allowedUrls = new HashSet(); - - + + /** * Process filter. * @@ -76,55 +76,55 @@ public class SchemeEnforcementFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - + if(this.schemeEnforcementEnabled && this.secureLoginEnabled) { - + HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; - + mLogger.debug("checking path = "+req.getServletPath()); - + if(!request.isSecure() && allowedUrls.contains(req.getServletPath())) { // http insecure request that should be over https String redirect = "https://"+req.getServerName(); - + if(this.httpsPort != 443) redirect += ":"+this.httpsPort; - + redirect += req.getRequestURI(); - + if(req.getQueryString() != null) redirect += "?"+req.getQueryString(); - + mLogger.debug("Redirecting to "+redirect); res.sendRedirect(redirect); return; - + } else if(request.isSecure() && !allowedUrls.contains(req.getServletPath())) { // https secure request that should be over http String redirect = "http://"+req.getServerName(); - + if(this.httpPort != 80) redirect += ":"+this.httpPort; - + redirect += req.getRequestURI(); - + if(req.getQueryString() != null) redirect += "?"+req.getQueryString(); - + mLogger.debug("Redirecting to "+redirect); res.sendRedirect(redirect); return; } } - + chain.doFilter(request, response); } - - + + public void destroy() {} - - + + /** * Filter init. * @@ -132,20 +132,20 @@ public void destroy() {} */ public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; - + // determine if we are doing scheme enforcement - this.schemeEnforcementEnabled = + this.schemeEnforcementEnabled = WebloggerConfig.getBooleanProperty("schemeenforcement.enabled"); - this.secureLoginEnabled = + this.secureLoginEnabled = WebloggerConfig.getBooleanProperty("securelogin.enabled"); - + if(this.schemeEnforcementEnabled && this.secureLoginEnabled) { // gather some more properties - String http_port = + String http_port = WebloggerConfig.getProperty("securelogin.http.port"); - String https_port = + String https_port = WebloggerConfig.getProperty("securelogin.https.port"); - + try { this.httpPort = Integer.parseInt(http_port); this.httpsPort = Integer.parseInt(https_port); @@ -153,14 +153,14 @@ public void init(FilterConfig filterConfig) { // ignored ... guess we'll have to use the defaults mLogger.warn("error with secure login ports", nfe); } - + // finally, construct our list of allowable https urls - String urls = + String urls = WebloggerConfig.getProperty("schemeenforcement.https.urls"); String[] urlsArray = urls.split(","); for(int i=0; i < urlsArray.length; i++) this.allowedUrls.add(urlsArray[i]); - + // some logging for the curious mLogger.info("Scheme enforcement = enabled"); if(mLogger.isDebugEnabled()) { @@ -170,5 +170,5 @@ public void init(FilterConfig filterConfig) { } } } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/TextEditor.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/TextEditor.java index 728de38938..aee12726d9 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/TextEditor.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/TextEditor.java @@ -26,21 +26,21 @@ * The default text editor. Basically just plain html textareas. */ public class TextEditor implements WeblogEntryEditor { - - + + public TextEditor() {} - - + + public String getId() { return "editor-text.jsp"; } - + public String getName() { return "editor.text.name"; } - + public String getJspPage() { return "/roller-ui/authoring/editors/editor-text.jsp"; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManager.java index aeb6277eb8..218e0f78d0 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManager.java @@ -25,15 +25,15 @@ * Plugin management for UI layer plugins. */ public interface UIPluginManager { - + /** * Get the list of all configured WeblogEntryEditors. * * @return List of all configure WeblogEntryEditor objects. */ public List getWeblogEntryEditors(); - - + + /** * Get a WeblogEntryEditor by name. If the specified editor cannot be found * or the id is null, then the default editor should be returned. @@ -43,5 +43,5 @@ public interface UIPluginManager { * desired editor could not be found. */ public WeblogEntryEditor getWeblogEntryEditor(String id); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.java index 78006a237f..1f6f958cfd 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.java @@ -32,78 +32,78 @@ * Plugin management for UI layer plugins. */ public class UIPluginManagerImpl implements UIPluginManager { - + private static Log log = LogFactory.getLog(UIPluginManagerImpl.class); - + // singleton instance private static UIPluginManagerImpl instance = null; - + // list of configured WeblogEntryEditor classes Map editors = new LinkedHashMap(); - + // the default WeblogEntryEditor WeblogEntryEditor defaultEditor = null; - - + + static { instance = new UIPluginManagerImpl(); } - - + + // private to enforce singleton pattern private UIPluginManagerImpl() { loadEntryEditorClasses(); } - - + + // static singleton accessor public static UIPluginManager getInstance() { return instance; } - - + + public List getWeblogEntryEditors() { // TODO: sort list of returned editors return new ArrayList(this.editors.values()); } - - + + public WeblogEntryEditor getWeblogEntryEditor(String id) { - + WeblogEntryEditor editor = null; - + // see if this editor is configured editor = (id == null) ? null : (WeblogEntryEditor) this.editors.get(id); if(editor == null) { editor = this.defaultEditor; } - + return editor; } - - + + /** * Initialize the set of configured editors and define the default editor. */ private void loadEntryEditorClasses() { - + log.debug("Initializing entry editor plugins"); - + String editorStr = WebloggerConfig.getProperty("plugins.weblogEntryEditors"); if (editorStr != null) { - + String[] editorList = StringUtils.stripAll(StringUtils.split(editorStr, ",")); for (int i=0; i < editorList.length; i++) { - + log.debug("trying editor " + editorList[i]); - + try { Class editorClass = Class.forName(editorList[i]); WeblogEntryEditor editor = (WeblogEntryEditor) editorClass.newInstance(); - + // looks okay, add it to the map this.editors.put(editor.getId(), editor); - + } catch(ClassCastException cce) { log.error("It appears that your editor does not implement "+ "the WeblogEntryEditor interface", cce); @@ -112,27 +112,27 @@ private void loadEntryEditorClasses() { } } } - + if(this.editors.size() < 1) { log.warn("No entry editors configured, this means that publishing "+ "entries will be impossible."); return; } - + // make sure the default editor is defined String defaultEditorId = WebloggerConfig.getProperty("plugins.defaultEditor"); if(defaultEditorId != null) { this.defaultEditor = (WeblogEntryEditor) this.editors.get(defaultEditorId); } - + if(this.defaultEditor == null) { // someone didn't configure the default editor properly // guess we'll just have to pick one for them log.warn("Default editor was not properly configured, picking one at random instead."); - + Object editor = this.editors.values().iterator().next(); this.defaultEditor = (WeblogEntryEditor) editor; } } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/WeblogEntryEditor.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/WeblogEntryEditor.java index 519b68f3da..26325d8bd1 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/WeblogEntryEditor.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/WeblogEntryEditor.java @@ -22,12 +22,12 @@ * Represents an editor for a WeblogEntry. */ public interface WeblogEntryEditor { - + /** * The unique identifier for this editor. * - * It is important that each editor have a unique identifier. The id for - * the editor is how it will be tracked and associated with each weblog + * It is important that each editor have a unique identifier. The id for + * the editor is how it will be tracked and associated with each weblog * that is using it, so having 2 editors with the same id would cause some * nasty problems. It is also preferable if the id not be a full class * name because then if you ever want to refactor the location of the class @@ -36,8 +36,8 @@ public interface WeblogEntryEditor { * @return The unique identifier for this WeblogEntryEditor. */ public String getId(); - - + + /** * The display name for the editor, as seen by users. * @@ -49,8 +49,8 @@ public interface WeblogEntryEditor { * @return The display name of this WeblogEntryEditor. */ public String getName(); - - + + /** * The location of the jsp page inside the webapp that renders this editor. * diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/XinhaEditor.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/XinhaEditor.java index 1c800869f4..fcad8a588b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/XinhaEditor.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/plugins/XinhaEditor.java @@ -24,23 +24,23 @@ * Uses ID of 'editor-rte.jsp' for historical reasons. */ public class XinhaEditor implements WeblogEntryEditor { - - + + public XinhaEditor() {} - - + + public String getId() { // return RTE becuase at one point we replaced RTE with Xinha // the real RTE editor will have to use a differernt ID. return "editor-rte.jsp"; } - + public String getName() { return "editor.xinha.name"; } - + public String getJspPage() { return "/roller-ui/authoring/editors/editor-xinha.jsp"; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AuthoritiesPopulator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AuthoritiesPopulator.java index 3d118d329d..d596644c03 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AuthoritiesPopulator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AuthoritiesPopulator.java @@ -41,7 +41,7 @@ public class AuthoritiesPopulator implements LdapAuthoritiesPopulator { /** A default role which will be assigned to all authenticated users if set */ private GrantedAuthority defaultRole = null; - + /* (non-Javadoc) * @see org.springframework.security.ldap.LdapAuthoritiesPopulator#getGrantedAuthorities(org.springframework.ldap.core.DirContextOperations, String) */ @@ -73,7 +73,7 @@ public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userData, S for(String role : roles) { authorities[i++] = new GrantedAuthorityImpl(role); } - + if (defaultRole != null) { authorities[roleCount-1] = defaultRole; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AutoProvision.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AutoProvision.java index e59363aa8a..2e7b84f776 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AutoProvision.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/AutoProvision.java @@ -22,5 +22,5 @@ public interface AutoProvision { public boolean execute(HttpServletRequest request); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/BasicUserAutoProvision.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/BasicUserAutoProvision.java index 563a77fe23..d9c9825eb4 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/BasicUserAutoProvision.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/BasicUserAutoProvision.java @@ -28,20 +28,20 @@ /** * @author Elias Torres (eliast@us.ibm.com) - * + * */ public class BasicUserAutoProvision implements AutoProvision { - + private static Log log = LogFactory.getFactory().getInstance(BasicUserAutoProvision.class); /* * (non-Javadoc) - * + * * @see org.apache.roller.weblogger.ui.core.security.AutoProvision#execute() */ public boolean execute(HttpServletRequest request) { User ud = CustomUserRegistry.getUserDetailsFromAuthentication(request); - + if(ud != null) { UserManager mgr; try { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java index 61fd90f841..e0819f3fc2 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java @@ -40,7 +40,7 @@ * */ public class CustomUserRegistry { - + private static final Log log = LogFactory.getLog(CustomUserRegistry.class); private static final String DEFAULT_SNAME_LDAP_ATTRIBUTE = "screenname"; @@ -49,7 +49,7 @@ public class CustomUserRegistry { private static final String DEFAULT_EMAIL_LDAP_ATTRIBUTE = "mail"; private static final String DEFAULT_LOCALE_LDAP_ATTRIBUTE = "locale"; private static final String DEFAULT_TIMEZONE_LDAP_ATTRIBUTE = "timezone"; - + private static final String SNAME_LDAP_PROPERTY = "users.sso.registry.ldap.attributes.screenname"; private static final String UID_LDAP_PROPERTY = "users.sso.registry.ldap.attributes.uid"; private static final String NAME_LDAP_PROPERTY = "users.sso.registry.ldap.attributes.name"; @@ -64,9 +64,9 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) log.info("SSO is not enabled. Skipping CustomUserRegistry functionality."); return null; } - + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - + User ud = new User(); // setting default ud.setId(null); @@ -97,7 +97,7 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) timezone = getRequestAttribute(request, WebloggerConfig.getProperty(TIMEZONE_LDAP_PROPERTY, DEFAULT_TIMEZONE_LDAP_ATTRIBUTE)); - + if (userName == null && fullName == null && screenName == null && email == null && locale == null && timezone == null) { @@ -107,26 +107,26 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) enabled = true; } } else { - + Object oPrincipal = authentication.getPrincipal(); - + if(oPrincipal == null) { log.warn("Principal is null. Skipping auto-registration."); return null; } - + if (!(oPrincipal instanceof UserDetails)) { log.warn("Unsupported Principal type in Authentication. Skipping auto-registration."); return null; } - + UserDetails userDetails = (UserDetails) oPrincipal; - + userName = userDetails.getUsername(); password = userDetails.getPassword(); enabled = userDetails.isEnabled(); - - + + if(userDetails instanceof RollerUserDetails) { RollerUserDetails rollerDetails = (RollerUserDetails) userDetails; @@ -135,7 +135,7 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) email = rollerDetails.getEmailAddress(); locale = rollerDetails.getLocale(); timezone = rollerDetails.getTimeZone(); - + } else if(userDetails instanceof LdapUserDetails) { LdapUserDetails ldapDetails = (LdapUserDetails) userDetails; @@ -145,7 +145,7 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) email = getLdapAttribute(attributes, WebloggerConfig.getProperty(EMAIL_LDAP_PROPERTY, DEFAULT_EMAIL_LDAP_ATTRIBUTE)); locale = getLdapAttribute(attributes, WebloggerConfig.getProperty(LOCALE_LDAP_PROPERTY, DEFAULT_LOCALE_LDAP_ATTRIBUTE)); timezone = getLdapAttribute(attributes, WebloggerConfig.getProperty(TIMEZONE_LDAP_PROPERTY, DEFAULT_TIMEZONE_LDAP_ATTRIBUTE)); - + } } @@ -170,29 +170,29 @@ public static User getUserDetailsFromAuthentication(HttpServletRequest request) return ud; } - + private static String getLdapAttribute(Attributes attributes, String name) { if(attributes == null) { return null; } - + Attribute attribute = attributes.get(name); - + if(attribute == null) { return null; } - + Object oValue = null; try { oValue = attribute.get(); } catch (NamingException e) { return null; } - + if(oValue == null) { return null; } - + return oValue.toString(); } @@ -203,7 +203,7 @@ private static String getRequestAttribute(HttpServletRequest request, String att if (attrObj instanceof String) { attr = (String)attrObj; } else if (attrObj instanceof Set) { - Set attrSet = (Set)attrObj; + Set attrSet = (Set)attrObj; if (!attrSet.isEmpty()) { attr = (String)attrSet.iterator().next(); } @@ -211,5 +211,5 @@ private static String getRequestAttribute(HttpServletRequest request, String att return attr; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetails.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetails.java index f6ac2b36a3..be68dbc1fb 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetails.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetails.java @@ -21,21 +21,21 @@ /** * An interface to extract additional properties from a UserDetails instance. These extra - * properties are needed in order to complete User object in RollerDB. - * + * properties are needed in order to complete User object in RollerDB. + * * @author Elias Torres (eliast@us.ibm.com) * */ public interface RollerUserDetails extends UserDetails { public String getTimeZone(); - + public String getLocale(); - + public String getScreenName(); public String getFullName(); public String getEmailAddress(); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java index d104eebe7d..2fc1bc5027 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java @@ -23,8 +23,8 @@ */ public class RollerUserDetailsService implements UserDetailsService { private static Log log = LogFactory.getLog(RollerUserDetailsService.class); - - public UserDetails loadUserByUsername(String userName) + + public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { Weblogger roller = null; try { @@ -37,14 +37,14 @@ public UserDetails loadUserByUsername(String userName) } try { UserManager umgr = roller.getUserManager(); - User userData = null; + User userData = null; if (userName.startsWith("http://")) { if (userName.endsWith("/")) { userName = userName.substring(0, userName.length() -1 ); } try { userData = umgr.getUserByAttribute( - UserAttribute.Attributes.OPENID_URL.toString(), + UserAttribute.Attributes.OPENID_URL.toString(), userName); } catch (WebloggerException ex) { throw new DataRetrievalFailureException("ERROR in user lookup", ex); @@ -52,10 +52,10 @@ public UserDetails loadUserByUsername(String userName) String name; String password; GrantedAuthority[] authorities; - - // We are not throwing UsernameNotFound exception in case of - // openid authentication in order to recieve user SREG attributes - // from the authentication filter and save them + + // We are not throwing UsernameNotFound exception in case of + // openid authentication in order to recieve user SREG attributes + // from the authentication filter and save them if (userData == null) { authorities = new GrantedAuthority[1]; GrantedAuthority g = new GrantedAuthorityImpl("openidLogin"); @@ -69,7 +69,7 @@ public UserDetails loadUserByUsername(String userName) } UserDetails usr = new org.springframework.security.userdetails.User(name, password, true, authorities); return usr; - + } else { try { userData = umgr.getUserByUserName(userName); @@ -79,16 +79,16 @@ public UserDetails loadUserByUsername(String userName) if (userData == null) { throw new UsernameNotFoundException("ERROR no user: " + userName); } - GrantedAuthority[] authorities = getAuthorities(userData, umgr); + GrantedAuthority[] authorities = getAuthorities(userData, umgr); return new org.springframework.security.userdetails.User(userData.getUserName(), userData.getPassword(), true, authorities); - } + } } catch (WebloggerException ex) { throw new DataAccessResourceFailureException("ERROR: fetching roles", ex); } - + } - + private GrantedAuthority[] getAuthorities(User userData, UserManager umgr) throws WebloggerException { List roles = umgr.getRoles(userData); GrantedAuthority[] authorities = new GrantedAuthorityImpl[roles.size()]; @@ -98,5 +98,5 @@ private GrantedAuthority[] getAuthorities(User userData, UserManager umgr) throw } return authorities; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/BigWeblogCalendarModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/BigWeblogCalendarModel.java index 1cbd4e587e..c71ca6f064 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/BigWeblogCalendarModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/BigWeblogCalendarModel.java @@ -36,26 +36,26 @@ * Model for big calendar that displays titles for each day. */ public class BigWeblogCalendarModel extends WeblogCalendarModel { - + private static Log mLogger = LogFactory.getLog(BigWeblogCalendarModel.class); - + protected static final SimpleDateFormat mStarDateFormat = DateUtil.get8charDateFormat(); - + protected static final SimpleDateFormat mSingleDayFormat = new SimpleDateFormat("dd"); - - + + public BigWeblogCalendarModel(WeblogPageRequest pRequest, String cat) { super(pRequest, cat); } - - + + protected void loadWeblogEntries(Date startDate, Date endDate, String catName) { try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); monthMap = mgr.getWeblogEntryObjectMap( - + weblog, // website startDate, // startDate endDate, // endDate @@ -68,13 +68,13 @@ protected void loadWeblogEntries(Date startDate, Date endDate, String catName) { monthMap = new HashMap(); } } - - + + public String getContent(Date day) { String content = null; try { StringBuffer sb = new StringBuffer(); - + // get the 8 char YYYYMMDD datestring for day, returns null // if no weblog entry on that day String dateString = null; @@ -82,23 +82,23 @@ public String getContent(Date day) { if ( entries != null ) { dateString = mStarDateFormat.format( ((WeblogEntry)entries.get(0)).getPubTime()); - + // append 8 char date string on end of selfurl String dayUrl = WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogCollectionURL(weblog, locale, cat, dateString, null, -1, false); - + sb.append("

    "); - + for ( int i=0; i"); sb.append(""); - + String title = ((WeblogEntry)entries.get(i)).getTitle().trim(); if ( title.length()==0 ) { title = ((WeblogEntry)entries.get(i)).getAnchor(); @@ -106,11 +106,11 @@ public String getContent(Date day) { if ( title.length() > 20 ) { title = title.substring(0,20)+"..."; } - + sb.append( title ); sb.append(""); } - + } else { sb.append("
    "); sb.append( mSingleDayFormat.format( day ) ); @@ -123,7 +123,7 @@ public String getContent(Date day) { } return content; } - + /** * Create URL for use on view-weblog page * @param day Day for URL or null if no entries on that day @@ -148,10 +148,10 @@ else if (dateString == null && !nextPrevMonthURL) { dateString = DateUtil.format6chars(day); } try { - if (nextPrevMonthURL && pageLink != null) { + if (nextPrevMonthURL && pageLink != null) { // next/prev month URLs point to current page url = WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogPageURL(weblog, locale, pageLink, null, cat, dateString, null, -1, false); - } else { + } else { // all other URLs point back to main weblog page url = WebloggerFactory.getWeblogger().getUrlStrategy().getWeblogCollectionURL(weblog, locale, cat, dateString, null, -1, false); } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarModel.java index e34c6a849b..85a3e45f27 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarModel.java @@ -26,19 +26,19 @@ */ public interface CalendarModel { public Calendar getCalendar(); - + public void setDay( String month ) throws Exception; - + public Date getDay(); - + public Date getNextMonth(); public Date getPrevMonth(); - + public String computePrevMonthUrl(); - + public String computeTodayMonthUrl(); - + public String computeNextMonthUrl(); /** @@ -46,7 +46,7 @@ public interface CalendarModel { * is the beginning of the month containing the creation date. */ //public Date getInitialMonth(); - + /** * Create URL for use on edit-weblog page, preserves the request * parameters used by the tabbed-menu tag for navigation. @@ -57,7 +57,7 @@ public interface CalendarModel { * @return URL for day, or null if no weblog entry on that day */ public String computeUrl( java.util.Date day, boolean monthURL, boolean valid ); - + /** * Get calendar cell content or null if none. * diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarTag.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarTag.java index 900a87fd8f..360901fc2e 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarTag.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/CalendarTag.java @@ -45,37 +45,37 @@ public class CalendarTag extends TagSupport { private static Log mLogger = LogFactory.getFactory().getInstance(CalendarTag.class); - + // JSP Attributes - + /** @jsp.attribute required="true" */ public String getName() { return mName; } public void setName( String name ) { mName = name; } private String mName = null; - + /* @jsp.attribute description="Date in yyyyMMdd format" public String getDate() { return mDate; } public void setDate( String s ) { mDate = s; } private String mDate = null; */ - + /** @jsp.attribute */ public String getModel() { return mModelName; } public void setModel( String s ) { mModelName= s; } private String mModelName = null; - + /** @jsp.attribute */ public String getClassSuffix() { return mClassSuffix; } public void setClassSuffix( String s ) { mClassSuffix= s; } private String mClassSuffix = ""; - + // not a tag attribute public void setLocale(Locale locale) { if (locale != null) mLocale = locale; } private Locale mLocale = Locale.getDefault(); - + // not a tag attribute /* private TimeZone mTimeZone = TimeZone.getDefault(); @@ -91,9 +91,9 @@ private TimeZone getTimeZone() return mTimeZone; } */ - + private String[] mDayNames = null; - + public CalendarTag() { /* * Empty constructor. @@ -103,7 +103,7 @@ public CalendarTag() { * doStartTag() method. */ } - + //------------------------------------------------------------------------ /** * Write to a PrintWriter so that tag may be used from Velocity @@ -112,17 +112,17 @@ public int doStartTag( PrintWriter pw ) throws JspException { try { // build week day names this.buildDayNames(); - + Date day=null; // day to be displayed Calendar dayCal; // set to day to be displayed Calendar cal; // for iterating through days of month Calendar todayCal; // for iterating through days of month CalendarModel model; // the calendar model - + // --------------------------------- // --- initialize date variables --- // --------------------------------- - + // check for parameter map and target url StringTokenizer toker = new StringTokenizer(mModelName,"."); String tok1 = toker.nextToken(); @@ -133,42 +133,42 @@ public int doStartTag( PrintWriter pw ) throws JspException { } else { model = (CalendarModel)pageContext.findAttribute( mModelName ); } - + // no model specified, nothing to generate if (model == null) { return SKIP_BODY; } - + day = model.getDay(); - + // ceate object to represent today todayCal = model.getCalendar(); todayCal.setTime( new Date() ); - + // formatter Month-Year title of calendar SimpleDateFormat formatTitle = new SimpleDateFormat("MMMM yyyy", mLocale); - + HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); - + // get Resource Bundle ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources", mLocale); - + // go back to first day in month cal = model.getCalendar(); day = DateUtil.getNoonOfDay(day, cal); cal.set( Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH) ); - + // Go back to first day of week before that (Sunday in US, Monday in France, e.g.) // in the calendar while ( cal.get( Calendar.DAY_OF_WEEK ) != cal.getFirstDayOfWeek() ) { cal.add( Calendar.DATE, -1 ); } - + // create table of 5 weeks, 7 days per row dayCal = model.getCalendar(); dayCal.setTime( day ); - + // ------------------------- // --- draw the calendar --- // ------------------------- @@ -192,7 +192,7 @@ public int doStartTag( PrintWriter pw ) throws JspException { + "\" class=\"hCalendarNavBar\">»"); } pw.print(""); - + // emit the HTML calendar for ( int w=-1; w<6; w++ ) { pw.print("
    "); @@ -205,12 +205,12 @@ public int doStartTag( PrintWriter pw ) throws JspException { pw.print(""); continue; } - + // determine URL for this calendar day Date tddate = cal.getTime(); String url = model.computeUrl(tddate, false, false); String content = model.getContent( tddate ); - + if // day is in calendar month ((cal.get(Calendar.MONTH) == dayCal.get(Calendar.MONTH)) && (cal.get(Calendar.YEAR) == dayCal.get(Calendar.YEAR))) { @@ -229,25 +229,25 @@ public int doStartTag( PrintWriter pw ) throws JspException { { printDayNotInMonth(pw, cal); } - + // increment calendar by one day cal.add( Calendar.DATE, 1 ); } pw.print(""); } - + pw.print(""); pw.print(""); pw.print(""); - + pw.print("
    "); - + pw.print("" +bundle.getString("calendar.today") +""); - + pw.print("
    "); } catch (Exception e) { pw.print(""); @@ -257,14 +257,14 @@ public int doStartTag( PrintWriter pw ) throws JspException { } return Tag.SKIP_BODY; } - + private void printDayNotInMonth(PrintWriter pw, Calendar cal) { pw.print(""); //pw.print(cal.get(Calendar.DAY_OF_MONTH)); pw.print(" "); pw.print(""); } - + private void printDayInThisMonth(PrintWriter pw, Calendar cal, String url, String content) { if ( content!=null ) { pw.print(""); } } - + private void printToday(PrintWriter pw, Calendar cal, String url, String content) { if ( content!=null ) { pw.print(""); } } - + /** * Helper method to build the names of the weekdays. This * used to take place in the CalendarTag constructor, @@ -331,8 +331,8 @@ private void buildDayNames() { dayNameCal.add(Calendar.DATE, 1); } } - - + + public String toString() { String ret = null; try { @@ -347,24 +347,24 @@ public String toString() { } return ret; } - + public String emit() { return toString(); } - + public int doStartTag() throws JspException { return doStartTag( new PrintWriter( pageContext.getOut(), true) ); } - - + + public int doEndTag() throws JspException { return doEndTag( new PrintWriter( pageContext.getOut(), true) ); } - + /** Default processing of the end tag returning EVAL_PAGE. */ public int doEndTag( PrintWriter pw ) throws JspException { return EVAL_PAGE; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/WeblogCalendarModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/WeblogCalendarModel.java index 2dba5db3e9..b4680ca324 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/WeblogCalendarModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/tags/calendar/WeblogCalendarModel.java @@ -44,9 +44,9 @@ * Calendar model for calendar intended for use on view-weblog page. */ public class WeblogCalendarModel implements CalendarModel { - + private static Log log = LogFactory.getLog(WeblogCalendarModel.class); - + protected Map monthMap; protected Date day; protected String cat = null; @@ -55,64 +55,64 @@ public class WeblogCalendarModel implements CalendarModel { protected Calendar calendar = null; protected Weblog weblog = null; protected Date prevMonth = null; // prev month or null if none - protected Date nextMonth = null; // next month or null if none + protected Date nextMonth = null; // next month or null if none protected WeblogPageRequest pageRequest = null; - - + + public WeblogCalendarModel(WeblogPageRequest pRequest, String catArgument) { - + this.pageRequest = pRequest; try { - this.weblog = pageRequest.getWeblog(); + this.weblog = pageRequest.getWeblog(); if(weblog == null) { throw new WebloggerException("unable to lookup weblog: "+ pageRequest.getWeblogHandle()); } - pageLink = pageRequest.getWeblogPageName(); + pageLink = pageRequest.getWeblogPageName(); // day = DateUtil.parseWeblogURLDateString(pageRequest.getWeblogDate(), // weblog.getTimeZoneInstance(), weblog.getLocaleInstance()); day = parseWeblogURLDateString(pageRequest.getWeblogDate(), weblog.getTimeZoneInstance(), weblog.getLocaleInstance()); locale = pageRequest.getLocale(); - + // Category method argument overrides category from URL if (catArgument != null) { cat = catArgument; } else if (pageRequest.getWeblogCategoryName() != null) { cat = pageRequest.getWeblogCategoryName(); } - + initDay(day); } catch (Exception e) { // some kind of error parsing the request or looking up weblog log.debug("ERROR: initializing calendar", e); } - + } - - + + protected void initDay(Date month) { calendar = Calendar.getInstance( weblog.getTimeZoneInstance(), weblog.getLocaleInstance()); - + Calendar cal = (Calendar)calendar.clone(); Date startDate = DateUtil.getStartOfMonth(month,cal); Date endDate = DateUtil.getEndOfMonth(month,cal); - + // Determine previous non-empty month // Get entries before startDate, using category restriction limit 1 // Use entry's date as previous month try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); List prevEntries = mgr.getWeblogEntries( - + weblog, // website null, // user null, // startDate // since we need an entry.pubTimeendDate, but the method use >= new Date(endDate.getTime()+1), // startDate - null, // endDate + null, // endDate cat, // cat null,WeblogEntry.PUBLISHED, // status null, // text @@ -153,23 +153,23 @@ protected void initDay(Date month) { } } catch (WebloggerException e) { log.error("ERROR determining next non-empty month"); - } - + } + // Fix for ROL-840 Don't include future entries Date now = new Date(); if (endDate.after(now)) { endDate = now; nextMonth = null; } - + loadWeblogEntries(startDate, endDate, cat); } - + protected void loadWeblogEntries(Date startDate, Date endDate, String catName) { try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); monthMap = mgr.getWeblogEntryStringMap( - + weblog, // website startDate, // startDate endDate, // endDate @@ -182,18 +182,18 @@ protected void loadWeblogEntries(Date startDate, Date endDate, String catName) { monthMap = new HashMap(); } } - + public void setDay(String month) throws Exception { SimpleDateFormat fmt = DateUtil.get8charDateFormat(); fmt.setCalendar(getCalendar()); ParsePosition pos = new ParsePosition(0); initDay( fmt.parse( month, pos ) ); } - + public Date getDay() { return (Date)day.clone(); } - + public String getParameterValue(Date day) { return (String)monthMap.get( day ); } @@ -204,8 +204,8 @@ public static String format8chars(Date date, Calendar cal) { format.setCalendar(cal); return DateUtil.format(date,format); } - - + + // convenience method returns 6 char month stamp YYYYMM public static String format6chars(Date date, Calendar cal) { SimpleDateFormat format = DateUtil.get6charDateFormat(); @@ -217,10 +217,10 @@ public static String format6chars(Date date, Calendar cal) { * Parse data as either 6-char or 8-char format. */ public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Locale locale) { - + Date ret = new Date(); Calendar cal = Calendar.getInstance(tz,locale); - + if (dateString != null && dateString.length()==8 && StringUtils.isNumeric(dateString) ) { @@ -228,7 +228,7 @@ public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Loca char8DateFormat.setCalendar(cal); ParsePosition pos = new ParsePosition(0); ret = char8DateFormat.parse(dateString, pos); - + // make sure the requested date is not in the future // Date today = null; // Calendar todayCal = Calendar.getInstance(); @@ -240,7 +240,7 @@ public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Loca if(ret.after(today)) { ret = today; } - + } else if(dateString != null && dateString.length()==6 && StringUtils.isNumeric(dateString)) { @@ -248,7 +248,7 @@ public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Loca char6DateFormat.setCalendar(cal); ParsePosition pos = new ParsePosition(0); ret = char6DateFormat.parse(dateString, pos); - + // make sure the requested date is not in the future // Calendar todayCal = Calendar.getInstance(); // todayCal = Calendar.getInstance(tz, locale); @@ -259,10 +259,10 @@ public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Loca ret = today; } } - + return ret; } - + /** * Create URL for use on view-weblog page * @param day Day for URL or null if no entries on that day @@ -292,15 +292,15 @@ else if (dateString == null && !monthURL) { } return url; } - + public String getContent(Date day) { return null; } - + public Calendar getCalendar() { return (Calendar)calendar.clone(); } - + public Date getNextMonth() { return nextMonth; } @@ -308,7 +308,7 @@ public Date getNextMonth() { public Date getPrevMonth() { return prevMonth; } - + public String computeNextMonthUrl() { return computeUrl(nextMonth, true, true); } @@ -316,7 +316,7 @@ public String computeNextMonthUrl() { public String computePrevMonthUrl() { return computeUrl(prevMonth, true, true); } - + public String computeTodayMonthUrl() { String url; if (pageLink == null) { // create default URL @@ -326,5 +326,5 @@ public String computeTodayMonthUrl() { } return url; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/Menu.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/Menu.java index 9935268f6f..894f0ed00e 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/Menu.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/Menu.java @@ -26,15 +26,15 @@ * A Menu of MenuTab objects. */ public class Menu { - + private List tabs = new ArrayList(); - - + + public void addTab(MenuTab tab) { this.tabs.add(tab); } - - + + public List getTabs() { return tabs; } @@ -42,5 +42,5 @@ public List getTabs() { public void setTabs(List menus) { this.tabs = menus; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuHelper.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuHelper.java index dbe14624d0..4ecd178fff 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuHelper.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuHelper.java @@ -45,12 +45,12 @@ * A helper class for dealing with UI menus. */ public class MenuHelper { - + private static Log log = LogFactory.getLog(MenuHelper.class); - + private static Hashtable menus = new Hashtable(); - - + + static { try { // parse menus and cache so we can efficiently reuse them @@ -59,27 +59,27 @@ public class MenuHelper { MenuHelper.class.getResourceAsStream( "/org/apache/roller/weblogger/ui/struts2/editor/editor-menu.xml")); menus.put("editor", editorMenu); - + ParsedMenu adminMenu = unmarshall( MenuHelper.class.getResourceAsStream( "/org/apache/roller/weblogger/ui/struts2/admin/admin-menu.xml")); menus.put("admin", adminMenu); - + } catch (Exception ex) { log.error("Error parsing menu configs", ex); } } - - + + public static Menu getMenu(String menuId, String currentAction, User user, Weblog weblog) { - + if(menuId == null) { return null; } - + Menu menu = null; - + // do we know the specified menu config? ParsedMenu menuConfig = (ParsedMenu) menus.get(menuId); if(menuConfig != null) { @@ -89,27 +89,27 @@ public static Menu getMenu(String menuId, String currentAction, log.debug("ERROR: fethcing user roles", ex); } } - + return menu; } - - - private static Menu buildMenu(ParsedMenu menuConfig, String currentAction, + + + private static Menu buildMenu(ParsedMenu menuConfig, String currentAction, User user, Weblog weblog) throws WebloggerException { - + log.debug("creating menu for action - "+currentAction); - + Menu tabMenu = new Menu(); UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - + // iterate over tabs from parsed config ParsedTab configTab = null; Iterator tabsIter = menuConfig.getTabs().iterator(); while (tabsIter.hasNext()) { configTab = (ParsedTab) tabsIter.next(); - + log.debug("config tab = "+configTab.getName()); - + // does this tab have an enabledProperty? boolean includeTab = true; if(configTab.getEnabledProperty() != null) { @@ -117,13 +117,13 @@ private static Menu buildMenu(ParsedMenu menuConfig, String currentAction, } else if(configTab.getDisabledProperty() != null) { includeTab = ! getBooleanProperty(configTab.getDisabledProperty()); } - + if (includeTab) { // user roles check if (configTab.getGlobalPermissionActions() != null && !configTab.getGlobalPermissionActions().isEmpty()) { try { - GlobalPermission perm = + GlobalPermission perm = new GlobalPermission(configTab.getGlobalPermissionActions()); if (!umgr.checkPermission(perm, user)) { includeTab = false; @@ -134,52 +134,52 @@ private static Menu buildMenu(ParsedMenu menuConfig, String currentAction, } } } - + if (includeTab) { // weblog permissions check - if (configTab.getWeblogPermissionActions() != null + if (configTab.getWeblogPermissionActions() != null && !configTab.getWeblogPermissionActions().isEmpty()) { - WeblogPermission perm = + WeblogPermission perm = new WeblogPermission(weblog, configTab.getWeblogPermissionActions()); includeTab = umgr.checkPermission(perm, user); } } - + if (includeTab) { log.debug("tab allowed - "+configTab.getName()); - + // all checks passed, tab should be included MenuTab tab = new MenuTab(); tab.setKey(configTab.getName()); - + // setup tab items boolean firstItem = true; ParsedTabItem configTabItem = null; Iterator itemsIter = configTab.getTabItems().iterator(); while (itemsIter.hasNext()) { configTabItem = (ParsedTabItem) itemsIter.next(); - + log.debug("config tab item = "+configTabItem.getName()); - + boolean includeItem = true; if (configTabItem.getEnabledProperty() != null) { includeItem = getBooleanProperty(configTabItem.getEnabledProperty()); } else if (configTabItem.getDisabledProperty() != null) { includeItem = ! getBooleanProperty(configTabItem.getDisabledProperty()); } - + if (includeItem) { // user roles check if (configTabItem.getGlobalPermissionActions() != null && !configTabItem.getGlobalPermissionActions().isEmpty()) { - GlobalPermission perm = + GlobalPermission perm = new GlobalPermission(configTabItem.getGlobalPermissionActions()); if (!umgr.checkPermission(perm, user)) { includeItem = false; } } } - + if (includeItem) { // weblog permissions check if (configTabItem.getWeblogPermissionActions() != null @@ -188,40 +188,40 @@ private static Menu buildMenu(ParsedMenu menuConfig, String currentAction, includeItem = umgr.checkPermission(perm, user); } } - + if (includeItem) { log.debug("tab item allowed - "+configTabItem.getName()); - + // all checks passed, item should be included MenuTabItem tabItem = new MenuTabItem(); tabItem.setKey(configTabItem.getName()); tabItem.setAction(configTabItem.getAction()); - + // is this the selected item? if (isSelected(currentAction, configTabItem)) { tabItem.setSelected(true); tab.setSelected(true); } - + // the url for the tab is the url of the first item of the tab if (firstItem) { tab.setAction(tabItem.getAction()); firstItem = false; } - + // add the item tab.addItem(tabItem); } } - + // add the tab tabMenu.addTab(tab); } } - + return tabMenu; - } - + } + /** Check enabled property, prefers runtime properties */ private static boolean getBooleanProperty(String propertyName) { if (WebloggerRuntimeConfig.getProperty(propertyName) != null) { @@ -229,13 +229,13 @@ private static boolean getBooleanProperty(String propertyName) { } return WebloggerConfig.getBooleanProperty(propertyName); } - + private static boolean isSelected(String currentAction, ParsedTabItem tabItem) { - + if (currentAction.equals(tabItem.getAction())) { return true; } - + // an item is also considered selected if it's subforwards are the current action String[] subActions = tabItem.getSubActions(); if (subActions != null && subActions.length > 0) { @@ -245,26 +245,26 @@ private static boolean isSelected(String currentAction, ParsedTabItem tabItem) { } } } - + return false; } - - + + /** * Unmarshall the given input stream into our defined * set of Java objects. **/ - private static ParsedMenu unmarshall(InputStream instream) + private static ParsedMenu unmarshall(InputStream instream) throws IOException, JDOMException { - + if (instream == null) throw new IOException("InputStream is null!"); - + ParsedMenu config = new ParsedMenu(); - + SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(instream); - + Element root = doc.getRootElement(); List parsedMenus = root.getChildren("menu"); Iterator iter = parsedMenus.iterator(); @@ -272,15 +272,15 @@ private static ParsedMenu unmarshall(InputStream instream) Element e = (Element) iter.next(); config.addTab(elementToParsedTab(e)); } - + return config; } - - + + private static ParsedTab elementToParsedTab(Element element) { - + ParsedTab tab = new ParsedTab(); - + tab.setName(element.getAttributeValue("name")); if (element.getAttributeValue("weblogPerms") != null) { tab.setWeblogPermissionActions(Utilities.stringToStringList(element.getAttributeValue("weblogPerms"),",")); @@ -290,30 +290,30 @@ private static ParsedTab elementToParsedTab(Element element) { } tab.setEnabledProperty(element.getAttributeValue("enabledProperty")); tab.setDisabledProperty(element.getAttributeValue("disabledProperty")); - + List menuItems = element.getChildren("menu-item"); Iterator iter = menuItems.iterator(); while (iter.hasNext()) { Element e = (Element) iter.next(); tab.addItem(elementToParsedTabItem(e)); } - + return tab; } - - + + private static ParsedTabItem elementToParsedTabItem(Element element) { - + ParsedTabItem tabItem = new ParsedTabItem(); - + tabItem.setName(element.getAttributeValue("name")); tabItem.setAction(element.getAttributeValue("action")); - + String subActions = element.getAttributeValue("subactions"); if (subActions != null) { tabItem.setSubActions(subActions.split(",")); } - + if (element.getAttributeValue("weblogPerms") != null) { tabItem.setWeblogPermissionActions(Utilities.stringToStringList(element.getAttributeValue("weblogPerms"), ",")); } @@ -322,9 +322,9 @@ private static ParsedTabItem elementToParsedTabItem(Element element) { } tabItem.setEnabledProperty(element.getAttributeValue("enabledProperty")); tabItem.setDisabledProperty(element.getAttributeValue("disabledProperty")); - + return tabItem; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTab.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTab.java index 140410f8f8..d7085b6814 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTab.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTab.java @@ -26,18 +26,18 @@ * Tab in a Menu. */ public class MenuTab { - + private String key = null; private String action = null; private boolean selected = false; private List items = new ArrayList(); - - + + public void addItem(MenuTabItem item) { this.items.add(item); } - - + + public String getKey() { return key; } @@ -61,7 +61,7 @@ public boolean isSelected() { public void setSelected(boolean selected) { this.selected = selected; } - + public List getItems() { return items; } @@ -69,5 +69,5 @@ public List getItems() { public void setItems(List items) { this.items = items; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTabItem.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTabItem.java index bcca553fab..663d166e8e 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTabItem.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/MenuTabItem.java @@ -23,12 +23,12 @@ * Items in a Tab. */ public class MenuTabItem { - + private String key = null; private String action = null; private boolean selected = false; - - + + public String getKey() { return key; } @@ -52,5 +52,5 @@ public boolean isSelected() { public void setSelected(boolean selected) { this.selected = selected; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedMenu.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedMenu.java index c565abc318..6b64b2757c 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedMenu.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedMenu.java @@ -26,15 +26,15 @@ * A parsed xml defined menu. */ public class ParsedMenu { - + private List tabs = new ArrayList(); - - + + public void addTab(ParsedTab tab) { this.tabs.add(tab); } - - + + public List getTabs() { return tabs; } @@ -42,5 +42,5 @@ public List getTabs() { public void setTabs(List tabs) { this.tabs = tabs; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTab.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTab.java index 812d1229ca..314fab4ba2 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTab.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTab.java @@ -26,21 +26,21 @@ * A parsed "tab" from an xml defined menu config. */ public class ParsedTab { - + private String name = null; private List weblogPermissionActions = null; private List globalPermissionActions = null; private String enabledProperty = null; private String disabledProperty = null; - + private List tabItems = new ArrayList(); - - + + public void addItem(ParsedTabItem item) { this.tabItems.add(item); } - - + + public String getName() { return name; } @@ -88,5 +88,5 @@ public String getDisabledProperty() { public void setDisabledProperty(String disabledProperty) { this.disabledProperty = disabledProperty; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTabItem.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTabItem.java index 4e5e86ab1e..8ba425c969 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTabItem.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/core/util/menu/ParsedTabItem.java @@ -25,7 +25,7 @@ * A parsed "tab-item" from an xml defined menu config. */ public class ParsedTabItem { - + private String name = null; private String action = null; private String[] subActions = null; @@ -33,8 +33,8 @@ public class ParsedTabItem { private List globalPermissionActions = null; private String enabledProperty = null; private String disabledProperty = null; - - + + public String getName() { return name; } @@ -89,6 +89,6 @@ public String getDisabledProperty() { public void setDisabledProperty(String disabledProperty) { this.disabledProperty = disabledProperty; - } + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/Renderer.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/Renderer.java index c385afb020..4461ed6336 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/Renderer.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/Renderer.java @@ -26,8 +26,8 @@ * Renders content to writer based on values in a map. */ public interface Renderer { - - + + /** * Render the content for this Renderer to the given Writer using * the given set of model objects. @@ -35,5 +35,5 @@ public interface Renderer { * Throws an exception if there is a problem during rendering. */ public void render(Map model, Writer writer) throws RenderingException; - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererFactory.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererFactory.java index 5e7bc9137a..97c3ef7c14 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererFactory.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererFactory.java @@ -28,8 +28,8 @@ * what Renderer object should be used to render a given resource. */ public interface RendererFactory { - - + + /** * Get a Renderer that will handle the given Template. * If a RendererFactory does not have a Renderer which can handle the @@ -41,5 +41,5 @@ public interface RendererFactory { * report any relevant exceptions itself. */ public Renderer getRenderer(Template template); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererManager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererManager.java index 1d6bab74a3..3be964bdf7 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererManager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RendererManager.java @@ -28,29 +28,29 @@ /** - * Returns Renderer for Template via configured RendererFactories. - * - * The purpose of the RendererManager is to provide a level of abstraction + * Returns Renderer for Template via configured RendererFactories. + * + * The purpose of the RendererManager is to provide a level of abstraction * between classes that are rendering content and the implementations of the * rendering technology. This allows us to provide easily pluggable rendering * implementations. */ public class RendererManager { - + private static Log log = LogFactory.getLog(RendererManager.class); - + // a set of all renderer factories we are consulting private static Set rendererFactories = new HashSet(); - - + + static { // lookup set of renderer factories we are going to use String rollerFactories = WebloggerConfig.getProperty("rendering.rollerRendererFactories"); String userFactories = WebloggerConfig.getProperty("rendering.userRendererFactories"); - + // instantiate user defined renderer factory classes if(userFactories != null && userFactories.trim().length() > 0) { - + RendererFactory rendererFactory = null; String[] uFactories = userFactories.split(","); for(int i=0; i < uFactories.length; i++) { @@ -66,10 +66,10 @@ public class RendererManager { } } } - + // instantiate roller standard renderer factory classes if(rollerFactories != null && rollerFactories.trim().length() > 0) { - + RendererFactory rendererFactory = null; String[] rFactories = rollerFactories.split(","); for(int i=0; i < rFactories.length; i++) { @@ -85,21 +85,21 @@ public class RendererManager { } } } - + if(rendererFactories.size() < 1) { // hmm ... failed to load any renderer factories? log.warn("Failed to load any renderer factories. "+ "Rendering probably won't function as you expect."); } - + log.info("Renderer Manager Initialized."); } - - + + // this class is non-instantiable private RendererManager() {} - - + + /** * Find the appropriate Renderer for the given content. * @@ -107,24 +107,24 @@ private RendererManager() {} * instance and tries to find a Renderer for the content. If no Renderer * can be found then we throw an exception. */ - public static Renderer getRenderer(Template template) + public static Renderer getRenderer(Template template) throws RenderingException { - + Renderer renderer = null; - + // iterate over our renderer factories and see if one of them // wants to handle this content Iterator factories = rendererFactories.iterator(); while(factories.hasNext()) { renderer = ((RendererFactory)factories.next()).getRenderer(template); - + if(renderer != null) { return renderer; } } - + throw new RenderingException("No renderer found for template "+ template.getId()+"!"); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RenderingException.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RenderingException.java index bbf956a924..9007196b8d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RenderingException.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RenderingException.java @@ -25,17 +25,17 @@ * A generic Roller rendering exception. */ public class RenderingException extends WebloggerException { - + public RenderingException(String s) { super(s); } - + public RenderingException(String s, Throwable t) { super(s, t); } - + public RenderingException(Throwable t) { super(t); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RequestMapper.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RequestMapper.java index 1714f18039..209bb2c3eb 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RequestMapper.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/RequestMapper.java @@ -11,16 +11,16 @@ * Interface for object that can handle requests, return true if handled. */ public interface RequestMapper { - + /** * Handle an incoming request. * * RequestMappers are not required to handle all requests and are instead * encouraged to inspect the request and only take action when it - * wants to. If action is taken then the RequestMapper should return a + * wants to. If action is taken then the RequestMapper should return a * boolean "true" value indicating that no further action is required. */ public boolean handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException; - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/WeblogRequestMapper.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/WeblogRequestMapper.java index dcd5b3854f..7f120a27f5 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/WeblogRequestMapper.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/WeblogRequestMapper.java @@ -44,78 +44,78 @@ * TODO: we should try and make this class easier to extend and build upon */ public class WeblogRequestMapper implements RequestMapper { - + private static Log log = LogFactory.getLog(WeblogRequestMapper.class); - + private static final String PAGE_SERVLET = "/roller-ui/rendering/page"; private static final String FEED_SERVLET = "/roller-ui/rendering/feed"; private static final String RESOURCE_SERVLET = "/roller-ui/rendering/resources"; private static final String MEDIA_SERVLET = "/roller-ui/rendering/media-resources"; private static final String SEARCH_SERVLET = "/roller-ui/rendering/search"; private static final String RSD_SERVLET = "/roller-ui/rendering/rsd"; - + private static final String COMMENT_SERVLET = "/roller-ui/rendering/comment"; private static final String TRACKBACK_SERVLET = "/roller-ui/rendering/trackback"; - - + + // url patterns that are not allowed to be considered weblog handles Set restricted = null; - - + + public WeblogRequestMapper() { - + this.restricted = new HashSet(); - + // build roller restricted list - String restrictList = + String restrictList = WebloggerConfig.getProperty("rendering.weblogMapper.rollerProtectedUrls"); if(restrictList != null && restrictList.trim().length() > 0) { String[] restrict = restrictList.split(","); this.restricted.addAll(Arrays.asList(restrict)); } - + // add user restricted list - restrictList = + restrictList = WebloggerConfig.getProperty("rendering.weblogMapper.userProtectedUrls"); if(restrictList != null && restrictList.trim().length() > 0) { String[] restrict = restrictList.split(","); this.restricted.addAll(Arrays.asList(restrict)); } } - - + + public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + // kinda silly, but we need to keep track of whether or not the url had // a trailing slash so that we can act accordingly boolean trailingSlash = false; - + String weblogHandle = null; String weblogLocale = null; String weblogRequestContext = null; String weblogRequestData = null; - + log.debug("evaluating ["+request.getRequestURI()+"]"); - + // figure out potential weblog handle String servlet = request.getRequestURI(); String pathInfo = null; - + if(servlet != null && servlet.trim().length() > 1) { - + if(request.getContextPath() != null) servlet = servlet.substring(request.getContextPath().length()); - + // strip off the leading slash servlet = servlet.substring(1); - + // strip off trailing slash if needed if(servlet.endsWith("/")) { servlet = servlet.substring(0, servlet.length() - 1); trailingSlash = true; } - + if(servlet.indexOf("/") != -1) { weblogHandle = servlet.substring(0, servlet.indexOf("/")); pathInfo = servlet.substring(servlet.indexOf("/")+1); @@ -123,9 +123,9 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res weblogHandle = servlet; } } - + log.debug("potential weblog handle = "+weblogHandle); - + // check if it's a valid weblog handle if(restricted.contains(weblogHandle) || !this.isWeblog(weblogHandle)) { log.debug("SKIPPED "+weblogHandle); @@ -141,64 +141,64 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res return false; } } - + log.debug("WEBLOG_URL "+request.getServletPath()); - + // parse the rest of the url and build forward url if(pathInfo != null) { - + // parse the next portion of the url // we expect [locale/]// String[] urlPath = pathInfo.split("/", 3); - + // if we have a locale, deal with it if(this.isLocale(urlPath[0])) { weblogLocale = urlPath[0]; - + // no extra path info specified if(urlPath.length == 2) { weblogRequestContext = urlPath[1]; weblogRequestData = null; - + // request contains extra path info } else if(urlPath.length == 3) { weblogRequestContext = urlPath[1]; weblogRequestData = urlPath[2]; } - + // otherwise locale is empty } else { weblogLocale = null; weblogRequestContext = urlPath[0]; - + // last part of request is extra path info if(urlPath.length == 2) { weblogRequestData = urlPath[1]; - + // if we didn't have a locale then we have split too much // so we reassemble the last 2 path elements together } else if(urlPath.length == 3) { weblogRequestData = urlPath[1] + "/" + urlPath[2]; } } - + } - + // special handling for trailing slash issue // we need this because by http standards the urls /foo and /foo/ are // supposed to be considered different, so we must enforce that if(weblogRequestContext == null && !trailingSlash) { - // this means someone referred to a weblog index page with the + // this means someone referred to a weblog index page with the // shortest form of url / or // and we need // to do a redirect to // or /// String redirectUrl = request.getRequestURI() + "/"; if(request.getQueryString() != null) { redirectUrl += "?"+request.getQueryString(); } - + response.sendRedirect(redirectUrl); return true; - + } else if(weblogRequestContext != null && "tags".equals(weblogRequestContext)) { // tags section can have an index page at //tags/ and @@ -215,26 +215,26 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } - + // calculate forward url String forwardUrl = calculateForwardUrl(request, weblogHandle, weblogLocale, weblogRequestContext, weblogRequestData); - + // if we don't have a forward url then the request was invalid somehow if(forwardUrl == null) { return false; } - + // dispatch to forward url log.debug("forwarding to "+forwardUrl); RequestDispatcher dispatch = request.getRequestDispatcher(forwardUrl); dispatch.forward(request, response); - + // we dealt with this request ourselves, so return "true" return true; } - + /** * Convenience method for caculating the servlet forward url given a set * of information to make the decision with. @@ -244,18 +244,18 @@ public boolean handleRequest(HttpServletRequest request, HttpServletResponse res private String calculateForwardUrl(HttpServletRequest request, String handle, String locale, String context, String data) { - + log.debug(handle+","+locale+","+context+","+data); - + StringBuilder forwardUrl = new StringBuilder(); - + // POST urls, like comment and trackback servlets if("POST".equals(request.getMethod())) { // posting to permalink, this means comment or trackback if(context.equals("entry")) { // trackback requests are required to have an "excerpt" param if(request.getParameter("excerpt") != null) { - + forwardUrl.append(TRACKBACK_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); @@ -269,10 +269,10 @@ private String calculateForwardUrl(HttpServletRequest request, forwardUrl.append("/"); forwardUrl.append(data); } - + // comment requests are required to have a "content" param } else if(request.getParameter("content") != null) { - + forwardUrl.append(COMMENT_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); @@ -287,16 +287,16 @@ private String calculateForwardUrl(HttpServletRequest request, forwardUrl.append(data); } } - + } else { // someone posting data where they aren't supposed to return null; } - + } else { // no context means weblog homepage if(context == null) { - + forwardUrl.append(PAGE_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); @@ -304,12 +304,12 @@ private String calculateForwardUrl(HttpServletRequest request, forwardUrl.append("/"); forwardUrl.append(locale); } - + // requests handled by PageServlet } else if(context.equals("page") || context.equals("entry") || context.equals("date") || context.equals("category") || context.equals("tags")) { - + forwardUrl.append(PAGE_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); @@ -323,10 +323,10 @@ private String calculateForwardUrl(HttpServletRequest request, forwardUrl.append("/"); forwardUrl.append(data); } - + // requests handled by FeedServlet } else if(context.equals("feed")) { - + forwardUrl.append(FEED_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); @@ -338,7 +338,7 @@ private String calculateForwardUrl(HttpServletRequest request, forwardUrl.append("/"); forwardUrl.append(data); } - + // requests handled by ResourceServlet } else if(context.equals("resource")) { @@ -363,30 +363,30 @@ private String calculateForwardUrl(HttpServletRequest request, // requests handled by SearchServlet } else if(context.equals("search")) { - + forwardUrl.append(SEARCH_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); - + // requests handled by RSDServlet } else if(context.equals("rsd")) { - + forwardUrl.append(RSD_SERVLET); forwardUrl.append("/"); forwardUrl.append(handle); - + // unsupported url } else { return null; } } - + log.debug("FORWARD_URL "+forwardUrl.toString()); - + return forwardUrl.toString(); } - - + + /** * convenience method which determines if the given string is a valid * weblog handle. @@ -394,54 +394,54 @@ private String calculateForwardUrl(HttpServletRequest request, * TODO 3.0: some kind of caching */ private boolean isWeblog(String potentialHandle) { - + log.debug("checking weblog handle "+potentialHandle); - + boolean isWeblog = false; - + try { Weblog weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(potentialHandle); - + if(weblog != null) { isWeblog = true; } } catch(Exception ex) { // doesn't really matter to us why it's not a valid website } - + return isWeblog; } - - + + /** * Convenience method which determines if the given string is a valid * locale string. */ private boolean isLocale(String potentialLocale) { - + boolean isLocale = false; - + // we only support 2 or 5 character locale strings, so check that first - if(potentialLocale != null && + if(potentialLocale != null && (potentialLocale.length() == 2 || potentialLocale.length() == 5)) { - + // now make sure that the format is proper ... e.g. "en_US" // we are not going to be picky about capitalization String[] langCountry = potentialLocale.split("_"); - if(langCountry.length == 1 && + if(langCountry.length == 1 && langCountry[0] != null && langCountry[0].length() == 2) { isLocale = true; - - } else if(langCountry.length == 2 && - langCountry[0] != null && langCountry[0].length() == 2 && + + } else if(langCountry.length == 2 && + langCountry[0] != null && langCountry[0].length() == 2 && langCountry[1] != null && langCountry[1].length() == 2) { - + isLocale = true; } } - + return isLocale; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/filters/RequestMappingFilter.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/filters/RequestMappingFilter.java index f78a8f2732..994d527151 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/filters/RequestMappingFilter.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/filters/RequestMappingFilter.java @@ -44,22 +44,22 @@ * @web.filter name="RequestMappingFilter" */ public class RequestMappingFilter implements Filter { - + private static Log log = LogFactory.getLog(RequestMappingFilter.class); - + // list of RequestMappers that want to inspect the request private final List requestMappers = new ArrayList(); - - + + public void init(FilterConfig filterConfig) { - + // lookup set of request mappers we are going to use String rollerMappers = WebloggerConfig.getProperty("rendering.rollerRequestMappers"); String userMappers = WebloggerConfig.getProperty("rendering.userRequestMappers"); - + // instantiate user defined request mapper classes if(userMappers != null && userMappers.trim().length() > 0) { - + RequestMapper requestMapper = null; String[] uMappers = userMappers.split(","); for(int i=0; i < uMappers.length; i++) { @@ -75,10 +75,10 @@ public void init(FilterConfig filterConfig) { } } } - + // instantiate roller standard request mapper classes if(rollerMappers != null && rollerMappers.trim().length() > 0) { - + RequestMapper requestMapper = null; String[] rMappers = rollerMappers.split(","); for(int i=0; i < rMappers.length; i++) { @@ -94,37 +94,37 @@ public void init(FilterConfig filterConfig) { } } } - + if(requestMappers.size() < 1) { // hmm ... failed to load any request mappers? log.warn("Failed to load any request mappers. "+ "Weblog urls probably won't function as you expect."); } - + log.info("Request mapping filter initialized, "+requestMappers.size()+ " mappers configured."); } - - + + /** * Inspect incoming urls and see if they should be routed. */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - + HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; - + log.debug("entering"); - + // give each mapper a chance to handle the request RequestMapper mapper = null; Iterator mappersIT = this.requestMappers.iterator(); while(mappersIT.hasNext()) { mapper = (RequestMapper) mappersIT.next(); - + log.debug("trying mapper "+mapper.getClass().getName()); - + boolean wasHandled = mapper.handleRequest(request, response); if(wasHandled) { // if mapper has handled the request then we are done @@ -133,16 +133,16 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) return; } } - + log.debug("request not mapped"); - + // nobody handled the request, so let it continue as usual chain.doFilter(request, response); - + log.debug("exiting"); } - - + + public void destroy() {} - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/CalendarModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/CalendarModel.java index d78c7c887b..4a1a2e67e6 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/CalendarModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/CalendarModel.java @@ -34,35 +34,35 @@ /** * Model which provides functionality for displaying weblog calendar. - * + * * Implemented by calling hybrid JSP tag. */ public class CalendarModel implements Model { - + private static Log log = LogFactory.getLog(CalendarModel.class); - + private PageContext pageContext = null; private WeblogPageRequest pageRequest = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "calendarModel"; } - - + + /** Init page model based on request */ public void init(Map initData) throws WebloggerException { - + // extract page context this.pageContext = (PageContext) initData.get("pageContext"); - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // CalendarModel only works on page requests, so cast weblogRequest // into a WeblogPageRequest and if it fails then throw exception if(weblogRequest instanceof WeblogPageRequest) { @@ -72,21 +72,21 @@ public void init(Map initData) throws WebloggerException { " CalendarModel only supports page requests."); } } - - - public String showWeblogEntryCalendar(WeblogWrapper websiteWrapper, String catArgument) { + + + public String showWeblogEntryCalendar(WeblogWrapper websiteWrapper, String catArgument) { return showWeblogEntryCalendar(websiteWrapper, catArgument, false); } - - - public String showWeblogEntryCalendarBig(WeblogWrapper websiteWrapper, String catArgument) { + + + public String showWeblogEntryCalendarBig(WeblogWrapper websiteWrapper, String catArgument) { return showWeblogEntryCalendar(websiteWrapper, catArgument, true); } - - + + private String showWeblogEntryCalendar(WeblogWrapper websiteWrapper, String catArgument, boolean big) { - - if ("nil".equals(catArgument)) catArgument = null; + + if ("nil".equals(catArgument)) catArgument = null; String ret = null; try { org.apache.roller.weblogger.ui.core.tags.calendar.CalendarModel model = null; @@ -95,10 +95,10 @@ private String showWeblogEntryCalendar(WeblogWrapper websiteWrapper, String catA } else { model = new WeblogCalendarModel(pageRequest, catArgument); } - + // save model in JSP page context so CalendarTag can find it pageContext.setAttribute("calendarModel", model); - + CalendarTag calTag = new CalendarTag(); calTag.setPageContext(pageContext); calTag.setName("calendar"); @@ -113,5 +113,5 @@ private String showWeblogEntryCalendar(WeblogWrapper websiteWrapper, String catA } return ret; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ConfigModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ConfigModel.java index c03a40b04b..f7e36f6cf8 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ConfigModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ConfigModel.java @@ -30,116 +30,116 @@ * config properties. */ public class ConfigModel implements Model { - + private static Log log = LogFactory.getLog(ConfigModel.class); - - + + /** Template context name to be used for model */ public String getModelName() { return "config"; } - - + + /** Init model */ public void init(Map map) throws WebloggerException { // no-op } - - + + public String getSiteName() { return getProperty("site.name"); } - + public String getSiteShortName() { return getProperty("site.shortName"); } - + public String getSiteDescription() { return getProperty("site.description"); } - + public String getSiteEmail() { return getProperty("site.adminemail"); } - + public boolean getRegistrationEnabled() { return getBooleanProperty("users.registration.enabled"); } - + public String getRegistrationURL() { return getProperty("users.registration.url"); } - + public boolean getFeedHistoryEnabled() { return getBooleanProperty("site.newsfeeds.history.enabled"); } - + public int getFeedSize() { return getIntProperty("site.newsfeeds.defaultEntries"); } - + public int getFeedMaxSize() { return getIntProperty("site.newsfeeds.defaultEntries"); } - + public boolean getFeedStyle() { return getBooleanProperty("site.newsfeeds.styledFeeds"); } - + public boolean getCommentHtmlAllowed() { return getBooleanProperty("users.comments.htmlenabled"); } - + public boolean getCommentAutoFormat() { // this prop was removed in 4.0 return false; } - + public boolean getCommentEscapeHtml() { // replaced by new htmlallowed property in 4.0 return !getCommentHtmlAllowed(); } - + public boolean getCommentEmailNotify() { return getBooleanProperty("users.comments.emailnotify"); } - + public boolean getTrackbacksEnabled() { return getBooleanProperty("users.trackbacks.enabled"); } - - + + /** Get Roller version string */ public String getRollerVersion() { return WebloggerFactory.getWeblogger().getVersion(); } - - + + /** Get timestamp of Roller build */ public String getRollerBuildTimestamp() { return WebloggerFactory.getWeblogger().getBuildTime(); } - - + + /** Get username who created Roller build */ public String getRollerBuildUser() { return WebloggerFactory.getWeblogger().getBuildUser(); } - - + + private String getProperty(String name) { return WebloggerRuntimeConfig.getProperty(name); } - - + + private int getIntProperty(String name) { return WebloggerRuntimeConfig.getIntProperty(name); } - - + + private boolean getBooleanProperty(String name) { return WebloggerRuntimeConfig.getBooleanProperty(name); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/FeedModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/FeedModel.java index 65897ad6b0..169e81fc53 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/FeedModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/FeedModel.java @@ -42,24 +42,24 @@ * Model which provides information needed to render a feed. */ public class FeedModel implements Model { - - private static Log log = LogFactory.getLog(FeedModel.class); - + + private static Log log = LogFactory.getLog(FeedModel.class); + private static int DEFAULT_ENTRIES = WebloggerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries"); - + private WeblogFeedRequest feedRequest = null; private URLStrategy urlStrategy = null; private Weblog weblog = null; - - + + public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // PageModel only works on page requests, so cast weblogRequest // into a WeblogPageRequest and if it fails then throw exception if(weblogRequest instanceof WeblogFeedRequest) { @@ -68,101 +68,101 @@ public void init(Map initData) throws WebloggerException { throw new WebloggerException("weblogRequest is not a WeblogFeedRequest."+ " FeedModel only supports feed requests."); } - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + // extract weblog object weblog = feedRequest.getWeblog(); } - - + + /** Template context name to be used for model */ public String getModelName() { return "model"; } - - + + /** * Get the weblog locale used to render this page, null if no locale. */ public String getLocale() { return feedRequest.getLocale(); } - - + + /** * Get weblog being displayed. */ public WeblogWrapper getWeblog() { return WeblogWrapper.wrap(weblog, urlStrategy); } - - + + /** * Get category path or name specified by request. */ public boolean getExcerpts() { return feedRequest.isExcerpts(); } - - + + /** * Get category path or name specified by request. */ public String getCategoryPath() { return feedRequest.getWeblogCategoryName(); } - + /** - * Gets most recent entries limited by: weblog and category specified in + * Gets most recent entries limited by: weblog and category specified in * request plus the weblog.entryDisplayCount. */ public Pager getWeblogEntriesPager() { - return new FeedEntriesPager(feedRequest); + return new FeedEntriesPager(feedRequest); } - - + + /** - * Gets most recent comments limited by: weblog specified in request and + * Gets most recent comments limited by: weblog specified in request and * the weblog.entryDisplayCount. */ public Pager getCommentsPager() { return new FeedCommentsPager(feedRequest); - } - + } + /** - * Gets most recently uploaded media files limited by: weblog specified + * Gets most recently uploaded media files limited by: weblog specified * in request and the weblog.entryDisplayCount. */ public Pager getMediaFilesPager() { return new FeedFilesPager(feedRequest); - } - + } + /** * Returns the list of tags specified in the request /?tags=foo+bar * @return */ public List getTags() { return feedRequest.getTags(); - } + } public class FeedEntriesPager extends WeblogEntriesListPager { - + private WeblogFeedRequest feedRequest; - + public FeedEntriesPager(WeblogFeedRequest feedRequest) { - super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), + super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), feedRequest.getLocale(), feedRequest.getType(), - feedRequest.getFormat(), null, null, null, false, true), + feedRequest.getFormat(), null, null, null, false, true), feedRequest.getWeblog(), null, feedRequest.getWeblogCategoryName(), feedRequest.getTags(), feedRequest.getLocale(), -1, feedRequest.getPage(), DEFAULT_ENTRIES); this.feedRequest = feedRequest; } - + protected String createURL(String url, Map params) { List tags = feedRequest.getTags(); if(tags != null && tags.size() > 0) { @@ -171,30 +171,30 @@ protected String createURL(String url, Map params) { String category = feedRequest.getWeblogCategoryName(); if(category != null && category.trim().length() > 0) { params.put("cat", URLUtilities.encode(category)); - } + } if(feedRequest.isExcerpts()) { params.put("excerpts", "true"); - } + } return super.createURL(url, params); } - + public String getUrl() { return createURL(super.getUrl(), new HashMap()); } } - + public class FeedCommentsPager extends CommentsPager { - + private WeblogFeedRequest feedRequest; - - public FeedCommentsPager(WeblogFeedRequest feedRequest) { - super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), + + public FeedCommentsPager(WeblogFeedRequest feedRequest) { + super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), feedRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), null, null, null, false, true), feedRequest.getWeblog(), feedRequest.getLocale(), -1, feedRequest.getPage(), DEFAULT_ENTRIES); this.feedRequest = feedRequest; } - + protected String createURL(String url, Map params) { List tags = feedRequest.getTags(); if(tags != null && tags.size() > 0) { @@ -203,30 +203,30 @@ protected String createURL(String url, Map params) { String category = feedRequest.getWeblogCategoryName(); if(category != null && category.trim().length() > 0) { params.put("cat", URLUtilities.encode(category)); - } + } if(feedRequest.isExcerpts()) { params.put("excerpts", "true"); - } + } return super.createURL(url, params); } - + public String getUrl() { return createURL(super.getUrl(), new HashMap()); } - } + } public class FeedFilesPager extends MediaFilesPager { - + private WeblogFeedRequest feedRequest; - - public FeedFilesPager(WeblogFeedRequest feedRequest) { - super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), + + public FeedFilesPager(WeblogFeedRequest feedRequest) { + super(urlStrategy, urlStrategy.getWeblogFeedURL(feedRequest.getWeblog(), feedRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), null, null, null, false, true), feedRequest.getWeblog(), -1, feedRequest.getPage(), 10); this.feedRequest = feedRequest; } - + protected String createURL(String url, Map params) { List tags = feedRequest.getTags(); if(tags != null && tags.size() > 0) { @@ -235,15 +235,15 @@ protected String createURL(String url, Map params) { String category = feedRequest.getWeblogCategoryName(); if(category != null && category.trim().length() > 0) { params.put("cat", URLUtilities.encode(category)); - } + } if(feedRequest.isExcerpts()) { params.put("excerpts", "true"); - } + } return super.createURL(url, params); } - + public String getUrl() { return createURL(super.getUrl(), new HashMap()); } - } + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MenuModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MenuModel.java index 086a3e8c70..6ff0ff1219 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MenuModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MenuModel.java @@ -33,31 +33,31 @@ /** * Model which provides methods for displaying editor menu/navigation-bar. - * + * * Implemented by calling hybrid JSP tag. */ public class MenuModel implements Model { - + private static Log logger = LogFactory.getLog(MenuModel.class); - + private WeblogPageRequest pageRequest = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "menuModel"; } - - + + /** Init page model based on request */ public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // MenuModel only works on page requests, so cast weblogRequest // into a WeblogPageRequest and if it fails then throw exception if(weblogRequest instanceof WeblogPageRequest) { @@ -67,18 +67,18 @@ public void init(Map initData) throws WebloggerException { " MenuModel only supports page requests."); } } - - + + /** - * Get a Menu representing the admin UI action menu, if the user is + * Get a Menu representing the admin UI action menu, if the user is * currently logged in and is an admin. */ public Menu getAdminMenu() { try { - GlobalPermission adminPerm = + GlobalPermission adminPerm = new GlobalPermission(Collections.singletonList(GlobalPermission.ADMIN)); boolean hasAdmin = WebloggerFactory.getWeblogger().getUserManager() - .checkPermission(adminPerm, pageRequest.getUser()); + .checkPermission(adminPerm, pageRequest.getUser()); if (pageRequest.isLoggedIn() && hasAdmin) { return MenuHelper.getMenu("admin", "noAction", pageRequest.getUser(), pageRequest.getWeblog()); } @@ -87,8 +87,8 @@ public Menu getAdminMenu() { } return null; } - - + + /** * Get a Menu representing the author UI action menu, if the use is * currently logged in. @@ -99,5 +99,5 @@ public Menu getAuthorMenu() { } return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MessageModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MessageModel.java index 70b51cceac..3607e69c30 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MessageModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/MessageModel.java @@ -29,37 +29,37 @@ * Provides access to application resources required for I18N. * Uses model name 'text' because that's what the Velocity Tools did. */ -public class MessageModel implements Model { - +public class MessageModel implements Model { + I18nMessages messages = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "text"; } - - + + /** Init page model based on request */ public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // get messages util based on desired locale this.messages = I18nMessages.getMessages(weblogRequest.getLocaleInstance()); } - - + + /** Return message string */ public String get(String key) { return messages.getString(key); } - - + + /** Return parameterized message string */ public String get(String key, List args) { return messages.getString(key, args); diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/Model.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/Model.java index 2baf5de5c3..21490e7b78 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/Model.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/Model.java @@ -26,16 +26,16 @@ * Represents a set of functionality to be used at rendering. */ public interface Model { - + /** * Name to be used when referring to this model. */ public String getModelName(); - - + + /** * Initialize. */ public void init(Map params) throws WebloggerException; - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ModelLoader.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ModelLoader.java index 5bbc747eef..14de590fa5 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ModelLoader.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/ModelLoader.java @@ -37,10 +37,10 @@ * Helps with model loading process. */ public class ModelLoader { - + private static Log log = LogFactory.getLog(ModelLoader.class); - - + + /** * Load old page models, but only if they are enabled. */ @@ -51,21 +51,21 @@ public static void loadOldModels( PageContext pageContext, WeblogPageRequest pageRequest, URLStrategy urlStrategy) throws WebloggerException { - - // Only load old models if it's enabled - if (WebloggerConfig.getBooleanProperty("rendering.legacyModels.enabled")) { - ContextLoader.setupContext(model, request, response, pageContext, pageRequest, urlStrategy); + + // Only load old models if it's enabled + if (WebloggerConfig.getBooleanProperty("rendering.legacyModels.enabled")) { + ContextLoader.setupContext(model, request, response, pageContext, pageRequest, urlStrategy); } } - - + + /** * Load set of custom models set for the given weblog. * * Does not fail if there is a problem with one of the models. */ public static void loadCustomModels(Weblog weblog, Map model, Map initData) { - + if (weblog.getPageModels() != null) { try { loadModels(weblog.getPageModels(), model, initData, false); @@ -73,20 +73,20 @@ public static void loadCustomModels(Weblog weblog, Map model, Map initData) { // shouldn't happen, but log it just in case log.error("Error loading weblog custom models", ex); } - } + } } - - + + /** * Convenience method to load a comma-separated list of page models. * * Optionally fails if any exceptions are thrown when initializing * the Model instances. */ - public static void loadModels(String modelsString, Map model, - Map initData, boolean fail) + public static void loadModels(String modelsString, Map model, + Map initData, boolean fail) throws WebloggerException { - + String[] models = Utilities.stringToStringArray(modelsString, ","); for(int i=0; i < models.length; i++) { try { @@ -121,5 +121,5 @@ public static void loadModels(String modelsString, Map model, } } } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PageModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PageModel.java index 9dabdd614a..f06dad0cb2 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PageModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PageModel.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.weblogger.ui.rendering.model; +package org.apache.roller.weblogger.ui.rendering.model; import java.util.ArrayList; import java.util.List; @@ -46,43 +46,43 @@ * Model which provides information needed to render a weblog page. */ public class PageModel implements Model { - + private static Log log = LogFactory.getLog(PageModel.class); - + private WeblogPageRequest pageRequest = null; private URLStrategy urlStrategy = null; private WeblogEntryCommentForm commentForm = null; private Map requestParameters = null; private Weblog weblog = null; - - + + /** - * + * * Creates an un-initialized new instance, Weblogger calls init() to complete * construction. */ public PageModel() {} - - - /** + + + /** * Template context name to be used for model. */ public String getModelName() { return "model"; } - - - /** - * Init page model based on request. + + + /** + * Init page model based on request. */ public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // PageModel only works on page requests, so cast weblogRequest // into a WeblogPageRequest and if it fails then throw exception if(weblogRequest instanceof WeblogPageRequest) { @@ -91,48 +91,48 @@ public void init(Map initData) throws WebloggerException { throw new WebloggerException("weblogRequest is not a WeblogPageRequest."+ " PageModel only supports page requests."); } - + // see if there is a comment form this.commentForm = (WeblogEntryCommentForm) initData.get("commentForm"); - + // custom request parameters this.requestParameters = (Map)initData.get("requestParameters"); - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + // extract weblog object weblog = pageRequest.getWeblog(); - } - - + } + + /** * Get the weblog locale used to render this page, null if no locale. */ public String getLocale() { return pageRequest.getLocale(); } - - + + /** * Get weblog being displayed. */ public WeblogWrapper getWeblog() { return WeblogWrapper.wrap(weblog, urlStrategy); } - - + + /** * Is this page considered a permalink? */ public boolean isPermalink() { return (pageRequest.getWeblogAnchor() != null); } - - + + /** * Is this page showing search results? */ @@ -140,8 +140,8 @@ public boolean isSearchResults() { // the search results model will extend this class and override this return false; } - - + + /** * Get weblog entry being displayed or null if none specified by request. */ @@ -151,8 +151,8 @@ public WeblogEntryWrapper getWeblogEntry() { } return null; } - - + + /** * Get weblog entry being displayed or null if none specified by request. */ @@ -168,8 +168,8 @@ public ThemeTemplateWrapper getWeblogPage() { } return null; } - - + + /** * Get weblog category specified by request, or null if the category path * found in the request does not exist in the current weblog. @@ -180,64 +180,64 @@ public WeblogCategoryWrapper getWeblogCategory() { } return null; } - - + + /** * Returns the list of tags specified in the request /tags/foo+bar */ public List getTags() { return pageRequest.getTags(); } - - + + /** - * A map of entries representing this page. The collection is grouped by - * days of entries. Each value is a list of entry objects keyed by the + * A map of entries representing this page. The collection is grouped by + * days of entries. Each value is a list of entry objects keyed by the * date they were published. */ public WeblogEntriesPager getWeblogEntriesPager() { return getWeblogEntriesPager(null); } - - + + /** * A map of entries representing this page - with entries restricted by category. - * The collection is grouped by days of entries. + * The collection is grouped by days of entries. * Each value is a list of entry objects keyed by the date they were published. * @param catArgument Category restriction (null or "nil" for no restriction) */ public WeblogEntriesPager getWeblogEntriesPager(String catArgument) { return getWeblogEntriesPager(catArgument, null); } - - + + /** * A map of entries representing this page - with entries restricted by tag. - * The collection is grouped by days of entries. + * The collection is grouped by days of entries. * Each value is a list of entry objects keyed by the date they were published. * @param tagArgument tag restriction (null or "nil" for no restriction) */ public WeblogEntriesPager getWeblogEntriesPagerByTag(String tagArgument) { return getWeblogEntriesPager(null, tagArgument); } - - + + private WeblogEntriesPager getWeblogEntriesPager(String catArgument, String tagArgument) { - + // category specified by argument wins over request parameter String cat = pageRequest.getWeblogCategoryName(); if (catArgument != null && !StringUtils.isEmpty(catArgument) && !"nil".equals(catArgument)) { cat = catArgument; } - + List tags = pageRequest.getTags(); if (tagArgument != null && !StringUtils.isEmpty(tagArgument) && !"nil".equals(tagArgument)) { tags = new ArrayList(); tags.add(tagArgument); } - + String dateString = pageRequest.getWeblogDate(); - + // determine which mode to use if (pageRequest.getWeblogAnchor() != null) { return new WeblogEntriesPermalinkPager( @@ -272,7 +272,7 @@ private WeblogEntriesPager getWeblogEntriesPager(String catArgument, String tagA cat, tags, pageRequest.getPageNum()); - + } else { return new WeblogEntriesLatestPager( urlStrategy, @@ -286,21 +286,21 @@ private WeblogEntriesPager getWeblogEntriesPager(String catArgument, String tagA pageRequest.getPageNum()); } } - - + + /** * Get comment form to be displayed, may contain preview data. * * @return Comment form object */ public WeblogEntryCommentForm getCommentForm() { - + if(commentForm == null) { commentForm = new WeblogEntryCommentForm(); } return commentForm; } - + /** * Get request parameter by name. */ @@ -313,5 +313,5 @@ public String getRequestParameter(String paramName) { } return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PlanetModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PlanetModel.java index 0a66fb9a91..d065cf27b3 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PlanetModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PlanetModel.java @@ -45,53 +45,53 @@ * Model that provides access to planet aggregations, feeds and subscriptions. */ public class PlanetModel implements Model { - - public static final String DEFAULT_PLANET_HANDLE = "default"; - + + public static final String DEFAULT_PLANET_HANDLE = "default"; + private static Log log = LogFactory.getLog(PlanetModel.class); - + private WeblogRequest weblogRequest = null; private String pageLink = null; private int pageNum = 0; private Weblog weblog = null; - + private URLStrategy urlStrategy = null; private org.apache.roller.planet.business.URLStrategy planetUrlStrategy = null; - + public String getModelName() { return "planet"; } - + public void init(Map initData) throws WebloggerException { if (!WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) return; - + // we expect the init data to contain a weblogRequest object this.weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(this.weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + if (weblogRequest instanceof WeblogPageRequest) { ThemeTemplate weblogPage = ((WeblogPageRequest)weblogRequest).getWeblogPage(); pageLink = (weblogPage != null) ? weblogPage.getLink() : null; pageNum = ((WeblogPageRequest)weblogRequest).getPageNum(); - } - + } + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + planetUrlStrategy = PlanetFactory.getPlanet().getURLStrategy(); - + // extract weblog object weblog = weblogRequest.getWeblog(); - } - - + } + + /** * Get pager for PlanetEntry objects from 'all' and * 'exernal' Planet groups. in reverse chrono order. @@ -99,23 +99,23 @@ public void init(Map initData) throws WebloggerException { * @param len Max number of results to return */ public Pager getAggregationPager(int sinceDays, int length) { - - String pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + + String pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); - + return new PlanetEntriesPager( urlStrategy, null, - null, + null, pagerUrl, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); } - - + + /** * Get pager for WeblogEntry objects from specified * Planet groups in reverse chrono order. @@ -123,11 +123,11 @@ public Pager getAggregationPager(int sinceDays, int length) { * @param len Max number of results to return */ public Pager getAggregationPager(String groupHandle, int sinceDays, int length) { - - String pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + + String pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); - + return new PlanetEntriesPager( urlStrategy, null, @@ -135,11 +135,11 @@ public Pager getAggregationPager(String groupHandle, int sinceDays, int length) pagerUrl, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); } - - + + /** * Get pager for WeblogEntry objects from specified * Planet feed in reverse chrono order. @@ -147,11 +147,11 @@ public Pager getAggregationPager(String groupHandle, int sinceDays, int length) * @param len Max number of results to return */ public Pager getFeedPager(String feedURL, int length) { - - String pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + + String pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); - + return new PlanetEntriesPager( urlStrategy, feedURL, @@ -159,11 +159,11 @@ public Pager getFeedPager(String feedURL, int length) { pagerUrl, weblogRequest.getLocale(), -1, - pageNum, + pageNum, length); } - - + + /** * Get PlanetSubscription objects in descending order by Planet ranking. * @param sinceDays Only consider weblogs updated in the last sinceDays @@ -173,8 +173,8 @@ public Pager getFeedPager(String feedURL, int length) { public List getRankedSubscriptions(int sinceDays, int length) { return getRankedSubscriptions(null, sinceDays, length); } - - + + /** * Get PlanetSubscription objects in descending order by Planet ranking. * @param groupHandle Only consider weblogs updated in the last sinceDays @@ -192,15 +192,15 @@ public List getRankedSubscriptions(String groupHandle, int sinceDays, int length for (Iterator it = subs.iterator(); it.hasNext();) { Subscription sub = (Subscription) it.next(); // TODO needs pojo wrapping from planet - list.add(sub); + list.add(sub); } } catch (Exception e) { log.error("ERROR: get ranked blogs", e); } return list; } - - + + /** * Get PlanetGroups defined. * @return List of Planet groups defined. @@ -213,15 +213,15 @@ public List getGroups() { Set groups = (Set)defaultPlanet.getGroups(); for (PlanetGroup group : groups) { // TODO needs pojo wrapping from planet - list.add(group); + list.add(group); } } catch (Exception e) { log.error("ERROR: getting groups", e); } - return list; + return list; } - - + + /** * Get PlanetGroup by handle. * @param groupHandle Handle of PlanetGroup to fetch. @@ -231,26 +231,26 @@ public PlanetGroup getGroup(String groupHandle) { PlanetGroup group = null; try { PlanetManager planetManager = PlanetFactory.getPlanet().getPlanetManager(); - Planet defaultPlanet = planetManager.getPlanet(DEFAULT_PLANET_HANDLE); + Planet defaultPlanet = planetManager.getPlanet(DEFAULT_PLANET_HANDLE); // TODO needs pojo wrapping from planet - group = planetManager.getGroup(defaultPlanet, groupHandle); + group = planetManager.getGroup(defaultPlanet, groupHandle); } catch (Exception e) { log.error("ERROR: getting group", e); } - return group; + return group; } - - + + public String getPlanetURL() { return planetUrlStrategy.getPlanetURL("ignored"); } - + public String getPlanetGroupURL(String group, int pageNum) { return planetUrlStrategy.getPlanetGroupURL("ignored", group, pageNum); } - - + + public String getPlanetFeedURL(String group, String format) { return planetUrlStrategy.getPlanetGroupFeedURL("ignored", group, format); } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewPageModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewPageModel.java index f627c136dc..12fec1cfcc 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewPageModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewPageModel.java @@ -34,22 +34,22 @@ * An extension of the PageModel to make some adjustments for previewing. */ public class PreviewPageModel extends PageModel { - + private WeblogPreviewRequest previewRequest = null; private URLStrategy urlStrategy = null; - - - /** + + + /** * Init model. */ public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + // PreviewPageModel only works on preview requests, so cast weblogRequest // into a WeblogPreviewRequest and if it fails then throw exception if(weblogRequest instanceof WeblogPreviewRequest) { @@ -58,45 +58,45 @@ public void init(Map initData) throws WebloggerException { throw new WebloggerException("weblogRequest is not a WeblogPreviewRequest."+ " PreviewPageModel only supports preview requests."); } - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + super.init(initData); - } - - + } + + public boolean isPermalink() { return (previewRequest.getPreviewEntry() != null || previewRequest.getWeblogAnchor() != null); } - - + + public WeblogEntryWrapper getWeblogEntry() { - + if(previewRequest.getPreviewEntry() != null || previewRequest.getWeblogAnchor() != null) { return WeblogEntryWrapper.wrap(previewRequest.getWeblogEntry(), urlStrategy); } return null; } - - + + /** * Override method that returns pager so that we can introduce a custom * pager for preview pages which can display things that we don't want * available on the "live" weblog, like DRAFT entries. */ public WeblogEntriesPager getWeblogEntriesPager(String catArgument) { - + String anchor = previewRequest.getPreviewEntry(); if(anchor == null) { anchor = previewRequest.getWeblogAnchor(); } - + if (anchor != null) { return new WeblogEntriesPreviewPager( urlStrategy, @@ -120,7 +120,7 @@ public WeblogEntriesPager getWeblogEntriesPager(String catArgument) { previewRequest.getTags(), previewRequest.getPageNum()); } - + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewURLModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewURLModel.java index aa93f65972..8129ba4792 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewURLModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/PreviewURLModel.java @@ -31,22 +31,22 @@ * generated to make them work for previewing mode. */ public class PreviewURLModel extends URLModel { - + private WeblogPreviewRequest previewRequest = null; private Weblog weblog = null; private String locale = null; - + private URLStrategy urlStrategy = null; - - + + public void init(Map initData) throws WebloggerException { - + // need a weblog request so that we can know the weblog and locale WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("Expected 'weblogRequest' init param!"); } - + // PreviewURLModel only works on preview requests, so cast weblogRequest // into a WeblogPreviewRequest and if it fails then throw exception if(weblogRequest instanceof WeblogPreviewRequest) { @@ -55,20 +55,20 @@ public void init(Map initData) throws WebloggerException { throw new WebloggerException("weblogRequest is not a WeblogPreviewRequest."+ " PreviewURLModel only supports preview requests."); } - + this.weblog = weblogRequest.getWeblog(); this.locale = weblogRequest.getLocale(); - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + super.init(initData); } - - + + /** * We need resource urls to point to our custom PreviewResourceServlet * because when previewing a theme the ResourceServlet has no way of @@ -78,5 +78,5 @@ public void init(Map initData) throws WebloggerException { public String resource(String filePath) { return urlStrategy.getWeblogResourceURL(weblog, filePath, true); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsFeedModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsFeedModel.java index 77f4c9565f..923321dc18 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsFeedModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsFeedModel.java @@ -60,16 +60,16 @@ public class SearchResultsFeedModel implements Model { private static Log log = LogFactory.getLog(SearchResultsFeedModel.class); - + private WeblogFeedRequest feedRequest = null; private URLStrategy urlStrategy = null; private Weblog weblog = null; - + // the pager used by the 3.0+ rendering system private SearchResultsFeedPager pager = null; - + private List results = new LinkedList(); - + private Set categories = new TreeSet(); private boolean websiteSpecificSearch = true; @@ -77,7 +77,7 @@ public class SearchResultsFeedModel implements Model { private int hits = 0; private int offset = 0; private int limit = 0; - + private int entryCount = 0; @@ -85,127 +85,127 @@ public String getModelName() { return "model"; } - + public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + if(weblogRequest instanceof WeblogFeedRequest) { this.feedRequest = (WeblogFeedRequest) weblogRequest; } else { throw new WebloggerException("weblogRequest is not a WeblogFeedRequest."+ " FeedModel only supports feed requests."); } - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + // extract weblog object weblog = feedRequest.getWeblog(); - - String pagerUrl = urlStrategy.getWeblogFeedURL(weblog, + + String pagerUrl = urlStrategy.getWeblogFeedURL(weblog, feedRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), null, null, /* cat and term are null but added to the url in the pager */ null, false, true); - + // if there is no query, then we are done if(feedRequest.getTerm() == null) { pager = new SearchResultsFeedPager(urlStrategy, pagerUrl, feedRequest.getPage(), feedRequest, results, false); return; } - + this.entryCount = WebloggerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries"); - + // setup the search IndexManager indexMgr = WebloggerFactory.getWeblogger().getIndexManager(); - + SearchOperation search = new SearchOperation(indexMgr); search.setTerm(feedRequest.getTerm()); - + if(WebloggerRuntimeConfig.isSiteWideWeblog(feedRequest.getWeblogHandle())) { this.websiteSpecificSearch = false; } else { search.setWebsiteHandle(feedRequest.getWeblogHandle()); } - + if(StringUtils.isNotEmpty(feedRequest.getWeblogCategoryName())) { search.setCategory(feedRequest.getWeblogCategoryName()); } - + // execute search indexMgr.executeIndexOperationNow(search); - + if (search.getResultsCount() > -1) { Hits hits = search.getResults(); this.hits = search.getResultsCount(); - + // Convert the Hits into WeblogEntryData instances. convertHitsToEntries(hits); } - + // search completed, setup pager based on results pager = new SearchResultsFeedPager(urlStrategy, pagerUrl, feedRequest.getPage(), feedRequest, results, (hits > (offset+limit))); } - + public Pager getSearchResultsPager() { return pager; } - + private void convertHitsToEntries(Hits hits) throws WebloggerException { - + // determine offset this.offset = feedRequest.getPage() * this.entryCount; if(this.offset >= hits.length()) { this.offset = 0; } - + // determine limit this.limit = this.entryCount; if(this.offset + this.limit > hits.length()) { this.limit = hits.length() - this.offset; } - + try { TreeSet categories = new TreeSet(); Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager weblogMgr = roller.getWeblogEntryManager(); - + WeblogEntry entry = null; Document doc = null; String handle = null; Timestamp now = new Timestamp(new Date().getTime()); for(int i = offset; i < offset+limit; i++) { - + entry = null; // reset for each iteration - + doc = hits.doc(i); handle = doc.getField(FieldConstants.WEBSITE_HANDLE).stringValue(); - + if(websiteSpecificSearch && handle.equals(feedRequest.getWeblogHandle())) { - + entry = weblogMgr.getWeblogEntry( doc.getField(FieldConstants.ID).stringValue()); } else { - + entry = weblogMgr.getWeblogEntry( doc.getField(FieldConstants.ID).stringValue()); - + if (doc.getField(FieldConstants.CATEGORY) != null) { categories.add( doc.getField(FieldConstants.CATEGORY).stringValue()); } } - + // maybe null if search result returned inactive user // or entry's user is not the requested user. // but don't return future posts @@ -213,7 +213,7 @@ private void convertHitsToEntries(Hits hits) throws WebloggerException { results.add(WeblogEntryWrapper.wrap(entry, urlStrategy)); } } - + if(categories.size() > 0) { this.categories = categories; } @@ -221,14 +221,14 @@ private void convertHitsToEntries(Hits hits) throws WebloggerException { throw new WebloggerException(e); } } - + /** * Get weblog being displayed. */ public WeblogWrapper getWeblog() { return WeblogWrapper.wrap(weblog, urlStrategy); } - + public String getTerm() { return (feedRequest.getTerm() == null) ? "" : feedRequest.getTerm(); } @@ -240,7 +240,7 @@ public int getHits() { public int getOffset() { return offset; } - + public int getPage() { return feedRequest.getPage(); } @@ -259,16 +259,16 @@ public Set getCategories() { public boolean isWebsiteSpecificSearch() { return websiteSpecificSearch; - } - + } + public String getCategoryPath() { return feedRequest.getWeblogCategoryName(); } - + public WeblogCategoryWrapper getWeblogCategory() { if(feedRequest.getWeblogCategory() != null) { return WeblogCategoryWrapper.wrap(feedRequest.getWeblogCategory(), urlStrategy); } return null; - } + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsModel.java index 60dd4d48db..05f588560f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SearchResultsModel.java @@ -57,148 +57,148 @@ * Also adds some new methods which are specific only to search results. */ public class SearchResultsModel extends PageModel { - + public static final int RESULTS_PER_PAGE = 10; - - + + // the original search request WeblogSearchRequest searchRequest = null; private URLStrategy urlStrategy = null; - + // the actual search results mapped by Day -> Set of entries private TreeMap results = new TreeMap(new ReverseComparator()); - + // the pager used by the 3.0+ rendering system private SearchResultsPager pager = null; - + private int hits = 0; private int offset = 0; private int limit = 0; private Set categories = new TreeSet(); private boolean websiteSpecificSearch = true; private String errorMessage = null; - - + + public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a searchRequest object searchRequest = (WeblogSearchRequest) initData.get("searchRequest"); if(searchRequest == null) { throw new WebloggerException("expected searchRequest from init data"); } - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + // let parent initialize super.init(initData); - + // if there is no query, then we are done if(searchRequest.getQuery() == null) { pager = new SearchResultsPager(urlStrategy, searchRequest, results, false); return; } - + // setup the search IndexManager indexMgr = WebloggerFactory.getWeblogger().getIndexManager(); - + SearchOperation search = new SearchOperation(indexMgr); search.setTerm(searchRequest.getQuery()); - + if(WebloggerRuntimeConfig.isSiteWideWeblog(searchRequest.getWeblogHandle())) { this.websiteSpecificSearch = false; } else { search.setWebsiteHandle(searchRequest.getWeblogHandle()); } - + if(StringUtils.isNotEmpty(searchRequest.getWeblogCategoryName())) { search.setCategory(searchRequest.getWeblogCategoryName()); } - + // execute search indexMgr.executeIndexOperationNow(search); - + if (search.getResultsCount() == -1) { // this means there has been a parsing (or IO) error this.errorMessage = I18nMessages.getMessages(searchRequest.getLocaleInstance()).getString("error.searchProblem"); } else { Hits hits = search.getResults(); this.hits = search.getResultsCount(); - + // Convert the Hits into WeblogEntryData instances. convertHitsToEntries(hits); } - + // search completed, setup pager based on results pager = new SearchResultsPager(urlStrategy, searchRequest, results, (hits > (offset+limit))); } - + /** * Is this page showing search results? */ public boolean isSearchResults() { return true; } - + // override page model and return search results pager public WeblogEntriesPager getWeblogEntriesPager() { return pager; } - + // override page model and return search results pager public WeblogEntriesPager getWeblogEntriesPager(String category) { return pager; } - + private void convertHitsToEntries(Hits hits) throws WebloggerException { - + // determine offset this.offset = searchRequest.getPageNum() * RESULTS_PER_PAGE; if(this.offset >= hits.length()) { this.offset = 0; } - + // determine limit this.limit = RESULTS_PER_PAGE; if(this.offset + this.limit > hits.length()) { this.limit = hits.length() - this.offset; } - + try { TreeSet categories = new TreeSet(); Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager weblogMgr = roller.getWeblogEntryManager(); - + WeblogEntry entry = null; Document doc = null; String handle = null; Timestamp now = new Timestamp(new Date().getTime()); for(int i = offset; i < offset+limit; i++) { - + entry = null; // reset for each iteration - + doc = hits.doc(i); handle = doc.getField(FieldConstants.WEBSITE_HANDLE).stringValue(); - + if(websiteSpecificSearch && handle.equals(searchRequest.getWeblogHandle())) { - + entry = weblogMgr.getWeblogEntry( doc.getField(FieldConstants.ID).stringValue()); } else { - + entry = weblogMgr.getWeblogEntry( doc.getField(FieldConstants.ID).stringValue()); - + if (doc.getField(FieldConstants.CATEGORY) != null) { categories.add( doc.getField(FieldConstants.CATEGORY).stringValue()); } } - + // maybe null if search result returned inactive user // or entry's user is not the requested user. // but don't return future posts @@ -206,7 +206,7 @@ private void convertHitsToEntries(Hits hits) throws WebloggerException { addEntryToResults(WeblogEntryWrapper.wrap(entry, urlStrategy)); } } - + if(categories.size() > 0) { this.categories = categories; } @@ -214,13 +214,13 @@ private void convertHitsToEntries(Hits hits) throws WebloggerException { throw new WebloggerException(e); } } - - + + private void addEntryToResults(WeblogEntryWrapper entry) { - + // convert entry's each date to midnight (00m 00h 00s) Date midnight = DateUtil.getStartOfDay(entry.getPubTime()); - + // ensure we do not get duplicates from Lucene by // using a Set Collection. Entries sorted by pubTime. TreeSet set = (TreeSet) this.results.get(midnight); @@ -231,8 +231,8 @@ private void addEntryToResults(WeblogEntryWrapper entry) { } set.add(entry); } - - + + public String getTerm() { String query = searchRequest.getQuery(); return (query == null) ? "" : StringEscapeUtils.escapeXml(Utilities.escapeHTML(query)); @@ -269,16 +269,16 @@ public boolean isWebsiteSpecificSearch() { public String getErrorMessage() { return errorMessage; } - + public String getWeblogCategoryName() { return searchRequest.getWeblogCategoryName(); } - + public WeblogCategoryWrapper getWeblogCategory() { if(searchRequest.getWeblogCategory() != null) { return WeblogCategoryWrapper.wrap(searchRequest.getWeblogCategory(), urlStrategy); } return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SiteModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SiteModel.java index d32cb60694..de44907d3d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SiteModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/SiteModel.java @@ -58,31 +58,31 @@ * Page model that provides access to site-wide users, weblogs and entries. */ public class SiteModel implements Model { - - private static Log log = LogFactory.getLog(SiteModel.class); - + + private static Log log = LogFactory.getLog(SiteModel.class); + private Weblog weblog = null; private WeblogRequest weblogRequest = null; private WeblogFeedRequest feedRequest = null; private List tags = new ArrayList(); private String pageLink = null; private int pageNum = 0; - + private URLStrategy urlStrategy = null; - - + + public String getModelName() { return "site"; } - + public void init(Map initData) throws WebloggerException { - + // we expect the init data to contain a weblogRequest object this.weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(this.weblogRequest == null) { throw new WebloggerException("expected weblogRequest from init data"); } - + if (weblogRequest instanceof WeblogPageRequest) { ThemeTemplate weblogPage = ((WeblogPageRequest)weblogRequest).getWeblogPage(); pageLink = (weblogPage != null) ? weblogPage.getLink() : null; @@ -93,57 +93,57 @@ public void init(Map initData) throws WebloggerException { tags = feedRequest.getTags(); pageNum = feedRequest.getPage(); } - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } - + // extract weblog object weblog = weblogRequest.getWeblog(); } - + //----------------------------------------------------------------- Pagers - + /** * Get pager ofWeblogEntry objects across all weblogs, in reverse chrono order by pubTime. * @param sinceDays Limit to past X days in past (or -1 for no limit) * @param length Max number of results to return */ public Pager getWeblogEntriesPager(int sinceDays, int length) { - + String pagerUrl = null; - + if (feedRequest != null) { - pagerUrl = urlStrategy.getWeblogFeedURL(weblog, + pagerUrl = urlStrategy.getWeblogFeedURL(weblog, weblogRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), feedRequest.getWeblogCategoryName(), null, feedRequest.getTags(), feedRequest.isExcerpts(), true); - } else { - pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + } else { + pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, tags, 0, false); } - + return new WeblogEntriesListPager( urlStrategy, pagerUrl, null, null, null, tags, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); } - - + + /** * Get pager ofWeblogEntry objects across all weblogs, * in reverse chrono order by pubTime. * @param queryWeblog Restrict to this weblog * @param sinceDays Limit to past X days in past (or -1 for no limit) * @param length Max number of results to return - */ + */ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, int sinceDays, int length) { return getWeblogEntriesPager(queryWeblog, null, null, sinceDays, length); } @@ -155,7 +155,7 @@ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, int sinceDays, int * @param user Restrict to this user * @param sinceDays Limit to past X days in past (or -1 for no limit) * @param length Max number of results to return - */ + */ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, User user, int sinceDays, int length) { return getWeblogEntriesPager(queryWeblog, user, null, sinceDays, length); } @@ -168,32 +168,32 @@ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, User user, int sin * @param cat Restrict to this category * @param sinceDays Limit to past X days in past (or -1 for no limit) * @param length Max number of results to return - */ + */ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, User user, String cat, int sinceDays, int length) { - + String pagerUrl = null; if (feedRequest != null) { - pagerUrl = urlStrategy.getWeblogFeedURL(weblog, + pagerUrl = urlStrategy.getWeblogFeedURL(weblog, weblogRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), feedRequest.getWeblogCategoryName(), null, feedRequest.getTags(), feedRequest.isExcerpts(), true); } else { - pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, tags, 0, false); } - + return new WeblogEntriesListPager( urlStrategy, pagerUrl, queryWeblog.getPojo(), user, cat, tags, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); - } - - + } + + /* * Get pager of most recent Comment objects across all weblogs, * in reverse chrono order by postTime. @@ -201,81 +201,81 @@ public Pager getWeblogEntriesPager(WeblogWrapper queryWeblog, User user, String * @param len Max number of results to return */ public Pager getCommentsPager(int sinceDays, int length) { - + String pagerUrl = null; if (feedRequest != null) { - pagerUrl = urlStrategy.getWeblogFeedURL(weblog, + pagerUrl = urlStrategy.getWeblogFeedURL(weblog, weblogRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), null, null, null, feedRequest.isExcerpts(), true); - } else { - pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + } else { + pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); } - + return new CommentsPager( urlStrategy, pagerUrl, null, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); - } - - + } + + /* Get pager of users whose names begin with specified letter */ public Pager getUsersByLetterPager(String letter, int sinceDays, int length) { - + String pagerUrl = null; if (feedRequest != null) { - pagerUrl = urlStrategy.getWeblogFeedURL(weblog, + pagerUrl = urlStrategy.getWeblogFeedURL(weblog, weblogRequest.getLocale(), feedRequest.getType(), feedRequest.getFormat(), null, null, null, feedRequest.isExcerpts(), true); - } else { - pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + } else { + pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); - } - + } + if(letter != null && StringUtils.isEmpty(letter)) { letter = null; } - + return new UsersPager( urlStrategy, pagerUrl, letter, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); - } - - + } + + /** Get pager of weblogs whose handles begin with specified letter */ public Pager getWeblogsByLetterPager(String letter, int sinceDays, int length) { - - String pagerUrl = urlStrategy.getWeblogPageURL(weblog, - weblogRequest.getLocale(), pageLink, + + String pagerUrl = urlStrategy.getWeblogPageURL(weblog, + weblogRequest.getLocale(), pageLink, null, null, null, null, 0, false); - + if(letter != null && StringUtils.isEmpty(letter)) { letter = null; } - + return new WeblogsPager( urlStrategy, pagerUrl, letter, weblogRequest.getLocale(), sinceDays, - pageNum, + pageNum, length); - } - - //--------------------------------------------------- User/weblog directory + } + + //--------------------------------------------------- User/weblog directory /** * Get map with 26 entries, one for each letter A-Z and @@ -284,7 +284,7 @@ public Pager getWeblogsByLetterPager(String letter, int sinceDays, int length) { */ public Map getUserNameLetterMap() { Map results = new HashMap(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager umgr = roller.getUserManager(); results = umgr.getUserNameLetterMap(); @@ -293,8 +293,8 @@ public Map getUserNameLetterMap() { } return results; } - - + + /** * Get map with 26 entries, one for each letter A-Z and * containing integers reflecting the number of weblogs whose @@ -302,21 +302,21 @@ public Map getUserNameLetterMap() { */ public Map getWeblogHandleLetterMap() { Map results = new HashMap(); - try { + try { results = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogHandleLetterMap(); } catch (Exception e) { log.error("ERROR: fetching weblog handle letter map", e); } return results; } - - /** + + /** * Return list of weblogs that user belongs to. */ public List getUsersWeblogs(String userName) { List results = new ArrayList(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager umgr = roller.getUserManager(); User user = umgr.getUserByUserName(userName); @@ -329,14 +329,14 @@ public List getUsersWeblogs(String userName) { } return results; } - - - /** + + + /** * Return list of users that belong to website. */ public List getWeblogsUsers(String handle) { List results = new ArrayList(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager umgr = roller.getUserManager(); Weblog website = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogByHandle(handle); @@ -349,13 +349,13 @@ public List getWeblogsUsers(String handle) { } return results; } - - - + + + /** Get User object by username */ public UserWrapper getUser(String username) { UserWrapper wrappedUser = null; - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager umgr = roller.getUserManager(); User user = umgr.getUserByUserName(username, Boolean.TRUE); @@ -365,12 +365,12 @@ public UserWrapper getUser(String username) { } return wrappedUser; } - - + + /** Get Website object by handle */ public WeblogWrapper getWeblog(String handle) { WeblogWrapper wrappedWebsite = null; - try { + try { Weblog website = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogByHandle(handle); wrappedWebsite = WeblogWrapper.wrap(website, urlStrategy); } catch (Exception e) { @@ -378,10 +378,10 @@ public WeblogWrapper getWeblog(String handle) { } return wrappedWebsite; } - - + + //------------------------------------------------------- Small collections - + /* * Get most collection of Website objects, * in reverse chrono order by creationDate. @@ -394,7 +394,7 @@ public List getNewWeblogs(int sinceDays, int length) { cal.setTime(new Date()); cal.add(Calendar.DATE, -1 * sinceDays); Date startDate = cal.getTime(); - try { + try { List weblogs = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogs( Boolean.TRUE, Boolean.TRUE, startDate, null, 0, length); for (Iterator it = weblogs.iterator(); it.hasNext();) { @@ -406,7 +406,7 @@ public List getNewWeblogs(int sinceDays, int length) { } return results; } - + /* * Get most recent User objects, in reverse chrono order by creationDate. @@ -415,7 +415,7 @@ public List getNewWeblogs(int sinceDays, int length) { */ public List getNewUsers(int sinceDays, int length) { List results = new ArrayList(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager umgr = roller.getUserManager(); List users = umgr.getUsers(Boolean.TRUE, null, null, 0, length); @@ -427,21 +427,21 @@ public List getNewUsers(int sinceDays, int length) { log.error("ERROR: fetching weblog list", e); } return results; - } - - + } + + /** * Get list of WebsiteDisplay objects, ordered by number of hits. * @param sinceDays Only consider weblogs updated in the last sinceDays * @param len Max number of results to return */ public List getHotWeblogs(int sinceDays, int length) { - + List results = new ArrayList(); try { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); List hotBlogs = mgr.getHotWeblogs(sinceDays, 0, length); - + Iterator hitCounts = hotBlogs.iterator(); while (hitCounts.hasNext()) { WeblogHitCount hitCount = (WeblogHitCount) hitCounts.next(); @@ -452,17 +452,17 @@ public List getHotWeblogs(int sinceDays, int length) { "statCount.weblogDayHits", hitCount.getDailyHits()); statCount.setWeblogHandle(hitCount.getWeblog().getHandle()); - results.add(statCount); + results.add(statCount); } - + } catch (Exception e) { log.error("ERROR: fetching hot weblog list", e); } - + return results; } - - + + /** * Get most collection of most commented websites, as StatCount objects, * in descending order by number of comments. @@ -476,7 +476,7 @@ public List getMostCommentedWeblogs(int sinceDays , int length) { cal.setTime(new Date()); cal.add(Calendar.DATE, -1 * sinceDays); Date startDate = cal.getTime(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); results = WebloggerFactory.getWeblogger().getWeblogManager().getMostCommentedWeblogs( startDate, new Date(), 0, length); @@ -485,10 +485,10 @@ public List getMostCommentedWeblogs(int sinceDays , int length) { } return results; } - - + + /** - * Get most commented weblog entries across all weblogs, as StatCount + * Get most commented weblog entries across all weblogs, as StatCount * objects, in descending order by number of comments. * @param sinceDays Only consider weblogs updated in the last sinceDays * @param cats To limit results to list of category names @@ -501,7 +501,7 @@ public List getMostCommentedWeblogEntries( cal.setTime(new Date()); cal.add(Calendar.DATE, -1 * sinceDays); Date startDate = cal.getTime(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); results = wmgr.getMostCommentedWeblogEntries( @@ -511,7 +511,7 @@ public List getMostCommentedWeblogEntries( } return results; } - + /** * Get pinned entries. * @param sinceDays Only consider weblogs updated in the last sinceDays @@ -519,7 +519,7 @@ public List getMostCommentedWeblogEntries( */ public List getPinnedWeblogEntries(int length) { List results = new ArrayList(); - try { + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); List weblogs = wmgr.getWeblogEntriesPinnedToMain(new Integer(length)); @@ -532,9 +532,9 @@ public List getPinnedWeblogEntries(int length) { } return results; } - + /** - * + * * @param sinceDays * @param length * @return @@ -545,11 +545,11 @@ public List getPopularTags(int sinceDays, int length) { if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); - cal.add(Calendar.DATE, -1 * sinceDays); - startDate = cal.getTime(); + cal.add(Calendar.DATE, -1 * sinceDays); + startDate = cal.getTime(); } - - try { + + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); results = wmgr.getPopularTags(null, startDate, 0, length); @@ -557,56 +557,56 @@ public List getPopularTags(int sinceDays, int length) { log.error("ERROR: fetching site tags list", e); } return results; - } - - + } + + public long getCommentCount() { long count = 0; try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager mgr = roller.getWeblogEntryManager(); - count = mgr.getCommentCount(); + count = mgr.getCommentCount(); } catch (WebloggerException e) { log.error("Error getting comment count for site ", e); } return count; } - - + + public long getEntryCount() { long count = 0; try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager mgr = roller.getWeblogEntryManager(); - count = mgr.getEntryCount(); + count = mgr.getEntryCount(); } catch (WebloggerException e) { log.error("Error getting entry count for site", e); } return count; } - - + + public long getWeblogCount() { long count = 0; try { - count = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogCount(); + count = WebloggerFactory.getWeblogger().getWeblogManager().getWeblogCount(); } catch (WebloggerException e) { log.error("Error getting weblog count for site", e); } return count; - } - - + } + + public long getUserCount() { long count = 0; try { Weblogger roller = WebloggerFactory.getWeblogger(); UserManager mgr = roller.getUserManager(); - count = mgr.getUserCount(); + count = mgr.getUserCount(); } catch (WebloggerException e) { log.error("Error getting user count for site", e); } return count; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/URLModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/URLModel.java index 6b4b015cba..ff68198ab1 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/URLModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/URLModel.java @@ -48,46 +48,46 @@ * $url.getCategory("foo") */ public class URLModel implements Model { - + private static Log log = LogFactory.getLog(URLModel.class); - + protected Weblog weblog = null; protected String locale = null; - + protected URLStrategy urlStrategy = null; - - + + public URLModel() {} - + public String getModelName() { return "url"; } - + public void init(Map initData) throws WebloggerException { - + // need a weblog request so that we can know the weblog and locale WeblogRequest weblogRequest = (WeblogRequest) initData.get("parsedRequest"); if(weblogRequest == null) { throw new WebloggerException("Expected 'weblogRequest' init param!"); } - + this.weblog = weblogRequest.getWeblog(); this.locale = weblogRequest.getLocale(); - + // look for url strategy urlStrategy = (URLStrategy) initData.get("urlStrategy"); if(urlStrategy == null) { urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); } } - - + + /** Relative URL of Roller, e.g. /roller */ public String getSite() { return WebloggerRuntimeConfig.getRelativeContextURL(); } - - + + /** Absolute URL of Roller, e.g. http://localhost:8080/roller */ public String getAbsoluteSite() { String weblogAbsoluteURL = @@ -98,20 +98,20 @@ public String getAbsoluteSite() { return WebloggerRuntimeConfig.getAbsoluteContextURL(); } } - - - /** URL for logging in */ + + + /** URL for logging in */ public String getLogin() { return urlStrategy.getLoginURL(false); } - - + + /** URL for logging out */ public String getLogout() { return urlStrategy.getLogoutURL(false); } - - + + /** URL for a specific UI action */ public String action(String action, String namespace) { if(namespace != null) { @@ -125,163 +125,163 @@ public String action(String action, String namespace) { } return null; } - - + + public String getCommentAuthenticator() { return getSite()+"/CommentAuthenticatorServlet"; } - - + + public String themeResource(String theme, String filePath) { return getSite()+"/themes/"+theme+"/"+filePath; } - + public String themeResource(String theme, String filePath, boolean absolute) { if (absolute) { return getAbsoluteSite()+"/themes/"+theme+"/"+filePath; } return themeResource(theme, filePath); } - + public String getHome() { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, null, -1, true); } - - + + public String home(int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, null, pageNum, true); } - - + + public String home(String customLocale) { return urlStrategy.getWeblogCollectionURL(weblog, customLocale, null, null, null, -1, true); } - - + + public String home(String customLocale, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, customLocale, null, null, null, pageNum, true); } - - + + public String entry(String anchor) { return urlStrategy.getWeblogEntryURL(weblog, locale, anchor, true); } - + public String comment(String anchor, String timeStamp) { return urlStrategy.getWeblogCommentURL(weblog, locale, anchor, timeStamp, true); } - - + + public String comments(String anchor) { return urlStrategy.getWeblogCommentsURL(weblog, locale, anchor, true); } - - + + public String trackback(String anchor) { return urlStrategy.getWeblogEntryURL(weblog, locale, anchor, true); } - + public String date(String dateString) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, dateString, null, -1, true); } - - + + public String date(String dateString, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, dateString, null, pageNum, true); } - - + + public String category(String catPath) { return urlStrategy.getWeblogCollectionURL(weblog, locale, catPath, null, null, -1, true); } - - + + public String category(String catPath, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, catPath, null, null, pageNum, true); } - - + + public String tag(String tag) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, Arrays.asList(new String[]{tag}) , -1, true); } - - + + public String tag(String tag, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, Arrays.asList(new String[]{tag}), pageNum, true); - } - - + } + + public String tags(List tags) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, tags , -1, true); } - - + + public String tags(List tags, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, null, null, tags, -1, true); } - - + + public String collection(String dateString, String catPath) { return urlStrategy.getWeblogCollectionURL(weblog, locale, catPath, dateString, null, -1, true); } - - + + public String collection(String dateString, String catPath, int pageNum) { return urlStrategy.getWeblogCollectionURL(weblog, locale, catPath, dateString, null, pageNum, true); } - - + + public String getSearch() { return urlStrategy.getWeblogSearchURL(weblog, locale, null, null, -1, false); } - + public String search(String query, int pageNum) { return urlStrategy.getWeblogSearchURL(weblog, locale, query, null, pageNum, false); } - - + + public String search(String query, String catPath, int pageNum) { return urlStrategy.getWeblogSearchURL(weblog, locale, query, catPath, pageNum, false); } - + public String absoluteSearch(String query, String catPath, int pageNum) { return urlStrategy.getWeblogSearchURL(weblog, locale, query, catPath, pageNum, true); - } - + } + public String getOpenSearchSite() { return urlStrategy.getOpenSearchSiteURL(); } - + public String getOpenSearchWeblog() { return urlStrategy.getOpenSearchWeblogURL(weblog.getHandle()); } - + public String page(String pageLink) { return urlStrategy.getWeblogPageURL(weblog, locale, pageLink, null, null, null, null, -1, true); } - - + + public String page(String pageLink, String dateString, String catPath, int pageNum) { return urlStrategy.getWeblogPageURL(weblog, locale, pageLink, null, catPath, dateString, null, pageNum, true); } - - + + public String resource(String filePath) { return urlStrategy.getWeblogResourceURL(weblog, filePath, true); } - - + + public String getRsd() { return urlStrategy.getWeblogRsdURL(weblog, true); } - - + + public FeedURLS getFeed() { return new FeedURLS(); } - - + + /** URL for editing a weblog entry */ public String editEntry(String anchor) { try { @@ -295,29 +295,29 @@ public String editEntry(String anchor) { log.error("Error looking up entry by anchor - "+anchor, ex); } return null; - } - - + } + + /** URL for creating a new weblog entry */ public String getCreateEntry() { return urlStrategy.getEntryAddURL(weblog.getHandle(), false); } - - + + /** URL for editing weblog settings */ public String getEditSettings() { return urlStrategy.getWeblogConfigURL(weblog.getHandle(), false); } - - + + /////// Inner Classes /////// - + public class FeedURLS { - + public EntryFeedURLS getEntries() { return new EntryFeedURLS(); } - + public CommentFeedURLS getComments() { return new CommentFeedURLS(); } @@ -326,75 +326,75 @@ public MediaFileFeedURLS getMediaFiles() { return new MediaFileFeedURLS(); } } - + public class EntryFeedURLS { - + public String getRss() { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "rss", null, null, null, false, true); } - + public String rss(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "rss", catPath, null, null, excerpts, true); } - + public String rssByTags(List tags, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "rss", null, null, tags, excerpts, true); } - + public String getAtom() { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "atom", null, null, null, false, true); } - + public String atom(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "atom", catPath, null, null, excerpts, true); } - + public String search(String term, String catPath) { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "atom", catPath, term, null, false, true); - } - + } + public String atomByTags(List tags, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "entries", "atom", null, null, tags, excerpts, true); } } - + public class CommentFeedURLS { - + public String getRss() { return urlStrategy.getWeblogFeedURL(weblog, locale, "comments", "rss", null, null, null, false, true); } - + public String rss(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "comments", "rss", catPath, null, null, excerpts, true); } - + public String getAtom() { return urlStrategy.getWeblogFeedURL(weblog, locale, "comments", "atom", null, null, null, false, true); } - + public String atom(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "comments", "atom", catPath, null, null, excerpts, true); } - + } - + public class MediaFileFeedURLS { - + public String getRss() { return urlStrategy.getWeblogFeedURL(weblog, locale, "files", "rss", null, null, null, false, true); } - + public String rss(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "files", "rss", catPath, null, null, excerpts, true); } - + public String getAtom() { return urlStrategy.getWeblogFeedURL(weblog, locale, "files", "atom", null, null, null, false, true); } - + public String atom(String catPath, boolean excerpts) { return urlStrategy.getWeblogFeedURL(weblog, locale, "files", "atom", catPath, null, null, excerpts, true); } - + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java index 747ae4b698..a5c2a49c75 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java @@ -44,81 +44,81 @@ * Model which provides access to a set of general utilities. */ public class UtilitiesModel implements Model { - - private static Log log = LogFactory.getLog(UtilitiesModel.class); - + + private static Log log = LogFactory.getLog(UtilitiesModel.class); + private static Pattern mLinkPattern = - Pattern.compile("", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_B_TAG_PATTERN = + Pattern.compile("", Pattern.CASE_INSENSITIVE); + private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("<b>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_B_TAG_PATTERN = + private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("</b>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_I_TAG_PATTERN = + private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("<i>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_I_TAG_PATTERN = + private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("</i>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("<blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = + private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); - private static final Pattern BR_TAG_PATTERN = + private static final Pattern BR_TAG_PATTERN = Pattern.compile("<br */*>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_P_TAG_PATTERN = + private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("<p>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_P_TAG_PATTERN = + private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("</p>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_PRE_TAG_PATTERN = + private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("<pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_PRE_TAG_PATTERN = + private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("</pre>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_UL_TAG_PATTERN = + private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("<ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_UL_TAG_PATTERN = + private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("</ul>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_OL_TAG_PATTERN = + private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("<ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_OL_TAG_PATTERN = + private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("</ol>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_LI_TAG_PATTERN = + private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("<li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_LI_TAG_PATTERN = + private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("</li>", Pattern.CASE_INSENSITIVE); - private static final Pattern CLOSING_A_TAG_PATTERN = + private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("</a>", Pattern.CASE_INSENSITIVE); - private static final Pattern OPENING_A_TAG_PATTERN = + private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("<a href=.*?>", Pattern.CASE_INSENSITIVE); - private static final Pattern QUOTE_PATTERN = + private static final Pattern QUOTE_PATTERN = Pattern.compile(""", Pattern.CASE_INSENSITIVE); - + private ParsedRequest parsedRequest = null; private Weblog weblog = null; - - + + /** Template context name to be used for model */ public String getModelName() { return "utils"; } - - + + /** Init page model based on request */ - public void init(Map initData) throws WebloggerException { - + public void init(Map initData) throws WebloggerException { + // we expect the init data to contain a parsedRequest object parsedRequest = (ParsedRequest) initData.get("parsedRequest"); if(parsedRequest == null) { throw new WebloggerException("expected parsedRequest from init data"); } - + // extract weblog object if possible if(parsedRequest instanceof WeblogRequest) { WeblogRequest weblogRequest = (WeblogRequest) parsedRequest; weblog = weblogRequest.getWeblog(); } } - - - //---------------------------------------------------- Authentication utils - + + + //---------------------------------------------------- Authentication utils + public boolean isUserAuthorizedToAuthor(WeblogWrapper weblog) { try { if (parsedRequest.getAuthenticUser() != null) { @@ -130,7 +130,7 @@ public boolean isUserAuthorizedToAuthor(WeblogWrapper weblog) { } return false; } - + public boolean isUserAuthorizedToAdmin(WeblogWrapper weblog) { try { if (parsedRequest.getAuthenticUser() != null) { @@ -142,16 +142,16 @@ public boolean isUserAuthorizedToAdmin(WeblogWrapper weblog) { } return false; } - + public boolean isUserAuthenticated() { return (parsedRequest.getAuthenticUser() != null); } - + public UserWrapper getAuthenticatedUser() { - return parsedRequest.getAuthenticUser() != null + return parsedRequest.getAuthenticUser() != null ? UserWrapper.wrap(parsedRequest.getUser()) : null; } - + //-------------------------------------------------------------- Date utils /** * Return date for current time. @@ -159,51 +159,51 @@ public UserWrapper getAuthenticatedUser() { public static Date getNow() { return new Date(); } - + /** * Format date using SimpleDateFormat format string. */ public String formatDate(Date d, String fmt) { return formatDate(d, fmt, weblog.getTimeZoneInstance()); } - + /** * Format date using SimpleDateFormat format string. */ public String formatDate(Date d, String fmt, TimeZone tzOverride) { - + if(d == null || fmt == null) return fmt; - + SimpleDateFormat format = new SimpleDateFormat(fmt, weblog.getLocaleInstance()); if(tzOverride != null) { format.setTimeZone(tzOverride); } - + return format.format(d); } - + /** * Format date in ISO-8601 format. */ public String formatIso8601Date(Date d) { return DateUtil.formatIso8601(d); } - + /** * Format date in ISO-8601 format. */ public String formatIso8601Day(Date d) { return DateUtil.formatIso8601Day(d); } - + /** * Return a date in RFC-822 format. */ public String formatRfc822Date(Date date) { return DateUtil.formatRfc822(date); } - + /** * Return a date in 8 character format YYYYMMDD. */ @@ -211,74 +211,74 @@ public String format8charsDate(Date date) { return DateUtil.format8chars(date); } - + //------------------------------------------------------------ String utils - + public boolean isEmpty(String str) { return StringUtils.isEmpty(str); } - + public boolean isNotEmpty(String str) { return StringUtils.isNotEmpty(str); } - + public String[] split(String str1, String str2) { return StringUtils.split(str1, str2); } - + public boolean equals(String str1, String str2) { return StringUtils.equals(str1, str2); } - + public boolean isAlphanumeric(String str) { return StringUtils.isAlphanumeric(str); } - + public String[] stripAll(String[] strs) { return StringUtils.stripAll(strs); } - + public String left(String str, int length) { return StringUtils.left(str, length); } - + public String escapeHTML(String str) { return StringEscapeUtils.escapeHtml(str); } - + public String unescapeHTML(String str) { return StringEscapeUtils.unescapeHtml(str); } - + public String escapeXML(String str) { return StringEscapeUtils.escapeXml(str); } - + public String unescapeXML(String str) { return StringEscapeUtils.unescapeXml(str); } - + public String escapeJavaScript(String str) { return StringEscapeUtils.escapeJavaScript(str); } - + public String unescapeJavaScript(String str) { return StringEscapeUtils.unescapeJavaScript(str); } - + public String replace(String src, String target, String rWith) { return StringUtils.replace(src, target, rWith); } - + public String replace(String src, String target, String rWith, int maxCount) { return StringUtils.replace(src, target, rWith, maxCount); } - + private String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". Replace @@ -287,7 +287,7 @@ private String replace(String string, Pattern pattern, String replacement) { public String removeHTML(String str) { return removeHTML(str, true); } - + /** * Remove occurences of html, defined as any text * between the characters "<" and ">". @@ -296,14 +296,14 @@ public String removeHTML(String str) { public String removeHTML(String str, boolean addSpace) { return Utilities.removeHTML(str, addSpace); } - + /** * Autoformat. */ public String autoformat(String s) { return Utilities.autoformat(s); } - + /** * Strips HTML and truncates. */ @@ -311,25 +311,25 @@ public String truncate(String str, int lower, int upper, String appendToEnd) { // this method is a dupe of truncateText() method return truncateText(str, lower, upper, appendToEnd); } - + public String truncateNicely(String str, int lower, int upper, String appendToEnd) { return Utilities.truncateNicely(str, lower, upper, appendToEnd); } - + public String truncateText(String str, int lower, int upper, String appendToEnd) { return Utilities.truncateText(str, lower, upper, appendToEnd); - } - + } + public String hexEncode(String str) { if (StringUtils.isEmpty(str)) return str; - + return RegexUtil.encode(str); } - + public String encodeEmail(String str) { return str!=null ? RegexUtil.encodeEmail(str) : null; } - + /** * URL encoding. * @param s a string to be URL-encoded @@ -342,7 +342,7 @@ public final String encode(String s) { return s; } } - + /** * URL decoding. * @param s a URL-encoded string to be URL-decoded @@ -355,14 +355,14 @@ public final String decode(String s) { return s; } } - + /** * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML. */ public String addNofollow(String html) { return Utilities.addNofollow(html); } - + /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes <b>, <i>, <p>, <br>, @@ -374,12 +374,12 @@ public String addNofollow(String html) { public String transformToHTMLSubset(String s) { return Utilities.transformToHTMLSubset(s); } - + /** * Convert a byte array into a Base64 string (as used in mime formats) */ public String toBase64(byte[] aValue) { return Utilities.toBase64(aValue); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractPager.java index db01c19af5..0f59331d49 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractPager.java @@ -28,32 +28,32 @@ * Abstract base for simple pagers. */ public abstract class AbstractPager implements Pager { - + final URLStrategy urlStrategy; private String url = null; private int page = 0; - - + + public AbstractPager(URLStrategy strat, String baseUrl, int pageNum) { - + this.urlStrategy = strat; this.url = baseUrl; if(pageNum > 0) { this.page = pageNum; } } - - + + public String getHomeLink() { return url; } - - + + public String getHomeName() { return "Home"; } - - + + public String getNextLink() { if(hasMoreItems()) { int nextPage = page + 1; @@ -63,16 +63,16 @@ public String getNextLink() { } return null; } - - + + public String getNextName() { if(hasMoreItems()) { return "Next"; } return null; } - - + + public String getPrevLink() { if (page > 0) { int prevPage = page - 1; @@ -82,27 +82,27 @@ public String getPrevLink() { } return null; } - - + + public String getPrevName() { if (page > 0) { return "Previous"; } return null; } - - + + public boolean hasMoreItems() { return false; } - - + + protected String createURL(String url, Map params) { - + return url + URLUtilities.getQueryString(params); } - + public String getUrl() { return url; } @@ -118,5 +118,5 @@ public int getPage() { public void setPage(int page) { this.page = page; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractWeblogEntriesPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractWeblogEntriesPager.java index 11c4119b8c..c591d8017f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractWeblogEntriesPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/AbstractWeblogEntriesPager.java @@ -43,15 +43,15 @@ * paging their own way. */ public abstract class AbstractWeblogEntriesPager implements WeblogEntriesPager { - + private static Log log = LogFactory.getLog(AbstractWeblogEntriesPager.class); - + // message utils for doing i18n messages I18nMessages messageUtils = null; - + // url strategy for building urls URLStrategy urlStrategy = null; - + Weblog weblog = null; String locale = null; String pageLink = null; @@ -62,8 +62,8 @@ public abstract class AbstractWeblogEntriesPager implements WeblogEntriesPager { int offset = 0; int page = 0; int length = 0; - - + + public AbstractWeblogEntriesPager( URLStrategy strat, Weblog weblog, @@ -74,31 +74,31 @@ public AbstractWeblogEntriesPager( String catPath, List tags, int page) { - + this.urlStrategy = strat; - + this.weblog = weblog; this.locale = locale; this.pageLink = pageLink; this.entryAnchor = entryAnchor; this.dateString = dateString; this.catPath = catPath; - + if(tags != null) this.tags = tags; - + // make sure offset, length, and page are valid int maxLength = WebloggerRuntimeConfig.getIntProperty("site.pages.maxEntries"); length = weblog.getEntryDisplayCount(); if(length > maxLength) { length = maxLength; } - + if(page > 0) { this.page = page; } this.offset = length * page; - + // get a message utils instance to handle i18n of messages Locale viewLocale = null; if(locale != null) { @@ -113,75 +113,75 @@ public AbstractWeblogEntriesPager( } this.messageUtils = I18nMessages.getMessages(viewLocale); } - - + + public boolean hasMoreEntries() { return false; } - - + + public String getHomeLink() { return createURL(0, 0, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags); } - - + + public String getHomeName() { return messageUtils.getString("weblogEntriesPager.latest.home"); } - - + + public String getNextLink() { if (hasMoreEntries()) { return createURL(page, 1, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags); } return null; } - - + + public String getNextName() { if (hasMoreEntries()) { return messageUtils.getString("weblogEntriesPager.latest.next"); } return null; } - - + + public String getPrevLink() { if (page > 0) { return createURL(page, -1, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags); } return null; } - - + + public String getPrevName() { if (page > 0) { return messageUtils.getString("weblogEntriesPager.latest.prev"); } return null; } - - + + public String getNextCollectionLink() { return null; } - - + + public String getNextCollectionName() { return null; } - - + + public String getPrevCollectionLink() { return null; } - - + + public String getPrevCollectionName() { return null; } - - + + /** * Parse data as either 6-char or 8-char format. */ @@ -197,7 +197,7 @@ protected Date parseDate(String dateString) { char8DateFormat.setCalendar(cal); ParsePosition pos = new ParsePosition(0); ret = char8DateFormat.parse( dateString, pos ); - + // make sure the requested date is not in the future Date today = getToday(); if (ret.after(today)) ret = today; @@ -208,15 +208,15 @@ protected Date parseDate(String dateString) { char6DateFormat.setCalendar(cal); ParsePosition pos = new ParsePosition(0); ret = char6DateFormat.parse( dateString, pos ); - + // make sure the requested date is not in the future Date today = getToday(); if (ret.after(today)) ret = today; } return ret; } - - + + /** * Return today based on current blog's timezone/locale. */ @@ -227,8 +227,8 @@ protected Date getToday() { todayCal.setTime(new Date()); return todayCal.getTime(); } - - + + /** * Create URL that encodes pager state using most appropriate forms of URL. * @param pageAdd To be added to page number, or 0 for no page number @@ -243,16 +243,16 @@ protected String createURL( String dateString, String catPath, List tags) { - + int pageNum = page + pageAdd; - + if (pageLink != null) { return urlStrategy.getWeblogPageURL(website, locale, pageLink, entryAnchor, catPath, dateString, tags, pageNum, false); } else if (entryAnchor != null) { return urlStrategy.getWeblogEntryURL(website, locale, entryAnchor, true); } - + return urlStrategy.getWeblogCollectionURL(website, locale, catPath, dateString, tags, pageNum, false); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/CommentsPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/CommentsPager.java index 70afd11b85..9a49bab349 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/CommentsPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/CommentsPager.java @@ -39,23 +39,23 @@ * Paging through a collection of comments. */ public class CommentsPager extends AbstractPager { - + private static Log log = LogFactory.getLog(CommentsPager.class); - + private Weblog weblog = null; private String locale = null; private int sinceDays = -1; private int length = 0; - + // the collection for the pager private List comments = null; - + // are there more items? private boolean more = false; - + // most recent update time of current set of entries - private Date lastUpdated = null; - + private Date lastUpdated = null; + public CommentsPager( URLStrategy strat, String baseUrl, @@ -64,27 +64,27 @@ public CommentsPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.weblog = weblog; this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public List getItems() { - + if (comments == null) { // calculate offset int offset = getPage() * length; - + List results = new ArrayList(); - + Date startDate = null; if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); @@ -92,13 +92,13 @@ public List getItems() { cal.add(Calendar.DATE, -1 * sinceDays); startDate = cal.getTime(); } - + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); List entries = wmgr.getComments( weblog, null, null, startDate, null, WeblogEntryComment.APPROVED, true, offset, length + 1); - + // wrap the results int count = 0; for (Iterator it = entries.iterator(); it.hasNext();) { @@ -109,22 +109,22 @@ public List getItems() { more = true; } } - + } catch (Exception e) { log.error("ERROR: fetching comment list", e); } - + comments = results; } - + return comments; } - - + + public boolean hasMoreItems() { return more; } - + /** Get last updated time from items in pager */ public Date getLastUpdated() { if (lastUpdated == null) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/MediaFilesPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/MediaFilesPager.java index f6070eb08d..b5c809058d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/MediaFilesPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/MediaFilesPager.java @@ -36,22 +36,22 @@ * Paging through a collection of media files. */ public class MediaFilesPager extends AbstractPager { - + private static Log log = LogFactory.getLog(MediaFilesPager.class); - + private Weblog weblog = null; private int sinceDays = -1; private int length = 0; - + // the collection for the pager private List mediaFiles; - + // are there more items? private boolean more = false; - + // most recent update time of current set of entries - private Date lastUpdated = null; - + private Date lastUpdated = null; + public MediaFilesPager( URLStrategy strat, String baseUrl, @@ -59,26 +59,26 @@ public MediaFilesPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.weblog = weblog; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public List getItems() { - + if (this.mediaFiles == null) { // calculate offset //int offset = getPage() * length; - + List results = new ArrayList(); - + try { MediaFileManager mgr = WebloggerFactory.getWeblogger().getMediaFileManager(); results = mgr.fetchRecentPublicMediaFiles(length); @@ -87,15 +87,15 @@ public List getItems() { } this.mediaFiles = results; } - + return this.mediaFiles; } - - + + public boolean hasMoreItems() { return more; } - + /** Get last updated time from items in pager */ public Date getLastUpdated() { if (lastUpdated == null) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/Pager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/Pager.java index 6c18d30f48..364e74df82 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/Pager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/Pager.java @@ -53,10 +53,10 @@ public interface Pager { * Link value for prev page in current collection view */ public String getPrevName(); - + /** * Get current list of items available from the pager. */ public List getItems(); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/PlanetEntriesPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/PlanetEntriesPager.java index 5a74aa676a..275284f1fb 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/PlanetEntriesPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/PlanetEntriesPager.java @@ -38,22 +38,22 @@ * Paging through a collection of planet entries. */ public class PlanetEntriesPager extends AbstractPager { - + private static Log log = LogFactory.getLog(PlanetEntriesPager.class); - + private String feedURL = null; private String groupHandle = null; private String locale = null; private int sinceDays = -1; private int length = 0; - + // the collection for the pager private List entries = null; - + // are there more items? private boolean more = false; - - + + public PlanetEntriesPager( URLStrategy strat, String feedURL, @@ -63,26 +63,26 @@ public PlanetEntriesPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.feedURL = feedURL; this.groupHandle = groupHandle; this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public List getItems() { - + if (entries == null) { // calculate offset int offset = getPage() * length; - + Date startDate = null; if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); @@ -90,12 +90,12 @@ public List getItems() { cal.add(Calendar.DATE, -1 * sinceDays); startDate = cal.getTime(); } - + List results = new ArrayList(); try { PlanetManager planetManager = PlanetFactory.getPlanet().getPlanetManager(); Planet planet = planetManager.getPlanet("default"); - + List entries = null; if (feedURL != null) { Subscription sub = planetManager.getSubscription(feedURL); @@ -107,30 +107,30 @@ public List getItems() { PlanetGroup group = planetManager.getGroup(planet, "all"); entries = planetManager.getEntries(group, startDate, null, offset, length+1); } - + // wrap 'em int count = 0; for (Iterator it = entries.iterator(); it.hasNext();) { SubscriptionEntry entry = (SubscriptionEntry) it.next(); // TODO needs pojo wrapping from planet - if (count++ < length) { + if (count++ < length) { results.add(entry); } else { more = true; } } - + } catch (Exception e) { log.error("ERROR: get aggregation", e); } - + entries = results; } - + return entries; } - - + + public boolean hasMoreItems() { return more; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsFeedPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsFeedPager.java index c5fd0a3071..dcd4753128 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsFeedPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsFeedPager.java @@ -34,38 +34,38 @@ * Pager for navigating through search results feeds. */ public class SearchResultsFeedPager extends AbstractPager { - + // message utils for doing i18n messages I18nMessages messageUtils = null; - + private List entries = null; - + private Weblog weblog = null; private boolean moreResults = false; - + private WeblogFeedRequest feedRequest = null; - + private String url = null; - - + + public SearchResultsFeedPager(URLStrategy strat, String baseUrl, int pageNum, WeblogFeedRequest feedRequest, List entries, boolean more) { - + super(strat, baseUrl, pageNum); - + this.url = baseUrl; - + this.feedRequest = feedRequest; - + // store search results this.entries = entries; - + // data from search request this.weblog = feedRequest.getWeblog(); - + // does this pager have more results? this.moreResults = more; - + // get a message utils instance to handle i18n of messages Locale viewLocale = null; if(feedRequest.getLocale() != null) { @@ -80,23 +80,23 @@ public SearchResultsFeedPager(URLStrategy strat, String baseUrl, int pageNum, } this.messageUtils = I18nMessages.getMessages(viewLocale); } - + public List getItems() { return this.entries; } - + public boolean hasMoreItems() { return this.moreResults; } - + public String getHomeLink() { return urlStrategy.getWeblogURL(weblog, weblog.getLocale(), false); } public String getHomeName() { return messageUtils.getString("searchPager.home"); - } - + } + protected String createURL(String url, Map params) { String category = feedRequest.getWeblogCategoryName(); if(category != null && category.trim().length() > 0) { @@ -105,17 +105,17 @@ protected String createURL(String url, Map params) { String term = feedRequest.getTerm(); if(term != null && term.trim().length() > 0) { params.put("q", URLUtilities.encode(term.trim())); - } + } List tags = feedRequest.getTags(); if(tags != null && tags.size() > 0) { params.put("tags", URLUtilities.getEncodedTagsString(tags)); } if(feedRequest.isExcerpts()) { params.put("excerpts", "true"); - } + } return super.createURL(url, params); } - + public String getUrl() { return createURL(url, new HashMap()); } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsPager.java index abdbd01979..4f410bc9b4 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/SearchResultsPager.java @@ -29,43 +29,43 @@ * Pager for navigating through search results. */ public class SearchResultsPager implements WeblogEntriesPager { - + // message utils for doing i18n messages I18nMessages messageUtils = null; - + // url strategy URLStrategy urlStrategy = null; - + private Map entries = null; - + private Weblog weblog = null; private String locale = null; private String query = null; private String category = null; private int page = 0; private boolean moreResults = false; - - + + public SearchResultsPager() {} - + public SearchResultsPager(URLStrategy strat, WeblogSearchRequest searchRequest, Map entries, boolean more) { - + // url strategy for building urls this.urlStrategy = strat; - + // store search results this.entries = entries; - + // data from search request this.weblog = searchRequest.getWeblog(); this.query = searchRequest.getQuery(); this.category = searchRequest.getWeblogCategoryName(); this.locale = searchRequest.getLocale(); this.page = searchRequest.getPageNum(); - + // does this pager have more results? this.moreResults = more; - + // get a message utils instance to handle i18n of messages Locale viewLocale = null; if(locale != null) { @@ -80,13 +80,13 @@ public SearchResultsPager(URLStrategy strat, WeblogSearchRequest searchRequest, } this.messageUtils = I18nMessages.getMessages(viewLocale); } - - + + public Map getEntries() { return entries; } - - + + public String getHomeLink() { return urlStrategy.getWeblogURL(weblog, locale, false); } @@ -95,7 +95,7 @@ public String getHomeName() { return messageUtils.getString("searchPager.home"); } - + public String getNextLink() { if(moreResults) { return urlStrategy.getWeblogSearchURL(weblog, locale, query, category, page + 1, false); @@ -124,7 +124,7 @@ public String getPrevName() { return null; } - + public String getNextCollectionLink() { return null; } @@ -140,5 +140,5 @@ public String getPrevCollectionLink() { public String getPrevCollectionName() { return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/UsersPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/UsersPager.java index 9831d8d1ee..7b3b1bf94f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/UsersPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/UsersPager.java @@ -37,21 +37,21 @@ * Paging through a collection of users. */ public class UsersPager extends AbstractPager { - + private static Log log = LogFactory.getLog(UsersPager.class); - + private String letter = null; private String locale = null; private int sinceDays = -1; private int length = 0; - + // collection for the pager private List users; - + // are there more items? private boolean more = false; - - + + public UsersPager( URLStrategy strat, String baseUrl, @@ -59,18 +59,18 @@ public UsersPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public UsersPager( URLStrategy strat, String baseUrl, @@ -79,19 +79,19 @@ public UsersPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.letter = letter; this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public String getNextLink() { // need to add letter param if it exists if(letter != null) { @@ -107,8 +107,8 @@ public String getNextLink() { return super.getNextLink(); } } - - + + public String getPrevLink() { // need to add letter param if it exists if(letter != null) { @@ -124,14 +124,14 @@ public String getPrevLink() { return super.getPrevLink(); } } - - + + public List getItems() { - + if (users == null) { // calculate offset int offset = getPage() * length; - + List results = new ArrayList(); try { Weblogger roller = WebloggerFactory.getWeblogger(); @@ -142,7 +142,7 @@ public List getItems() { } else { rawUsers = umgr.getUsersByLetter(letter.charAt(0), offset, length + 1); } - + // wrap the results int count = 0; for (Iterator it = rawUsers.iterator(); it.hasNext();) { @@ -153,20 +153,20 @@ public List getItems() { more = true; } } - + } catch (Exception e) { log.error("ERROR: fetching user list", e); } - + users = results; } - + return users; } - - + + public boolean hasMoreItems() { return more; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesDayPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesDayPager.java index 979ec538d1..fa16229bd4 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesDayPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesDayPager.java @@ -43,22 +43,22 @@ * */ public class WeblogEntriesDayPager extends AbstractWeblogEntriesPager { - + private static Log log = LogFactory.getLog(WeblogEntriesDayPager.class); - + private SimpleDateFormat dayFormat = new SimpleDateFormat(); - + private Date day; private Date nextDay; private Date prevDay; - + // collection for the pager private Map entries = null; - + // are there more pages? private boolean more = false; - - + + public WeblogEntriesDayPager( URLStrategy strat, Weblog weblog, @@ -69,18 +69,18 @@ public WeblogEntriesDayPager( String catPath, List tags, int page) { - + super(strat, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags, page); - + dayFormat = new SimpleDateFormat( messageUtils.getString("weblogEntriesPager.day.dateFormat")); - + getEntries(); - + day = parseDate(dateString); - + Calendar cal = Calendar.getInstance(); - + cal.setTime(day); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR, 0); @@ -90,7 +90,7 @@ public WeblogEntriesDayPager( if (nextDay.after(getToday())) { nextDay = null; } - + cal.setTime(day); cal.add(Calendar.DAY_OF_MONTH, -1); cal.set(Calendar.HOUR, 23); @@ -102,8 +102,8 @@ public WeblogEntriesDayPager( prevDay = null; } } - - + + public Map getEntries() { Date date = parseDate(dateString); Calendar cal = Calendar.getInstance(weblog.getTimeZoneInstance()); @@ -111,30 +111,30 @@ public Map getEntries() { Date endDate = date; startDate = DateUtil.getStartOfDay(endDate, cal); endDate = DateUtil.getEndOfDay(endDate, cal); - + if (entries == null) { entries = new TreeMap(new ReverseComparator()); try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); Map mmap = WebloggerFactory.getWeblogger().getWeblogEntryManager().getWeblogEntryObjectMap( - + weblog, startDate, endDate, catPath, - tags,WeblogEntry.PUBLISHED, + tags,WeblogEntry.PUBLISHED, locale, - offset, + offset, length + 1); - + // need to wrap pojos int count = 0; Date key = null; Iterator days = mmap.keySet().iterator(); while(days.hasNext()) { key = (Date) days.next(); - + // now we need to go through each entry in a day and wrap List wrapped = new ArrayList(); List unwrapped = (List) mmap.get(key); @@ -145,64 +145,64 @@ public Map getEntries() { more = true; } } - + // done with that day, put it in the map if(wrapped.size() > 0) { entries.put(key, wrapped); } } - - + + } catch (Exception e) { log.error("ERROR: getting entry month map", e); } } return entries; } - - + + public String getHomeLink() { return createURL(0, 0, weblog, locale, pageLink, null, null, catPath, tags); } - - + + public String getHomeName() { return messageUtils.getString("weblogEntriesPager.day.home"); } - - + + public String getNextLink() { if (more) { return createURL(page, 1, weblog, locale, pageLink, null, dateString, catPath, tags); } return null; } - - + + public String getNextName() { if (getNextLink() != null) { return messageUtils.getString("weblogEntriesPager.day.next", new Object[] {dayFormat.format(day)}); } return null; } - - + + public String getPrevLink() { if (page > 0) { return createURL(page, -1, weblog, locale, pageLink, null, dateString, catPath, tags); } return null; } - - + + public String getPrevName() { if (getPrevLink() != null) { return messageUtils.getString("weblogEntriesPager.day.prev", new Object[] {dayFormat.format(day)}); } return null; } - - + + public String getNextCollectionLink() { if (nextDay != null) { String next = DateUtil.format8chars(nextDay); @@ -210,16 +210,16 @@ public String getNextCollectionLink() { } return null; } - - + + public String getNextCollectionName() { if (nextDay != null) { return messageUtils.getString("weblogEntriesPager.day.nextCollection", new Object[] {dayFormat.format(nextDay)}); } return null; } - - + + public String getPrevCollectionLink() { if (prevDay != null) { String prev = DateUtil.format8chars(prevDay); @@ -227,13 +227,13 @@ public String getPrevCollectionLink() { } return null; } - - + + public String getPrevCollectionName() { if (prevDay != null) { return messageUtils.getString("weblogEntriesPager.day.prevCollection", new Object[] {dayFormat.format(prevDay)}); } return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesLatestPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesLatestPager.java index 1869c3eb5c..4a2af60f0f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesLatestPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesLatestPager.java @@ -40,16 +40,16 @@ * A pager over a collection of recent weblog entries. */ public class WeblogEntriesLatestPager extends AbstractWeblogEntriesPager { - + private static Log log = LogFactory.getLog(WeblogEntriesLatestPager.class); - + // collection for the pager private Map entries = null; - + // are there more pages? private boolean more = false; - - + + public WeblogEntriesLatestPager( URLStrategy strat, Weblog weblog, @@ -60,16 +60,16 @@ public WeblogEntriesLatestPager( String catPath, List tags, int page) { - + super(strat, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags, page); - + // initialize the pager collection getEntries(); } - - + + public Map getEntries() { - + if (entries == null) { entries = new TreeMap(new ReverseComparator()); try { @@ -85,14 +85,14 @@ public Map getEntries() { locale, offset, length + 1); - + // need to wrap pojos int count = 0; java.util.Date key = null; Iterator days = mmap.keySet().iterator(); while(days.hasNext()) { key = (java.util.Date)days.next(); - + // now we need to go through each entry in a day and wrap List wrapped = new ArrayList(); List unwrapped= (List) mmap.get(key); @@ -103,7 +103,7 @@ public Map getEntries() { more = true; } } - + // done with that day, put it in the map if(wrapped.size() > 0) { entries.put(key, wrapped); @@ -113,13 +113,13 @@ public Map getEntries() { log.error("ERROR: getting entry month map", e); } } - + return entries; } - - + + public boolean hasMoreEntries() { return more; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesListPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesListPager.java index 00e9251d65..1be93abe97 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesListPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesListPager.java @@ -41,28 +41,28 @@ * Simple pager for list of weblog entries. */ public class WeblogEntriesListPager extends AbstractPager { - + private static Log log = LogFactory.getLog(WeblogEntriesListPager.class); - + private String locale = null; private int sinceDays = -1; private int length = 0; - + private Weblog queryWeblog = null; private User queryUser = null; private String queryCat = null; private List queryTags = null; - + // entries for the pager private List entries; - + // are there more entries? private boolean more = false; - + // most recent update time of current set of entries - private Date lastUpdated = null; - - + private Date lastUpdated = null; + + public WeblogEntriesListPager( URLStrategy strat, String baseUrl, @@ -74,9 +74,9 @@ public WeblogEntriesListPager( int sinceDays, int pageNum, int length) { - + super(strat, baseUrl, pageNum); - + // store the data this.queryWeblog = queryWeblog; this.queryUser = queryUser; @@ -85,20 +85,20 @@ public WeblogEntriesListPager( this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the pager collection getItems(); } - - + + public List getItems() { - + if (entries == null) { // calculate offset int offset = getPage() * length; - + List results = new ArrayList(); - + Date startDate = null; if(sinceDays > 0) { Calendar cal = Calendar.getInstance(); @@ -106,13 +106,13 @@ public List getItems() { cal.add(Calendar.DATE, -1 * sinceDays); startDate = cal.getTime(); } - + try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); UserManager umgr = roller.getUserManager(); List rawEntries = wmgr.getWeblogEntries( - + queryWeblog, queryUser, startDate, @@ -125,7 +125,7 @@ public List getItems() { locale, offset, length + 1); - + // wrap the results int count = 0; for (Iterator it = rawEntries.iterator(); it.hasNext();) { @@ -135,18 +135,18 @@ public List getItems() { } } if (rawEntries.size() > length) more = true; - + } catch (Exception e) { log.error("ERROR: fetching weblog entries list", e); } - + entries = results; } - + return entries; } - - + + public boolean hasMoreItems() { return more; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesMonthPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesMonthPager.java index 323c48e3fb..2faefd8661 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesMonthPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesMonthPager.java @@ -41,22 +41,22 @@ * */ public class WeblogEntriesMonthPager extends AbstractWeblogEntriesPager { - + private static Log log = LogFactory.getLog(WeblogEntriesMonthPager.class); - + private SimpleDateFormat monthFormat = new SimpleDateFormat(); - + private Date month; private Date nextMonth; private Date prevMonth; - + // collection for the pager private Map entries = null; - + // are there more pages? private boolean more = false; - - + + public WeblogEntriesMonthPager( URLStrategy strat, Weblog weblog, @@ -67,25 +67,25 @@ public WeblogEntriesMonthPager( String catPath, List tags, int page) { - + super(strat, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags, page); - + monthFormat = new SimpleDateFormat( messageUtils.getString("weblogEntriesPager.month.dateFormat")); - + getEntries(); - + month = parseDate(dateString); - + Calendar cal = Calendar.getInstance(); - + cal.setTime(month); cal.add(Calendar.MONTH, 1); nextMonth = cal.getTime(); if (nextMonth.after(getToday())) { nextMonth = null; } - + cal.setTime(month); cal.add(Calendar.MONTH, -1); prevMonth = cal.getTime(); @@ -95,8 +95,8 @@ public WeblogEntriesMonthPager( prevMonth = null; } } - - + + public Map getEntries() { Date date = parseDate(dateString); Calendar cal = Calendar.getInstance(weblog.getTimeZoneInstance()); @@ -105,21 +105,21 @@ public Map getEntries() { date = cal.getTime(); Date startDate = DateUtil.getStartOfMonth(date, cal); Date endDate = DateUtil.getEndOfMonth(date, cal); - + if (entries == null) { entries = new TreeMap(new ReverseComparator()); try { Map mmap = WebloggerFactory.getWeblogger().getWeblogEntryManager().getWeblogEntryObjectMap( - + weblog, startDate, endDate, catPath, - tags,WeblogEntry.PUBLISHED, + tags,WeblogEntry.PUBLISHED, locale, - offset, + offset, length + 1); - + // need to wrap pojos int count = 0; java.util.Date key = null; @@ -137,7 +137,7 @@ public Map getEntries() { more = true; } } - + // done with that day, put it in the map if(wrapped.size() > 0) { entries.put(key, wrapped); @@ -149,50 +149,50 @@ public Map getEntries() { } return entries; } - - + + public String getHomeLink() { return createURL(0, 0, weblog, locale, pageLink, null, null, catPath, tags); } - - + + public String getHomeName() { return messageUtils.getString("weblogEntriesPager.month.home"); } - - + + public String getNextLink() { if (more) { return createURL(page, 1, weblog, locale, pageLink, null, dateString, catPath, tags); } return null; } - - + + public String getNextName() { if (getNextLink() != null) { return messageUtils.getString("weblogEntriesPager.month.next", new Object[] {monthFormat.format(month)}); } return null; } - - + + public String getPrevLink() { if (offset > 0) { return createURL(page, -1, weblog, locale, pageLink, null, dateString, catPath, tags); } return null; } - - + + public String getPrevName() { if (getPrevLink() != null) { return messageUtils.getString("weblogEntriesPager.month.prev", new Object[] {monthFormat.format(month)}); } return null; } - - + + public String getNextCollectionLink() { if (nextMonth != null) { String next = DateUtil.format6chars(nextMonth); @@ -200,16 +200,16 @@ public String getNextCollectionLink() { } return null; } - - + + public String getNextCollectionName() { if (nextMonth != null) { return messageUtils.getString("weblogEntriesPager.month.nextCollection", new Object[] {monthFormat.format(nextMonth)}); } return null; } - - + + public String getPrevCollectionLink() { if (prevMonth != null) { String prev = DateUtil.format6chars(prevMonth); @@ -217,13 +217,13 @@ public String getPrevCollectionLink() { } return null; } - - + + public String getPrevCollectionName() { if (prevMonth != null) { return messageUtils.getString("weblogEntriesPager.month.prevCollection", new Object[] {monthFormat.format(prevMonth)}); } return null; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPager.java index dc6fd4ea5e..1475bb36f7 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPager.java @@ -22,11 +22,11 @@ /** * Pager for weblog entries, handles latest, single-entry, month and day views. - * Collection returned is a list of lists of entries, where each list of + * Collection returned is a list of lists of entries, where each list of * entries represents one day. */ -public interface WeblogEntriesPager { - +public interface WeblogEntriesPager { + /** * A map of entries representing this collection. * @@ -34,7 +34,7 @@ public interface WeblogEntriesPager { * entry objects keyed by the date they were published. */ public Map getEntries(); - + /** * Link value for returning to pager home */ @@ -64,26 +64,26 @@ public interface WeblogEntriesPager { * Link value for prev page in current collection view */ public String getPrevName(); - + /** * Link value for next collection view */ public String getNextCollectionLink(); - + /** * Name for next collection view */ - public String getNextCollectionName(); - + public String getNextCollectionName(); + /** * Link value for prev collection view */ - public String getPrevCollectionLink(); - + public String getPrevCollectionLink(); + /** * Name for prev collection view */ - public String getPrevCollectionName(); - + public String getPrevCollectionName(); + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPermalinkPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPermalinkPager.java index 8cb36cf1a0..cfeabafd9c 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPermalinkPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPermalinkPager.java @@ -40,17 +40,17 @@ * */ public class WeblogEntriesPermalinkPager extends AbstractWeblogEntriesPager { - + private static Log log = LogFactory.getLog(WeblogEntriesPermalinkPager.class); - + WeblogEntry currEntry = null; WeblogEntry nextEntry = null; WeblogEntry prevEntry = null; - + // collection for the pager Map entries = null; - - + + public WeblogEntriesPermalinkPager( URLStrategy strat, Weblog weblog, @@ -61,13 +61,13 @@ public WeblogEntriesPermalinkPager( String catPath, List tags, int page) { - + super(strat, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags, page); - + getEntries(); } - - + + public Map getEntries() { if (entries == null) try { Weblogger roller = WebloggerFactory.getWeblogger(); @@ -82,29 +82,29 @@ public Map getEntries() { } - + return entries; } - - + + public String getHomeLink() { return createURL(0, 0, weblog, locale, pageLink, null, dateString, catPath, tags); } - - + + public String getHomeName() { return messageUtils.getString("weblogEntriesPager.single.home"); } - - + + public String getNextLink() { if (getNextEntry() != null) { return createURL(0, 0, weblog, locale, pageLink, nextEntry.getAnchor(), dateString, catPath, tags); } return null; } - - + + public String getNextName() { if (getNextEntry() != null) { String title = Utilities.truncateNicely(getNextEntry().getTitle(), 15, 20, "..."); @@ -112,16 +112,16 @@ public String getNextName() { } return null; } - - + + public String getPrevLink() { if (getPrevEntry() != null) { return createURL(0, 0, weblog, locale, pageLink, prevEntry.getAnchor(), dateString, catPath, tags); } return null; } - - + + public String getPrevName() { if (getPrevEntry() != null) { String title = Utilities.truncateNicely(getPrevEntry().getTitle(), 15, 20, "..."); @@ -129,8 +129,8 @@ public String getPrevName() { } return null; } - - + + private WeblogEntry getNextEntry() { if (nextEntry == null) try { Weblogger roller = WebloggerFactory.getWeblogger(); @@ -147,8 +147,8 @@ private WeblogEntry getNextEntry() { return nextEntry; } - - + + private WeblogEntry getPrevEntry() { if (prevEntry == null) try { Weblogger roller = WebloggerFactory.getWeblogger(); @@ -165,5 +165,5 @@ private WeblogEntry getPrevEntry() { return prevEntry; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPreviewPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPreviewPager.java index 37713076bd..db0b5dc9cb 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPreviewPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogEntriesPreviewPager.java @@ -42,10 +42,10 @@ * like entries in DRAFT mode. */ public class WeblogEntriesPreviewPager extends WeblogEntriesPermalinkPager { - + private static Log log = LogFactory.getLog(WeblogEntriesPreviewPager.class); - - + + public WeblogEntriesPreviewPager( URLStrategy strat, Weblog weblog, @@ -56,27 +56,27 @@ public WeblogEntriesPreviewPager( String catPath, List tags, int page) { - + super(strat, weblog, locale, pageLink, entryAnchor, dateString, catPath, tags, page); } - - + + public Map getEntries() { if (entries == null) try { Weblogger roller = WebloggerFactory.getWeblogger(); WeblogEntryManager wmgr = roller.getWeblogEntryManager(); currEntry = wmgr.getWeblogEntryByAnchor(weblog, entryAnchor); if (currEntry != null) { - + // clone the entry since we don't want to work with the real pojo WeblogEntry tmpEntry = new WeblogEntry(); tmpEntry.setData(currEntry); - + // set the pubtime to the current time if it is unset if(tmpEntry.getPubTime() == null) { tmpEntry.setPubTime(new Timestamp(System.currentTimeMillis())); } - + // store the entry in the collection entries = new TreeMap(); entries.put(tmpEntry.getPubTime(),Collections.singletonList(WeblogEntryWrapper.wrap(tmpEntry, urlStrategy))); @@ -86,8 +86,8 @@ public Map getEntries() { } - + return entries; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogsPager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogsPager.java index 22be133b29..a520fd1770 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogsPager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/pagers/WeblogsPager.java @@ -40,21 +40,21 @@ * Paging through a collection of weblogs. */ public class WeblogsPager extends AbstractPager { - + private static Log log = LogFactory.getLog(WeblogsPager.class); - + private String letter = null; private String locale = null; private int sinceDays = -1; private int length = 0; - + // collection for the pager private List weblogs; - + // are there more items? private boolean more = false; - - + + public WeblogsPager( URLStrategy strat, String baseUrl, @@ -62,18 +62,18 @@ public WeblogsPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public WeblogsPager( URLStrategy strat, String baseUrl, @@ -82,19 +82,19 @@ public WeblogsPager( int sinceDays, int page, int length) { - + super(strat, baseUrl, page); - + this.letter = letter; this.locale = locale; this.sinceDays = sinceDays; this.length = length; - + // initialize the collection getItems(); } - - + + public String getNextLink() { // need to add letter param if it exists if(letter != null) { @@ -110,8 +110,8 @@ public String getNextLink() { return super.getNextLink(); } } - - + + public String getPrevLink() { // need to add letter param if it exists if(letter != null) { @@ -127,14 +127,14 @@ public String getPrevLink() { return super.getPrevLink(); } } - - + + public List getItems() { - + if (weblogs == null) { // calculate offset int offset = getPage() * length; - + List results = new ArrayList(); Date startDate = null; if (sinceDays != -1) { @@ -152,31 +152,31 @@ public List getItems() { } else { rawWeblogs = wmgr.getWeblogsByLetter(letter.charAt(0), offset, length + 1); } - + // wrap the results int count = 0; for (Iterator it = rawWeblogs.iterator(); it.hasNext();) { Weblog website = (Weblog) it.next(); if (count++ < length) { - results.add(WeblogWrapper.wrap(website, urlStrategy)); + results.add(WeblogWrapper.wrap(website, urlStrategy)); } else { more = true; } } - + } catch (Exception e) { log.error("ERROR: fetching weblog list", e); } - + weblogs = results; } - + return weblogs; } - - + + public boolean hasMoreItems() { return more; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/AkismetCommentValidator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/AkismetCommentValidator.java index 24ef75c400..b9a28f618b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/AkismetCommentValidator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/AkismetCommentValidator.java @@ -39,11 +39,11 @@ * You can get a free personal use key by registering as a user at wordpress.com. * See Akismet site for API details (http://akismet.com/development/api/) */ -public class AkismetCommentValidator implements CommentValidator { - private static Log log = LogFactory.getLog(AkismetCommentValidator.class); +public class AkismetCommentValidator implements CommentValidator { + private static Log log = LogFactory.getLog(AkismetCommentValidator.class); private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); private String apikey; - + /** Creates a new instance of AkismetCommentValidator */ public AkismetCommentValidator() { apikey = WebloggerConfig.getProperty("comment.validator.akismet.apikey"); @@ -72,8 +72,8 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { URLConnection conn = url.openConnection(); conn.setDoOutput(true); - conn.setRequestProperty("User_Agent", "Roller " + WebloggerFactory.getWeblogger().getVersion()); - conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8"); + conn.setRequestProperty("User_Agent", "Roller " + WebloggerFactory.getWeblogger().getVersion()); + conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8"); conn.setRequestProperty("Content-length", Integer.toString(sb.length())); OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream()); @@ -81,7 +81,7 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { osr.flush(); osr.close(); - BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = br.readLine(); if ("true".equals(response)) { messages.addError("comment.validator.akismetMessage"); @@ -91,7 +91,7 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { } catch (Exception e) { log.error("ERROR checking comment against Akismet", e); } - return 0; // interpret error as spam: better safe than sorry? + return 0; // interpret error as spam: better safe than sorry? } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/BlacklistCommentValidator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/BlacklistCommentValidator.java index 8dfd434181..1f279f407d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/BlacklistCommentValidator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/BlacklistCommentValidator.java @@ -27,7 +27,7 @@ * Validates comment if comment does not contain blacklisted words. */ public class BlacklistCommentValidator implements CommentValidator { - private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); + private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); private BlacklistChecker checker = new BlacklistChecker(); public String getName() { @@ -39,7 +39,7 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { messages.addError("comment.validator.blacklistMessage"); return 0; } - return 100; + return 100; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentAuthenticator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentAuthenticator.java index e3dcacf6c5..6794add378 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentAuthenticator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentAuthenticator.java @@ -25,8 +25,8 @@ * Interface for comment authentication plugin. */ public interface CommentAuthenticator { - - + + /** * Plugin should write out HTML for the form fields and other UI elements * needed to display the comment authentication widget. @@ -34,15 +34,15 @@ public interface CommentAuthenticator { * @param request comment form request object */ public String getHtml(HttpServletRequest request); - - + + /** - * Plugin should return true only if comment posting passes the + * Plugin should return true only if comment posting passes the * authentication test. * * @param request comment posting request object * @return true if authentication passed, false otherwise */ public boolean authenticate(HttpServletRequest request); - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidationManager.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidationManager.java index 4b6e8d4afc..74f36cd67a 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidationManager.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidationManager.java @@ -36,9 +36,9 @@ public class CommentValidationManager { private static Log log = LogFactory.getLog(CommentValidationManager.class); private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); private List validators = new ArrayList(); - + public CommentValidationManager() { - + // instantiate the validators that are configured try { String vals = WebloggerConfig.getProperty("comment.validator.classnames"); @@ -57,27 +57,27 @@ public CommentValidationManager() { log.warn("Error accessing comment validator: " + valsarray[i]); } } - + } catch (Exception e) { log.error("Error instantiating comment validators"); } log.info("Configured " + validators.size() + " CommentValidators"); } - + /** * Add validator to those managed by this manager (testing purposes). */ public void addCommentValidator(CommentValidator val) { validators.add(val); } - + /** * Return total number of validators (for teasting purposes). */ public int getValidatorCount() { return validators.size(); } - + /** * @param comment Comment to be validated * @param messages Messages object to which errors will be added @@ -98,5 +98,5 @@ public int validateComment(WeblogEntryComment comment, RollerMessages messages) } return total; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidator.java index 7f4bc78f8c..830cfe18af 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/CommentValidator.java @@ -23,8 +23,8 @@ import org.apache.roller.weblogger.util.RollerMessages; /** Interface for comment validation plugin */ -public interface CommentValidator { - +public interface CommentValidator { + /** * Plain text name of validator for display purposes. */ @@ -35,5 +35,5 @@ public interface CommentValidator { * @param messages Messages object to which errors will added * @return Number indicating confidence that comment is valid (100 meaning 100%) */ - public int validate(WeblogEntryComment comment, RollerMessages messages); + public int validate(WeblogEntryComment comment, RollerMessages messages); } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/DefaultCommentAuthenticator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/DefaultCommentAuthenticator.java index ea60540f75..f0f6563a61 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/DefaultCommentAuthenticator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/DefaultCommentAuthenticator.java @@ -25,15 +25,15 @@ * Default authenticator does nothing, always returns true. */ public class DefaultCommentAuthenticator implements CommentAuthenticator { - - + + public String getHtml(HttpServletRequest request) { return ""; } - - + + public boolean authenticate(HttpServletRequest request) { return true; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/ExcessLinksCommentValidator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/ExcessLinksCommentValidator.java index f171af9f02..847b9c77f6 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/ExcessLinksCommentValidator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/ExcessLinksCommentValidator.java @@ -29,14 +29,14 @@ * Validates comment only if it has fewer links than comment.validator.excessSize.threshold */ public class ExcessLinksCommentValidator implements CommentValidator { - private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); - private Pattern linkPattern = Pattern.compile(""); sb.append(bundle.getString("comments.mathAuthenticatorQuestion")); sb.append("

    "); @@ -71,23 +71,23 @@ public String getHtml(HttpServletRequest request) { sb.append("

    "); - + return sb.toString(); } - - + + public boolean authenticate(HttpServletRequest request) { - + boolean authentic = false; - + HttpSession session = request.getSession(false); String answerString = request.getParameter("answer"); - + if (answerString != null && session != null) { try { int answer = Integer.parseInt(answerString); Integer sum = (Integer) session.getAttribute("mathAnswer"); - + if (sum != null && answer == sum.intValue()) { authentic = true; session.removeAttribute("mathAnswer"); @@ -101,9 +101,9 @@ public boolean authenticate(HttpServletRequest request) { mLogger.error(e); } } - + return authentic; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/TrackbackLinkbackCommentValidator.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/TrackbackLinkbackCommentValidator.java index 66bbc39bf9..c751b52b50 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/TrackbackLinkbackCommentValidator.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/TrackbackLinkbackCommentValidator.java @@ -32,21 +32,21 @@ * intended for use with trackbacks only. */ public class TrackbackLinkbackCommentValidator implements CommentValidator { - + private ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources"); - + public String getName() { return bundle.getString("comment.validator.trackbackLinkbackName"); } - + public int validate(WeblogEntryComment comment, RollerMessages messages) { - + // linkback validation can be toggled at runtime, so check if it's enabled // if it's disabled then just return a score of 100 if(!WebloggerRuntimeConfig.getBooleanProperty("site.trackbackVerification.enabled")) { return 100; } - + int ret = 0; LinkbackExtractor linkback = null; try { @@ -59,7 +59,7 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { true)); } catch (MalformedURLException ignored1) { } catch (IOException ignored2) {} - + if (linkback != null && linkback.getExcerpt() != null) { ret = 100; } else { @@ -67,5 +67,5 @@ public int validate(WeblogEntryComment comment, RollerMessages messages) { } return ret; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/CommentServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/CommentServlet.java index 039a883886..2035cb3142 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/CommentServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/CommentServlet.java @@ -16,7 +16,7 @@ * directory of this distribution. */ -package org.apache.roller.weblogger.ui.rendering.servlets; +package org.apache.roller.weblogger.ui.rendering.servlets; import java.io.IOException; import java.sql.Timestamp; @@ -67,24 +67,24 @@ * email sent to the blog owner and all who have commented on the same post. */ public class CommentServlet extends HttpServlet { - + private static Log log = LogFactory.getLog(CommentServlet.class); - + private CommentAuthenticator authenticator = null; private CommentValidationManager commentValidationManager = null; private GenericThrottle commentThrottle = null; - - + + /** * Initialization. */ @Override public void init(ServletConfig servletConfig) throws ServletException { - + super.init(servletConfig); - + log.info("Initializing CommentServlet"); - + // lookup the authenticator we are going to use and instantiate it try { String name = WebloggerConfig.getProperty("comment.authenticator.classname"); @@ -94,24 +94,24 @@ public void init(ServletConfig servletConfig) throws ServletException { log.error(e); this.authenticator = new DefaultCommentAuthenticator(); } - + // instantiate a comment validation manager for comment spam checking commentValidationManager = new CommentValidationManager(); - + // instantiate a comment format manager for comment formatting String fmtrs = WebloggerConfig.getProperty("comment.formatter.classnames"); String[] formatters = Utilities.stringToStringArray(fmtrs, ","); - + // are we doing throttling? if(WebloggerConfig.getBooleanProperty("comment.throttle.enabled")) { - + int threshold = 25; try { threshold = Integer.parseInt(WebloggerConfig.getProperty("comment.throttle.threshold")); } catch(Exception e) { log.warn("bad input for config property comment.throttle.threshold", e); } - + int interval = 60000; try { interval = Integer.parseInt(WebloggerConfig.getProperty("comment.throttle.interval")); @@ -120,23 +120,23 @@ public void init(ServletConfig servletConfig) throws ServletException { } catch(Exception e) { log.warn("bad input for config property comment.throttle.interval", e); } - + int maxEntries = 250; try { maxEntries = Integer.parseInt(WebloggerConfig.getProperty("comment.throttle.maxentries")); } catch(Exception e) { log.warn("bad input for config property comment.throttle.maxentries", e); } - + commentThrottle = new GenericThrottle(threshold, interval, maxEntries); - + log.info("Comment Throttling ENABLED"); } else { log.info("Comment Throttling DISABLED"); } } - - + + /** * Handle incoming http GET requests. * @@ -147,8 +147,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.sendError(HttpServletResponse.SC_NOT_FOUND); } - - + + /** * Service incoming POST requests. * @@ -157,16 +157,16 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - + String error = null; String dispatch_url = null; - + Weblog weblog = null; WeblogEntry entry = null; - + String message = null; RollerMessages messages = new RollerMessages(); - + // are we doing a preview? or a post? String method = request.getParameter("method"); final boolean preview; @@ -178,54 +178,54 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) preview = false; log.debug("Handling regular comment post"); } - + // throttling protection against spammers if(commentThrottle != null && commentThrottle.processHit(request.getRemoteAddr())) { - + log.debug("ABUSIVE "+request.getRemoteAddr()); IPBanList.getInstance().addBannedIp(request.getRemoteAddr()); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + WeblogCommentRequest commentRequest = null; try { commentRequest = new WeblogCommentRequest(request); - + // lookup weblog specified by comment request weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(commentRequest.getWeblogHandle()); - + if(weblog == null) { throw new WebloggerException("unable to lookup weblog: "+ commentRequest.getWeblogHandle()); } - + // lookup entry specified by comment request entry = commentRequest.getWeblogEntry(); if(entry == null) { throw new WebloggerException("unable to lookup entry: "+ commentRequest.getWeblogAnchor()); } - + // we know what the weblog entry is, so setup our urls dispatch_url = "/roller-ui/rendering/page/"+weblog.getHandle(); if(commentRequest.getLocale() != null) { dispatch_url += "/"+commentRequest.getLocale(); } dispatch_url += "/entry/"+URLUtilities.encode(commentRequest.getWeblogAnchor()); - + } catch (Exception e) { // some kind of error parsing the request or looking up weblog log.debug("error creating page request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + log.debug("Doing comment posting for entry = "+entry.getPermalink()); - + // collect input from request params and construct new comment object // fields: name, email, url, content, notify // TODO: data validation on collected comment data @@ -238,36 +238,36 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) comment.setWeblogEntry(entry); comment.setRemoteHost(request.getRemoteHost()); comment.setPostTime(new Timestamp(System.currentTimeMillis())); - + // set comment content-type depending on if html is allowed if(WebloggerRuntimeConfig.getBooleanProperty("users.comments.htmlenabled")) { comment.setContentType("text/html"); } else { comment.setContentType("text/plain"); } - + // set whatever comment plugins are configured comment.setPlugins(WebloggerRuntimeConfig.getProperty("users.comments.plugins")); - + WeblogEntryCommentForm cf = new WeblogEntryCommentForm(); cf.setData(comment); if (preview) { cf.setPreview(comment); } - + I18nMessages messageUtils = I18nMessages.getMessages(commentRequest.getLocaleInstance()); - + // check if comments are allowed for this entry // this checks site-wide settings, weblog settings, and entry settings if(!entry.getCommentsStillAllowed() || !entry.isPublished()) { error = messageUtils.getString("comments.disabled"); - + // if this is a real comment post then authenticate request } else if(!preview && !this.authenticator.authenticate(request)) { error = messageUtils.getString("error.commentAuthFailed"); log.debug("Comment failed authentication"); } - + // bail now if we have already found an error if(error != null) { cf.setError(error); @@ -276,12 +276,12 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) dispatcher.forward(request, response); return; } - + int validationScore = commentValidationManager.validateComment(comment, messages); log.debug("Comment Validation score: " + validationScore); - + if (!preview) { - + if (validationScore == 100 && weblog.getCommentModerationRequired()) { // Valid comments go into moderation if required comment.setStatus(WeblogEntryComment.PENDING); @@ -295,17 +295,17 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) log.debug("Comment marked as spam"); comment.setStatus(WeblogEntryComment.SPAM); error = messageUtils.getString("commentServlet.commentMarkedAsSpam"); - + // add specific error messages if they exist if(messages.getErrorCount() > 0) { Iterator errors = messages.getErrors(); RollerMessage errorKey = null; - + StringBuilder buf = new StringBuilder(); buf.append("
      "); while(errors.hasNext()) { errorKey = (RollerMessage)errors.next(); - + buf.append("
    • "); if(errorKey.getArgs() != null) { buf.append(messageUtils.getString(errorKey.getKey(), errorKey.getArgs())); @@ -315,51 +315,51 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) buf.append("
    • "); } buf.append("
    "); - + error += buf.toString(); } - + } - - try { + + try { if(!WeblogEntryComment.SPAM.equals(comment.getStatus()) || !WebloggerRuntimeConfig.getBooleanProperty("comments.ignoreSpam.enabled")) { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.saveComment(comment); WebloggerFactory.getWeblogger().flush(); - + // Send email notifications only to subscribers if comment is 100% valid boolean notifySubscribers = (validationScore == 100); MailUtil.sendEmailNotification(comment, messages, messageUtils, notifySubscribers); - + // only re-index/invalidate the cache if comment isn't moderated if(!weblog.getCommentModerationRequired()) { IndexManager manager = WebloggerFactory.getWeblogger().getIndexManager(); - + // remove entry before (re)adding it, or in case it isn't Published manager.removeEntryIndexOperation(entry); - + // if published, index the entry if (entry.isPublished()) { manager.addEntryIndexOperation(entry); } - + // Clear all caches associated with comment CacheManager.invalidate(comment); } - + // comment was successful, clear the comment form cf = new WeblogEntryCommentForm(); } - + } catch (WebloggerException re) { log.error("Error saving comment", re); error = re.getMessage(); } } - - + + // the work has been done, now send the user back to the entry page if (error != null) { cf.setError(error); @@ -368,11 +368,11 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) cf.setMessage(message); } request.setAttribute("commentForm", cf); - + log.debug("comment processed, forwarding to "+dispatch_url); RequestDispatcher dispatcher = request.getRequestDispatcher(dispatch_url); dispatcher.forward(request, response); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java index 3d6ebdbc07..fc22858299 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java @@ -133,8 +133,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) if (WebloggerRuntimeConfig.getBooleanProperty("site.newsfeeds.styledFeeds") && accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null && userAgent.startsWith("Mozilla")) { - // client is a browser and feed style is enabled so we want - // browsers to load the page rather than popping up the download + // client is a browser and feed style is enabled so we want + // browsers to load the page rather than popping up the download // dialog, so we provide a content-type that browsers will display response.setContentType("text/xml"); } else if("rss".equals(feedRequest.getFormat())) { @@ -169,27 +169,27 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } else { log.debug("MISS "+cacheKey); } - - + + // validation. make sure that request input makes sense. boolean invalid = false; if(feedRequest.getLocale() != null) { - + // locale view only allowed if weblog has enabled it if(!feedRequest.getWeblog().isEnableMultiLang()) { invalid = true; } - + } if(feedRequest.getWeblogCategoryName() != null) { - + // category specified. category must exist. if(feedRequest.getWeblogCategory() == null) { invalid = true; } - + } else if(feedRequest.getTags() != null && feedRequest.getTags().size() > 0) { - + try { // tags specified. make sure they exist. WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -198,19 +198,19 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) invalid = true; } } - + if(invalid) { if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // do we need to force a specific locale for the request? if(feedRequest.getLocale() == null && !weblog.isShowAllLangs()) { feedRequest.setLocale(weblog.getLocale()); } - + // looks like we need to render content HashMap model = new HashMap(); String pageId = null; @@ -236,7 +236,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); - + // Load models for feeds String feedModels = WebloggerConfig.getProperty("rendering.feedModels"); ModelLoader.loadModels(feedModels, model, initData, true); @@ -250,11 +250,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); - + // Load search models if search feed - if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { + if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { ModelLoader.loadModels(SearchResultsFeedModel.class.getName(), model, initData, true); - } + } } catch (WebloggerException ex) { log.error("ERROR loading model for page", ex); diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceServlet.java index 63cfc08297..b3ca9bfae3 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceServlet.java @@ -52,12 +52,12 @@ public class MediaResourceServlet extends HttpServlet { private static Log log = LogFactory.getLog(MediaResourceServlet.class); - + public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing ResourceServlet"); - + } /** @@ -65,7 +65,7 @@ public void init(ServletConfig config) throws ServletException { */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + MediaFileManager mfMgr = WebloggerFactory.getWeblogger().getMediaFileManager(); Weblog weblog = null; @@ -90,15 +90,15 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + long resourceLastMod = 0; InputStream resourceStream = null; MediaFile mediaFile = null; - + try { mediaFile = mfMgr.getMediaFile(resourceRequest.getResourceId(), true); resourceLastMod = mediaFile.getLastModified(); - + } catch (Exception ex) { // still not found? then we don't have it, 404. log.debug("Unable to get resource", ex); @@ -113,7 +113,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod); } - + // set the content type based on whatever is in our web.xml mime defs if (resourceRequest.isThumbnail()) { @@ -143,10 +143,10 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) while((length = resourceStream.read(buf)) > 0) { out.write(buf, 0, length); } - + // close output stream out.close(); - + } catch (Throwable ex) { log.error("ERROR",ex); if(!response.isCommitted()) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PageServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PageServlet.java index fe8dd1b5a4..43905801e9 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PageServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PageServlet.java @@ -73,7 +73,7 @@ public class PageServlet extends HttpServlet { private boolean excludeOwnerPages = false; private WeblogPageCache weblogPageCache = null; private SiteWideCache siteWideCache = null; - + // Development theme reloading Boolean themeReload = false; @@ -110,7 +110,7 @@ public void init(ServletConfig servletConfig) throws ServletException { log.error("Error parsing referrer.robotCheck.userAgentPattern value '" + robotPatternStr + "'. Robots will not be filtered. ", e); } } - + // Development theme reloading themeReload = WebloggerConfig.getBooleanProperty("themes.reload.mode"); } @@ -188,7 +188,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro } else { cacheKey = weblogPageCache.generateKey(pageRequest); } - + // Development only. Reload if theme has been modified if (themeReload) { try { @@ -200,7 +200,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro } else { weblogPageCache.clear(); } - I18nMessages.reloadBundle(weblog.getLocaleInstance()); + I18nMessages.reloadBundle(weblog.getLocaleInstance()); } } catch (Exception ex) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewResourceServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewResourceServlet.java index 5f7ab01a1a..0a72f0397e 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewResourceServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewResourceServlet.java @@ -43,7 +43,7 @@ /** - * Special previewing servlet which serves files uploaded by users as well as + * Special previewing servlet which serves files uploaded by users as well as * static resources in shared themes. This servlet differs from the normal * ResourceServlet because it can accept urls parameters which affect how it * behaves which are used for previewing. @@ -54,7 +54,7 @@ public class PreviewResourceServlet extends HttpServlet { private static Log log = LogFactory.getLog(PreviewResourceServlet.class); - + private ServletContext context = null; @@ -63,7 +63,7 @@ public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing PreviewResourceServlet"); - + this.context = config.getServletContext(); } @@ -73,12 +73,12 @@ public void init(ServletConfig config) throws ServletException { */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Weblog weblog = null; String ctx = request.getContextPath(); String servlet = request.getServletPath(); String reqURI = request.getRequestURI(); - + WeblogPreviewResourceRequest resourceRequest = null; try { // parse the incoming request and extract the relevant data @@ -96,12 +96,12 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + log.debug("Resource requested ["+resourceRequest.getResourcePath()+"]"); - + long resourceLastMod = 0; InputStream resourceStream = null; - + // first, see if we have a preview theme to operate from if(!StringUtils.isEmpty(resourceRequest.getThemeName())) { Theme theme = resourceRequest.getTheme(); @@ -111,7 +111,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) resourceStream = resource.getInputStream(); } } - + // second, see if resource comes from weblog's configured shared theme if(resourceStream == null) { try { @@ -129,7 +129,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) return; } } - + // if not from theme then see if resource is in weblog's upload dir if(resourceStream == null) { try { @@ -147,7 +147,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) return; } } - + // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) { return; @@ -155,11 +155,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod); } - + // set the content type based on whatever is in our web.xml mime defs response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath())); - + OutputStream out = null; try { // ok, lets serve up the file @@ -169,11 +169,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) while((length = resourceStream.read(buf)) > 0) { out.write(buf, 0, length); } - + // cleanup out.close(); resourceStream.close(); - + } catch (Exception ex) { log.error("Error writing resource file", ex); if(!response.isCommitted()) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewServlet.java index 5757c3b33f..239bc60adb 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewServlet.java @@ -55,35 +55,35 @@ * outside of the authoring interface. */ public class PreviewServlet extends HttpServlet { - + private static Log log = LogFactory.getLog(PreviewServlet.class); - - + + /** * Init method for this servlet */ public void init(ServletConfig servletConfig) throws ServletException { - + super.init(servletConfig); - + log.info("Initializing PreviewServlet"); } - - + + /** * Handle GET requests for weblog pages. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + log.debug("Entering"); - + Weblog weblog = null; - + WeblogPreviewRequest previewRequest = null; try { previewRequest = new WeblogPreviewRequest(request); - + // lookup weblog specified by preview request weblog = previewRequest.getWeblog(); if(weblog == null) { @@ -96,9 +96,9 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + Weblog tmpWebsite = weblog; - + if (previewRequest.getThemeName() != null) { // only create temporary weblog object if theme name was specified // in request, which indicates we're doing a theme preview @@ -121,16 +121,16 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // the object that gets referenced during rendering operations previewRequest.setWeblog(tmpWebsite); } - + // do we need to force a specific locale for the request? if(previewRequest.getLocale() == null && !weblog.isShowAllLangs()) { previewRequest.setLocale(weblog.getLocale()); } - + Template page = null; if("page".equals(previewRequest.getContext())) { page = previewRequest.getWeblogPage(); - + // If request specified tags section index, then look for custom template } else if("tags".equals(previewRequest.getContext()) && previewRequest.getTags() == null) { @@ -139,7 +139,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } catch(Exception e) { log.error("Error getting weblog page for action 'tagsIndex'", e); } - + // if we don't have a custom tags page then 404, we don't let // this one fall through to the default template if(page == null) { @@ -147,7 +147,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // If this is a permalink then look for a permalink template } else if(previewRequest.getWeblogAnchor() != null) { try { @@ -156,7 +156,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) log.error("Error getting weblog page for action 'permalink'", e); } } - + if(page == null) { try { page = tmpWebsite.getTheme().getDefaultTemplate(); @@ -164,20 +164,20 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) log.error("Error getting default page for preview", re); } } - + // Still no page? Then that is a 404 if (page == null) { if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + log.debug("preview page found, dealing with it"); - + // set the content type String pageLink = previewRequest.getWeblogPageName(); - String mimeType = pageLink != null ? RollerContext.getServletContext().getMimeType(pageLink) : null; + String mimeType = pageLink != null ? RollerContext.getServletContext().getMimeType(pageLink) : null; String contentType = "text/html; charset=utf-8"; if(mimeType != null) { // we found a match ... set the content type @@ -186,28 +186,28 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // TODO: store content-type for each page so this hack is unnecessary contentType = "text/css; charset=utf-8"; } - + // looks like we need to render content Map model = new HashMap(); try { PageContext pageContext = JspFactory.getDefaultFactory().getPageContext( this, request, response,"", false, 8192, true); - + // special hack for menu tag request.setAttribute("pageRequest", previewRequest); - + // populate the rendering model Map initData = new HashMap(); initData.put("parsedRequest", previewRequest); initData.put("pageContext", pageContext); - + // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy().getPreviewURLStrategy(previewRequest.getThemeName())); - + // Load models for page previewing String pageModels = WebloggerConfig.getProperty("rendering.previewModels"); ModelLoader.loadModels(pageModels, model, initData, true); - + // Load special models for site-wide blog if(WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); @@ -216,19 +216,19 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); - + // ick, gotta load pre-3.0 model stuff as well :( ModelLoader.loadOldModels(model, request, response, pageContext, previewRequest, WebloggerFactory.getWeblogger().getUrlStrategy().getPreviewURLStrategy(previewRequest.getThemeName())); - + } catch (WebloggerException ex) { log.error("ERROR loading model for page", ex); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } - - + + // lookup Renderer we are going to use Renderer renderer = null; try { @@ -237,40 +237,40 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } catch(Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for page "+page.getId(), e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // render content. use default size of about 24K for a standard page CachedContent rendererOutput = new CachedContent(24567); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); - + // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch(Exception e) { // bummer, error during rendering log.error("Error during rendering for page "+page.getId(), e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // post rendering process - + // flush rendered content to response log.debug("Flushing response output"); response.setContentType(contentType); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); - + log.debug("Exiting"); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewThemeImageServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewThemeImageServlet.java index 0a68757cac..3b0a92fb81 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewThemeImageServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/PreviewThemeImageServlet.java @@ -36,7 +36,7 @@ import org.apache.roller.weblogger.ui.rendering.util.ModDateHeaderUtil; /** - * Special previewing servlet which serves files uploaded by users as well as + * Special previewing servlet which serves files uploaded by users as well as * static resources in shared themes. This servlet differs from the normal * ResourceServlet because it can accept urls parameters which affect how it * behaves which are used for previewing. @@ -44,7 +44,7 @@ public class PreviewThemeImageServlet extends HttpServlet { private static Log log = LogFactory.getLog(PreviewThemeImageServlet.class); - + private ServletContext context = null; @@ -53,7 +53,7 @@ public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing PreviewThemeImageServlet"); - + this.context = config.getServletContext(); } @@ -63,15 +63,15 @@ public void init(ServletConfig config) throws ServletException { */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + String theme = request.getParameter("theme"); - + log.debug("Theme requested ["+theme+"]"); - + long resourceLastMod = 0; InputStream resourceStream = null; String previewImagePath = null; - + // try looking up selected theme try { ThemeManager tmgr = WebloggerFactory.getWeblogger().getThemeManager(); @@ -87,14 +87,14 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // if we don't have a stream to the file then we can't continue if(resourceStream == null) { log.debug("Unable to get theme preview for theme - "+theme); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) { return; @@ -102,12 +102,12 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod); } - + log.debug("Everything is cool, sending image"); - + // set the content type based on whatever is in our web.xml mime defs response.setContentType(this.context.getMimeType(previewImagePath)); - + OutputStream out = null; try { // ok, lets serve up the file @@ -117,11 +117,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) while((length = resourceStream.read(buf)) > 0) { out.write(buf, 0, length); } - + // cleanup out.close(); resourceStream.close(); - + } catch (Exception ex) { log.error("Error writing resource file", ex); if(!response.isCommitted()) { diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java index cf4141f13d..75f3992f0b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java @@ -49,50 +49,50 @@ * @web.servlet-mapping url-pattern="/roller-ui/rendering/rsd/*" */ public class RSDServlet extends HttpServlet { - + private static Log log = LogFactory.getLog(RSDServlet.class); - - + + /** * Init method for this servlet */ public void init(ServletConfig servletConfig) throws ServletException { - + super.init(servletConfig); - + log.info("Initializing RSDServlet"); } - - + + /** * Handle GET requests for weblog pages. */ - public void doGet(HttpServletRequest request, HttpServletResponse response) + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + log.debug("Entering"); - + Weblog weblog = null; - + WeblogRequest weblogRequest = null; try { weblogRequest = new WeblogRequest(request); - + // now make sure the specified weblog really exists weblog = weblogRequest.getWeblog(); if(weblog == null) { throw new WebloggerException("Unable to lookup weblog: "+ weblogRequest.getWeblogHandle()); } - + } catch(Exception e) { // invalid rsd request format or weblog doesn't exist log.debug("error creating weblog request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // Respond with 304 Not Modified if it is not modified. long lastModified = System.currentTimeMillis(); @@ -108,13 +108,13 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set the content type response.setContentType("application/rsd+xml; charset=utf-8"); - + // populate the model HashMap model = new HashMap(); model.put("website", weblog); model.put("absBaseURL", WebloggerRuntimeConfig.getAbsoluteContextURL()); - + // lookup Renderer we are going to use Renderer renderer = null; try { @@ -124,39 +124,39 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } catch(Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for rsd template", e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // render content CachedContent rendererOutput = new CachedContent(4096); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); - + // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch(Exception e) { // bummer, error during rendering log.error("Error during rendering for rsd template", e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // post rendering process - + // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); - + log.debug("Exiting"); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/ResourceServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/ResourceServlet.java index 2f341ffe50..b11f061aa9 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/ResourceServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/ResourceServlet.java @@ -50,7 +50,7 @@ public class ResourceServlet extends HttpServlet { private static Log log = LogFactory.getLog(ResourceServlet.class); - + private ServletContext context = null; @@ -59,7 +59,7 @@ public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing ResourceServlet"); - + this.context = config.getServletContext(); } @@ -69,12 +69,12 @@ public void init(ServletConfig config) throws ServletException { */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Weblog weblog = null; String ctx = request.getContextPath(); String servlet = request.getServletPath(); String reqURI = request.getRequestURI(); - + WeblogResourceRequest resourceRequest = null; try { // parse the incoming request and extract the relevant data @@ -92,12 +92,12 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + log.debug("Resource requested ["+resourceRequest.getResourcePath()+"]"); - + long resourceLastMod = 0; InputStream resourceStream = null; - + // first see if resource comes from weblog's shared theme try { WeblogTheme weblogTheme = weblog.getTheme(); @@ -113,7 +113,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } - + // if not from theme then see if resource is in weblog's upload dir if(resourceStream == null) { try { @@ -123,7 +123,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) weblog, resourceRequest.getResourcePath()); resourceLastMod = mf.getLastModified(); resourceStream = mf.getInputStream(); - + } catch (Exception ex) { // still not found? then we don't have it, 404. log.debug("Unable to get resource", ex); @@ -131,7 +131,7 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) return; } } - + // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) { return; @@ -139,11 +139,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod); } - + // set the content type based on whatever is in our web.xml mime defs response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath())); - + OutputStream out = null; try { // ok, lets serve up the file @@ -153,10 +153,10 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) while((length = resourceStream.read(buf)) > 0) { out.write(buf, 0, length); } - + // close output stream out.close(); - + } catch (Exception ex) { if(!response.isCommitted()) { response.reset(); diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/SearchServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/SearchServlet.java index 155ddb177a..9d89609c78 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/SearchServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/SearchServlet.java @@ -53,65 +53,65 @@ /** * Handles search queries for weblogs. */ -public class SearchServlet extends HttpServlet { +public class SearchServlet extends HttpServlet { private static Log log = LogFactory.getLog(SearchServlet.class); - + // Development theme reloading Boolean themeReload = false; - + /** * Init method for this servlet */ public void init(ServletConfig servletConfig) throws ServletException { - + super.init(servletConfig); - + log.info("Initializing SearchServlet"); } - - + + /** * Handle GET requests for weblog pages. */ - public void doGet(HttpServletRequest request, HttpServletResponse response) + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + log.debug("Entering"); - + Weblog weblog = null; WeblogSearchRequest searchRequest = null; - + // first off lets parse the incoming request and validate it try { searchRequest = new WeblogSearchRequest(request); - + // now make sure the specified weblog really exists weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(searchRequest.getWeblogHandle(), Boolean.TRUE); - + } catch(Exception e) { // invalid search request format or weblog doesn't exist log.debug("error creating weblog search request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // do we need to force a specific locale for the request? if(searchRequest.getLocale() == null && !weblog.isShowAllLangs()) { searchRequest.setLocale(weblog.getLocale()); } - + // lookup template to use for rendering ThemeTemplate page = null; try { // first try looking for a specific search page page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_SEARCH); - + // if not found then fall back on default page if(page == null) { page = weblog.getTheme().getDefaultTemplate(); } - + // if still null then that's a problem if(page == null) { throw new WebloggerException("Could not lookup default page "+ @@ -121,21 +121,21 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) log.error("Error getting default page for weblog "+ weblog.getHandle(), e); } - + // set the content type response.setContentType("text/html; charset=utf-8"); - + // looks like we need to render content Map model = new HashMap(); try { PageContext pageContext = JspFactory.getDefaultFactory().getPageContext( this, request, response,"", false, 8192, true); - + // populate the rendering model Map initData = new HashMap(); initData.put("request", request); initData.put("pageContext", pageContext); - + // this is a little hacky, but nothing we can do about it // we need the 'weblogRequest' to be a pageRequest so other models // are properly loaded, which means that searchRequest needs its @@ -146,14 +146,14 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) pageRequest.setWeblogCategoryName(searchRequest.getWeblogCategoryName()); initData.put("parsedRequest", pageRequest); initData.put("searchRequest", searchRequest); - + // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); - + // Load models for pages String searchModels = WebloggerConfig.getProperty("rendering.searchModels"); ModelLoader.loadModels(searchModels, model, initData, true); - + // Load special models for site-wide blog if(WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); @@ -162,18 +162,18 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); - + // ick, gotta load pre-3.0 model stuff as well :( ModelLoader.loadOldModels(model, request, response, pageContext, pageRequest, WebloggerFactory.getWeblogger().getUrlStrategy()); - + // manually add search model again to support pre-3.0 weblogs Model searchModel = new SearchResultsModel(); searchModel.init(initData); model.put("searchResults", searchModel); - + } catch (WebloggerException ex) { log.error("Error loading model objects for page", ex); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; @@ -190,14 +190,14 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } else { WeblogPageCache.getInstance().clear(); } - I18nMessages.reloadBundle(weblog.getLocaleInstance()); + I18nMessages.reloadBundle(weblog.getLocaleInstance()); } } catch (Exception ex) { log.error("ERROR - reloading theme " + ex); } } - + // lookup Renderer we are going to use Renderer renderer = null; try { @@ -206,39 +206,39 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) } catch(Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for rsd template", e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - + // render content CachedContent rendererOutput = new CachedContent(4096); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); - + // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch(Exception e) { // bummer, error during rendering log.error("Error during rendering for rsd template", e); - + if(!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - - + + // post rendering process - + // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); - + log.debug("Exiting"); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/TrackbackServlet.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/TrackbackServlet.java index 52f9899e64..223fbb354b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/TrackbackServlet.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/TrackbackServlet.java @@ -54,21 +54,21 @@ * @web.servlet name="TrackbackServlet" * @web.servlet-mapping url-pattern="/roller-ui/rendering/trackback/*" */ -public class TrackbackServlet extends HttpServlet { - +public class TrackbackServlet extends HttpServlet { + private static Log logger = LogFactory.getLog(TrackbackServlet.class); - + private CommentValidationManager commentValidationManager = null; - + public void init(ServletConfig config) throws ServletException { commentValidationManager = new CommentValidationManager(); - + // add trackback verification validator just for trackbacks commentValidationManager.addCommentValidator(new TrackbackLinkbackCommentValidator()); } - - + + /** * Handle incoming http GET requests. * @@ -76,11 +76,11 @@ public void init(ServletConfig config) throws ServletException { */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - + response.sendError(HttpServletResponse.SC_NOT_FOUND); } - - + + /** * Service incoming POST requests. * @@ -88,70 +88,70 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + String error = null; PrintWriter pw = response.getWriter(); - + Weblog weblog = null; WeblogEntry entry = null; - + RollerMessages messages = new RollerMessages(); - + WeblogTrackbackRequest trackbackRequest = null; if (!WebloggerRuntimeConfig.getBooleanProperty("users.trackbacks.enabled")) { // TODO: i18n error = "Trackbacks are disabled for this site"; } else { - + try { trackbackRequest = new WeblogTrackbackRequest(request); - + if ((trackbackRequest.getTitle() == null) || "".equals(trackbackRequest.getTitle())) { trackbackRequest.setTitle(trackbackRequest.getUrl()); } - + if (trackbackRequest.getExcerpt() == null) { trackbackRequest.setExcerpt(""); } else if (trackbackRequest.getExcerpt().length() >= 255) { trackbackRequest.setExcerpt(trackbackRequest.getExcerpt().substring(0, 252)+"..."); } - + // lookup weblog specified by comment request weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(trackbackRequest.getWeblogHandle()); - + if (weblog == null) { throw new WebloggerException("unable to lookup weblog: "+ trackbackRequest.getWeblogHandle()); } - + // lookup entry specified by comment request WeblogEntryManager weblogMgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); entry = weblogMgr.getWeblogEntryByAnchor(weblog, trackbackRequest.getWeblogAnchor()); - + if (entry == null) { throw new WebloggerException("unable to lookup entry: "+ trackbackRequest.getWeblogAnchor()); } - + } catch (Exception e) { // some kind of error parsing the request or looking up weblog logger.debug("error creating trackback request", e); error = e.getMessage(); } } - + if (error != null) { pw.println(this.getErrorResponse(error)); return; } - - try { + + try { // check if trackbacks are allowed for this entry // this checks site-wide settings, weblog settings, and entry settings if (entry != null && entry.getCommentsStillAllowed() && entry.isPublished()) { - + // Track trackbacks as comments WeblogEntryComment comment = new WeblogEntryComment(); comment.setContent("[Trackback] "+trackbackRequest.getExcerpt()); @@ -161,11 +161,11 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) comment.setRemoteHost(request.getRemoteHost()); comment.setNotify(Boolean.FALSE); comment.setPostTime(new Timestamp(new Date().getTime())); - + // run new trackback through validators int validationScore = commentValidationManager.validateComment(comment, messages); logger.debug("Comment Validation score: " + validationScore); - + if (validationScore == 100 && weblog.getCommentModerationRequired()) { // Valid comments go into moderation if required comment.setStatus(WeblogEntryComment.PENDING); @@ -176,33 +176,33 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) // Invalid comments are marked as spam comment.setStatus(WeblogEntryComment.SPAM); } - + // save, commit, send response if(!WeblogEntryComment.SPAM.equals(comment.getStatus()) || !WebloggerRuntimeConfig.getBooleanProperty("trackbacks.ignoreSpam.enabled")) { - + WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.saveComment(comment); WebloggerFactory.getWeblogger().flush(); - + // only invalidate the cache if comment isn't moderated if(!weblog.getCommentModerationRequired()) { // Clear all caches associated with comment CacheManager.invalidate(comment); } - + // Send email notifications - MailUtil.sendEmailNotification(comment, messages, + MailUtil.sendEmailNotification(comment, messages, I18nMessages.getMessages(trackbackRequest.getLocaleInstance()), validationScore == 100); - + if(WeblogEntryComment.PENDING.equals(comment.getStatus())) { pw.println(this.getSuccessResponse("Trackback submitted to moderator")); } else { pw.println(this.getSuccessResponse("Trackback accepted")); } } - + } else if (entry!=null) { // TODO: i18n error = "Comments and Trackbacks are disabled for the entry you specified."; @@ -210,25 +210,25 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) // TODO: i18n error = "Entry not specified."; } - + } catch (Exception e) { error = e.getMessage(); if ( error == null ) { error = e.getClass().getName(); } } - + if(error!= null) { pw.println(this.getErrorResponse(error)); } - + } - - + + private String getSuccessResponse(String message) { - + StringBuffer output = new StringBuffer(); - + output.append(""); output.append(""); output.append("0"); @@ -236,15 +236,15 @@ private String getSuccessResponse(String message) { output.append(message); output.append(""); output.append(""); - + return output.toString(); } - - + + private String getErrorResponse(String message) { - + StringBuffer output = new StringBuffer(); - + output.append(""); output.append(""); output.append("1"); @@ -252,8 +252,8 @@ private String getErrorResponse(String message) { output.append(message); output.append(""); output.append(""); - + return output.toString(); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/InvalidRequestException.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/InvalidRequestException.java index dd595c8f53..acaf5e89aa 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/InvalidRequestException.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/InvalidRequestException.java @@ -26,13 +26,13 @@ * its subclasses when the request being parsed is invalid in any way. */ public class InvalidRequestException extends WebloggerException { - + public InvalidRequestException(String msg) { super(msg); } - + public InvalidRequestException(String msg, Exception e) { super(msg, e); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/ParsedRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/ParsedRequest.java index b48bcf5c3d..5f660c3f2b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/ParsedRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/ParsedRequest.java @@ -39,21 +39,21 @@ * needed. */ public abstract class ParsedRequest { - + private static Log log = LogFactory.getLog(ParsedRequest.class); - + HttpServletRequest request = null; - + // lightweight attributes private String authenticUser = null; - + // heavyweight attributes private User user = null; - - + + ParsedRequest() {} - - + + /** * Parse the given http request and extract any information we can. * @@ -61,31 +61,31 @@ public abstract class ParsedRequest { * relevant to all requests to Roller. */ public ParsedRequest(HttpServletRequest request) throws InvalidRequestException { - + // keep a reference to the original request this.request = request; - + // login status java.security.Principal prince = request.getUserPrincipal(); if(prince != null) { this.authenticUser = prince.getName(); } - + } - - + + public String getAuthenticUser() { return this.authenticUser; } - - + + public void setAuthenticUser(String authenticUser) { this.authenticUser = authenticUser; } - - + + public User getUser() { - + if(user == null && authenticUser != null) { try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); @@ -94,18 +94,18 @@ public User getUser() { log.error("Error looking up user "+authenticUser, ex); } } - + return user; } - - + + public void setUser(User u) { this.user = u; } - - + + public boolean isLoggedIn() { return (this.authenticUser != null); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/PlanetRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/PlanetRequest.java index 8098c473fe..20c96106e5 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/PlanetRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/PlanetRequest.java @@ -29,34 +29,34 @@ * currently ... /planet.do and /planetrss */ public class PlanetRequest extends ParsedRequest { - + private static Log log = LogFactory.getLog(PlanetRequest.class); - + private String context = null; private String type = null; private String flavor = null; private boolean excerpts = false; private String language = null; private String group = null; - - + + /** * Construct the PlanetRequest by parsing the incoming url */ public PlanetRequest(HttpServletRequest request) throws InvalidRequestException { - + super(request); - + // parse the request object and figure out what we've got log.debug("parsing url "+request.getRequestURL()); - + String servlet = request.getServletPath(); - + // what servlet is our destination? if(servlet != null) { // strip off the leading slash servlet = servlet.substring(1); - + if(servlet.equals("planet.do")) { this.context = "planet"; this.type = "page"; @@ -68,12 +68,12 @@ public PlanetRequest(HttpServletRequest request) throws InvalidRequestException // not a request to a feed servlet throw new InvalidRequestException("not a planet request, "+request.getRequestURL()); } - + } else { throw new InvalidRequestException("not a planet request, "+request.getRequestURL()); } - - + + /* * parse request parameters * @@ -84,29 +84,29 @@ public PlanetRequest(HttpServletRequest request) throws InvalidRequestException if (request.getParameter("excerpts") != null) { this.excerpts = Boolean.valueOf(request.getParameter("excerpts")).booleanValue(); } - + if (request.getParameter("group") != null) { this.group = request.getParameter("group"); } - - + + // language is always from the browser language = request.getLocale().getLanguage(); } - - + + public String getContext() { return context; } - + public String getType() { return type; } - + public String getFlavor() { return flavor; } - + public boolean isExcerpts() { return excerpts; } @@ -118,8 +118,8 @@ public String getLanguage() { public void setLanguage(String language) { this.language = language; } - + public String getGroup() { return group; - } + } } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogCommentRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogCommentRequest.java index 53713e31b3..bac53528ed 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogCommentRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogCommentRequest.java @@ -34,11 +34,11 @@ * Represents a request to post a weblog entry comment. */ public class WeblogCommentRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogCommentRequest.class); - + private static final String COMMENT_SERVLET = "/roller-ui/rendering/comment"; - + // lightweight attributes private String name = null; private String email = null; @@ -46,71 +46,71 @@ public class WeblogCommentRequest extends WeblogRequest { private String content = null; private boolean notify = false; private String weblogAnchor = null; - + // heavyweight attributes private WeblogEntry weblogEntry = null; - - + + public WeblogCommentRequest() {} - - - public WeblogCommentRequest(HttpServletRequest request) + + + public WeblogCommentRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // was this request bound for the comment servlet? if(servlet == null || !COMMENT_SERVLET.equals(servlet)) { throw new InvalidRequestException("not a weblog comment request, "+ request.getRequestURL()); } - - + + /* * parse path info. we expect ... * * /entry/ - permalink */ if(pathInfo != null && pathInfo.trim().length() > 0) { - + // we should only ever get 2 path elements String[] pathElements = pathInfo.split("/"); if(pathElements.length == 2) { - + String context = pathElements[0]; if("entry".equals(context)) { try { - this.weblogAnchor = + this.weblogAnchor = URLDecoder.decode(pathElements[1], "UTF-8"); } catch (UnsupportedEncodingException ex) { // should never happen log.error(ex); } - + } else { throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - + } else { throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - + } else { // bad request throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - - + + /* * parse request parameters * @@ -124,23 +124,23 @@ public WeblogCommentRequest(HttpServletRequest request) if(request.getParameter("name") != null) { this.name = Utilities.removeHTML(request.getParameter("name")); } - + if(request.getParameter("email") != null) { this.email = Utilities.removeHTML(request.getParameter("email")); } - + if(request.getParameter("url") != null) { this.url = Utilities.removeHTML(request.getParameter("url")); } - + if(request.getParameter("content") != null) { this.content = request.getParameter("content"); } - + if(request.getParameter("notify") != null) { this.notify = true; } - + if(log.isDebugEnabled()) { log.debug("name = "+this.name); log.debug("email = "+this.email); @@ -200,7 +200,7 @@ public void setWeblogAnchor(String weblogAnchor) { } public WeblogEntry getWeblogEntry() { - + if(weblogEntry == null && weblogAnchor != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -209,12 +209,12 @@ public WeblogEntry getWeblogEntry() { log.error("Error getting weblog entry "+weblogAnchor, ex); } } - + return weblogEntry; } public void setWeblogEntry(WeblogEntry weblogEntry) { this.weblogEntry = weblogEntry; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogEntryCommentForm.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogEntryCommentForm.java index 15752ba97c..597bdbcf1a 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogEntryCommentForm.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogEntryCommentForm.java @@ -28,27 +28,27 @@ * permalink page. We use this class to manage the interaction with that form. */ public class WeblogEntryCommentForm { - + private boolean error = false; private String message = null; - + private String name = ""; private String email = ""; private String url = ""; private String content = ""; private boolean notify = false; - + private WeblogEntryComment previewComment = null; - - + + public WeblogEntryCommentForm() {} - - + + public void setPreview(WeblogEntryComment preview) { this.previewComment = preview; setData(preview); } - + public void setData(WeblogEntryComment comment) { this.name = comment.getName(); this.email = comment.getEmail(); @@ -56,21 +56,21 @@ public void setData(WeblogEntryComment comment) { this.content = comment.getContent(); this.notify = comment.getNotify().booleanValue(); } - + public void setError(String errorMessage) { this.error = true; this.message = errorMessage; } - + public WeblogEntryCommentWrapper getPreviewComment() { // NOTE: no need for url strategy when wrapping preview comment return WeblogEntryCommentWrapper.wrap(previewComment, null); } - + public boolean isPreview() { return (this.previewComment != null); } - + public String getName() { return StringEscapeUtils.escapeHtml(name); } @@ -126,5 +126,5 @@ public String getMessage() { public void setMessage(String message) { this.message = message; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java index 8b536f1342..bc0f6886dd 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java @@ -38,18 +38,18 @@ /** * Represents a request for a Roller weblog feed. - * + * * /roller-ui/rendering/feeds/* * * We use this class as a helper to parse an incoming url and sort out the * information embedded in the url for later use. */ public class WeblogFeedRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogFeedRequest.class); - + private static final String FEED_SERVLET = "/roller-ui/rendering/feed"; - + // lightweight attributes private String type = null; private String format = null; @@ -58,48 +58,48 @@ public class WeblogFeedRequest extends WeblogRequest { private int page = 0; private boolean excerpts = false; private String term = null; - + // heavyweight attributes private WeblogCategory weblogCategory = null; - - + + public WeblogFeedRequest() {} - - + + /** * Construct the WeblogFeedRequest by parsing the incoming url */ - public WeblogFeedRequest(HttpServletRequest request) + public WeblogFeedRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - + // was this request bound for the feed servlet? if(servlet == null || !FEED_SERVLET.equals(servlet)) { throw new InvalidRequestException("not a weblog feed request, "+ request.getRequestURL()); } - - - /* + + + /* * parse the path info. - * + * * must look like this ... * * // */ if(pathInfo != null && pathInfo.trim().length() > 1) { - + String[] pathElements = pathInfo.split("/"); if(pathElements.length == 2) { this.type = pathElements[0]; @@ -108,14 +108,14 @@ public WeblogFeedRequest(HttpServletRequest request) throw new InvalidRequestException("invalid feed path info, "+ request.getRequestURL()); } - + } else { throw new InvalidRequestException("invalid feed path info, "+ request.getRequestURL()); } - - - /* + + + /* * parse request parameters * * the only params we currently care about are: @@ -126,42 +126,42 @@ public WeblogFeedRequest(HttpServletRequest request) if(request.getParameter("cat") != null) { this.weblogCategoryName = URLUtilities.decode(request.getParameter("cat")); - + // all categories must start with a / if(!this.weblogCategoryName.startsWith("/")) { this.weblogCategoryName = "/"+this.weblogCategoryName; } } - + if(request.getParameter("tags") != null) { - this.tags = Utilities.splitStringAsTags(request.getParameter("tags")); + this.tags = Utilities.splitStringAsTags(request.getParameter("tags")); int maxSize = WebloggerConfig.getIntProperty("tags.queries.maxIntersectionSize", 3); if (this.tags.size() > maxSize) throw new InvalidRequestException("max number of tags allowed is " + maxSize + ", " + request.getRequestURL()); - } - + } + if(request.getParameter("excerpts") != null) { this.excerpts = Boolean.valueOf(request.getParameter("excerpts")).booleanValue(); } - + if(request.getParameter("page") != null) { try { this.page = Integer.parseInt(request.getParameter("page")); } catch(NumberFormatException e) { - // + // } - } - + } + if(request.getParameter("q") != null && request.getParameter("q").trim().length() > 0) { this.term = URLUtilities.decode(request.getParameter("q")); - } - + } + if((this.tags != null && this.tags.size() > 0) && this.weblogCategoryName != null) { - throw new InvalidRequestException("please specify either category or tags but not both, " + request.getRequestURL()); + throw new InvalidRequestException("please specify either category or tags but not both, " + request.getRequestURL()); } - + if(log.isDebugEnabled()) { log.debug("type = "+this.type); log.debug("format = "+this.format); @@ -194,7 +194,7 @@ public String getWeblogCategoryName() { public void setWeblogCategoryName(String weblogCategory) { this.weblogCategoryName = weblogCategory; } - + public List getTags() { return tags; } @@ -212,7 +212,7 @@ public void setExcerpts(boolean excerpts) { } public WeblogCategory getWeblogCategory() { - + if(weblogCategory == null && weblogCategoryName != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -221,7 +221,7 @@ public WeblogCategory getWeblogCategory() { log.error("Error getting weblog category "+weblogCategoryName, ex); } } - + return weblogCategory; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogMediaResourceRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogMediaResourceRequest.java index 44fff11a98..b5a122ff20 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogMediaResourceRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogMediaResourceRequest.java @@ -29,47 +29,47 @@ * /roller-ui/rendering/resources/* */ public class WeblogMediaResourceRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogMediaResourceRequest.class); - + // lightweight attributes private String resourceId = null; private boolean thumbnail = false; - - + + public WeblogMediaResourceRequest() {} - - + + /** * Construct the WeblogResourceRequest by parsing the incoming url */ - public WeblogMediaResourceRequest(HttpServletRequest request) + public WeblogMediaResourceRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - - - /* + + + /* * any id is okay... */ if (pathInfo != null && pathInfo.trim().length() > 1) { - + this.resourceId = pathInfo; if (pathInfo.startsWith("/")) { this.resourceId = pathInfo.substring(1); } - + } else { throw new InvalidRequestException("invalid resource path info, "+ request.getRequestURL()); @@ -78,12 +78,12 @@ public WeblogMediaResourceRequest(HttpServletRequest request) if (request.getParameter("t") != null && "true".equals(request.getParameter("t"))) { thumbnail = true; } - + if(log.isDebugEnabled()) { log.debug("resourceId = "+this.resourceId); } } - + public String getResourceId() { return resourceId; } @@ -91,9 +91,9 @@ public String getResourceId() { public void setResourceId(String resourceId) { this.resourceId = resourceId; } - + protected boolean isLocale(String potentialLocale) { - // We don't support locales in the resource Servlet so we've got to + // We don't support locales in the resource Servlet so we've got to // keep parent from treating upload sub-directory name as a locale. return false; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPageRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPageRequest.java index 758cb0930b..2c1920c8f6 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPageRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPageRequest.java @@ -47,11 +47,11 @@ * information embedded in the url for later use. */ public class WeblogPageRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogPageRequest.class); - + private static final String PAGE_SERVLET = "/roller-ui/rendering/page"; - + // lightweight attributes private String context = null; private String weblogAnchor = null; @@ -61,41 +61,41 @@ public class WeblogPageRequest extends WeblogRequest { private List tags = null; private int pageNum = 0; private Map customParams = new HashMap(); - + // heavyweight attributes private WeblogEntry weblogEntry = null; private ThemeTemplate weblogPage = null; private WeblogCategory weblogCategory = null; - - + + public WeblogPageRequest() {} - - + + /** * Construct the WeblogPageRequest by parsing the incoming url */ - public WeblogPageRequest(HttpServletRequest request) + public WeblogPageRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - + // was this request bound for the right servlet? if(!isValidDestination(servlet)) { throw new InvalidRequestException("invalid destination for request, "+ request.getRequestURL()); } - - + + /* * parse path info * @@ -110,19 +110,19 @@ public WeblogPageRequest(HttpServletRequest request) * path info may be null, which indicates the weblog homepage */ if(pathInfo != null && pathInfo.trim().length() > 0) { - + // all views use 2 path elements, except category String[] pathElements = pathInfo.split("/", 2); - + // the first part of the path always represents the context this.context = pathElements[0]; - + // now check the rest of the path and extract other details if(pathElements.length == 2) { - + if("entry".equals(this.context)) { this.weblogAnchor = URLUtilities.decode(pathElements[1]); - + } else if("date".equals(this.context)) { if(this.isValidDateString(pathElements[1])) { this.weblogDate = pathElements[1]; @@ -130,15 +130,15 @@ public WeblogPageRequest(HttpServletRequest request) throw new InvalidRequestException("invalid date, "+ request.getRequestURL()); } - + } else if("category".equals(this.context)) { this.weblogCategoryName = URLUtilities.decode(pathElements[1]); - + // all categories must start with a / if(!this.weblogCategoryName.startsWith("/")) { this.weblogCategoryName = "/"+this.weblogCategoryName; } - + } else if("page".equals(this.context)) { this.weblogPageName = pathElements[1]; String tagsString = request.getParameter("tags"); @@ -148,16 +148,16 @@ public WeblogPageRequest(HttpServletRequest request) } else if("tags".equals(this.context)) { String tagsString = pathElements[1].replace('+', ' '); - this.tags = Utilities.splitStringAsTags(URLUtilities.decode(tagsString)); - int maxSize = WebloggerConfig.getIntProperty("tags.queries.maxIntersectionSize", 3); + this.tags = Utilities.splitStringAsTags(URLUtilities.decode(tagsString)); + int maxSize = WebloggerConfig.getIntProperty("tags.queries.maxIntersectionSize", 3); if(this.tags.size() > maxSize) throw new InvalidRequestException("max number of tags allowed is " + maxSize + ", " + request.getRequestURL()); - + } else { throw new InvalidRequestException("context "+this.context+ "not supported, "+request.getRequestURL()); } - + } else { // empty data is only allowed for the tags section if(!"tags".equals(this.context)) { @@ -165,12 +165,12 @@ public WeblogPageRequest(HttpServletRequest request) request.getRequestURL()); } } - + } else { // default view, weblog homepage } - - + + /* * parse request parameters * @@ -185,7 +185,7 @@ public WeblogPageRequest(HttpServletRequest request) * we prevent mixing of path based and query param style urls. */ if(pathInfo == null || this.weblogPageName != null) { - + // check for entry/anchor params which indicate permalink if(request.getParameter("entry") != null) { String anchor = request.getParameter("entry"); @@ -198,7 +198,7 @@ public WeblogPageRequest(HttpServletRequest request) this.weblogAnchor = anchor; } } - + // only check for other params if we didn't find an anchor above or tags if(this.weblogAnchor == null && this.tags == null) { if(request.getParameter("date") != null) { @@ -210,11 +210,11 @@ public WeblogPageRequest(HttpServletRequest request) request.getRequestURL()); } } - + if(request.getParameter("cat") != null) { this.weblogCategoryName = URLUtilities.decode(request.getParameter("cat")); - + // all categories must start with a / if(!this.weblogCategoryName.startsWith("/")) { this.weblogCategoryName = "/"+this.weblogCategoryName; @@ -222,7 +222,7 @@ public WeblogPageRequest(HttpServletRequest request) } } } - + // page request param is supported in all views if(request.getParameter("page") != null) { String pageInt = request.getParameter("page"); @@ -232,7 +232,7 @@ public WeblogPageRequest(HttpServletRequest request) // ignored, bad input } } - + // build customParams Map, we remove built-in params because we only // want this map to represent params defined by the template author customParams = new HashMap(request.getParameterMap()); @@ -242,8 +242,8 @@ public WeblogPageRequest(HttpServletRequest request) customParams.remove("cat"); customParams.remove("page"); customParams.remove("tags"); - - + + if(log.isDebugEnabled()) { log.debug("context = "+this.context); log.debug("weblogAnchor = "+this.weblogAnchor); @@ -254,13 +254,13 @@ public WeblogPageRequest(HttpServletRequest request) log.debug("pageNum = "+this.pageNum); } } - - + + boolean isValidDestination(String servlet) { return (servlet != null && PAGE_SERVLET.equals(servlet)); } - - + + private boolean isValidDateString(String dateString) { // string must be all numeric and 6 or 8 characters return (dateString != null && StringUtils.isNumeric(dateString) && @@ -322,17 +322,17 @@ public Map getCustomParams() { public void setCustomParams(Map customParams) { this.customParams = customParams; } - + public List getTags() { return tags; } - + public void setTags(List tags) { this.tags = tags; } - + public WeblogEntry getWeblogEntry() { - + if(weblogEntry == null && weblogAnchor != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -341,7 +341,7 @@ public WeblogEntry getWeblogEntry() { log.error("Error getting weblog entry "+weblogAnchor, ex); } } - + return weblogEntry; } @@ -350,15 +350,15 @@ public void setWeblogEntry(WeblogEntry weblogEntry) { } public ThemeTemplate getWeblogPage() { - + if(weblogPage == null && weblogPageName != null) { try { - weblogPage = getWeblog().getTheme().getTemplateByLink(weblogPageName); + weblogPage = getWeblog().getTheme().getTemplateByLink(weblogPageName); } catch (WebloggerException ex) { log.error("Error getting weblog page "+weblogPageName, ex); } } - + return weblogPage; } @@ -367,7 +367,7 @@ public void setWeblogPage(WeblogTemplate weblogPage) { } public WeblogCategory getWeblogCategory() { - + if(weblogCategory == null && weblogCategoryName != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -376,12 +376,12 @@ public WeblogCategory getWeblogCategory() { log.error("Error getting weblog category "+weblogCategoryName, ex); } } - + return weblogCategory; } public void setWeblogCategory(WeblogCategory weblogCategory) { this.weblogCategory = weblogCategory; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewRequest.java index f81f5fc5be..a640d7a85c 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewRequest.java @@ -35,46 +35,46 @@ * Represents a request for a weblog preview. */ public class WeblogPreviewRequest extends WeblogPageRequest { - + private static Log log = LogFactory.getLog(WeblogPreviewRequest.class); - + private static final String PREVIEW_SERVLET = "/roller-ui/authoring/preview"; - + // lightweight attributes private String themeName = null; private String previewEntry = null; - + // heavyweight attributes private Theme theme = null; private WeblogEntry weblogEntry = null; - - public WeblogPreviewRequest(HttpServletRequest request) + + public WeblogPreviewRequest(HttpServletRequest request) throws InvalidRequestException { - + // let parent go first super(request); - + // we may have a specific theme to preview if(request.getParameter("theme") != null) { this.themeName = request.getParameter("theme"); } - + // we may also have a specific entry to preview if(request.getParameter("previewEntry") != null) { this.previewEntry = URLUtilities.decode(request.getParameter("previewEntry")); } - + if(log.isDebugEnabled()) { log.debug("theme = "+this.themeName); } } - - + + boolean isValidDestination(String servlet) { return (servlet != null && PREVIEW_SERVLET.equals(servlet)); } - - + + public String getThemeName() { return themeName; } @@ -82,19 +82,19 @@ public String getThemeName() { public void setThemeName(String theme) { this.themeName = theme; } - + // override so that previews never show login status public String getAuthenticUser() { return null; } - + // override so that previews never show login status public boolean isLoggedIn() { return false; } public Theme getTheme() { - + if(theme == null && themeName != null) { try { ThemeManager themeMgr = WebloggerFactory.getWeblogger().getThemeManager(); @@ -105,7 +105,7 @@ public Theme getTheme() { log.error("Error looking up theme "+themeName, re); } } - + return theme; } @@ -120,18 +120,18 @@ public String getPreviewEntry() { public void setPreviewEntry(String previewEntry) { this.previewEntry = previewEntry; } - + // if we have a preview entry we would prefer to return that public WeblogEntry getWeblogEntry() { - - if(weblogEntry == null && + + if(weblogEntry == null && (previewEntry != null || super.getWeblogAnchor() != null)) { - + String anchor = previewEntry; if(previewEntry == null) { anchor = super.getWeblogAnchor(); } - + try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); weblogEntry = wmgr.getWeblogEntryByAnchor(getWeblog(), anchor); @@ -139,12 +139,12 @@ public WeblogEntry getWeblogEntry() { log.error("Error getting weblog entry "+anchor, ex); } } - + return weblogEntry; } - + public void setWeblogEntry(WeblogEntry weblogEntry) { this.weblogEntry = weblogEntry; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewResourceRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewResourceRequest.java index 1d4c40e58c..a2ea805da0 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewResourceRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogPreviewResourceRequest.java @@ -32,36 +32,36 @@ * */ public class WeblogPreviewResourceRequest extends WeblogResourceRequest { - + private static Log log = LogFactory.getLog(WeblogPreviewResourceRequest.class); - + // lightweight attributes private String themeName = null; - + // heavyweight attributes private Theme theme = null; - - + + public WeblogPreviewResourceRequest() {} - - - public WeblogPreviewResourceRequest(HttpServletRequest request) + + + public WeblogPreviewResourceRequest(HttpServletRequest request) throws InvalidRequestException { - + // let parent go first super(request); - + // all we need to worry about is the query params // the only param we expect is "theme" if(request.getParameter("theme") != null) { this.themeName = request.getParameter("theme"); } - + if(log.isDebugEnabled()) { log.debug("theme = "+this.themeName); } } - + public String getThemeName() { return themeName; } @@ -69,19 +69,19 @@ public String getThemeName() { public void setThemeName(String theme) { this.themeName = theme; } - + // override so that previews never show login status public String getAuthenticUser() { return null; } - + // override so that previews never show login status public boolean isLoggedIn() { return false; } public Theme getTheme() { - + if(theme == null && themeName != null) { try { ThemeManager themeMgr = WebloggerFactory.getWeblogger().getThemeManager(); @@ -92,7 +92,7 @@ public Theme getTheme() { log.error("Error looking up theme "+themeName, re); } } - + return theme; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogRequest.java index 013bc20ef8..81a68da07c 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogRequest.java @@ -30,14 +30,14 @@ /** * Represents a request to a weblog. - * + * * This is a fairly generic parsed request which is only trying to figure out - * the elements of a weblog request which apply to all weblogs. We try to - * determine the weblogHandle, if a locale was specified, and then what extra + * the elements of a weblog request which apply to all weblogs. We try to + * determine the weblogHandle, if a locale was specified, and then what extra * path info remains. The basic format is like this ... - * + * * /[/locale][/extra/path/info] - * + * * All weblog urls require a weblogHandle, so we ensure that part of the url is * properly specified. locale is always optional, so we do our best to see * if a locale is specified. and path info is always optional. @@ -48,43 +48,43 @@ * this class and simply pick up where it left off in the parsing process. */ public class WeblogRequest extends ParsedRequest { - + private static Log log = LogFactory.getLog(WeblogRequest.class); - + // lightweight attributes private String weblogHandle = null; private String locale = null; private String pathInfo = null; - + // heavyweight attributes private Weblog weblog = null; private Locale localeInstance = null; - - + + public WeblogRequest() {} - - - public WeblogRequest(HttpServletRequest request) + + + public WeblogRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first super(request); - + String path = request.getPathInfo(); - + log.debug("parsing path "+path); - + // first, cleanup extra slashes and extract the weblog weblogHandle if(path != null && path.trim().length() > 1) { - + // strip off the leading slash path = path.substring(1); - + // strip off trailing slash if needed if(path.endsWith("/")) { path = path.substring(0, path.length() - 1); } - + String[] pathElements = path.split("/", 2); if(pathElements[0].trim().length() > 0) { this.weblogHandle = pathElements[0]; @@ -93,7 +93,7 @@ public WeblogRequest(HttpServletRequest request) throw new InvalidRequestException("not a weblog request, "+ request.getRequestURL()); } - + // if there is more left of the path info then hold onto it if(pathElements.length == 2) { path = pathElements[1]; @@ -101,14 +101,14 @@ public WeblogRequest(HttpServletRequest request) path = null; } } - + // second, check if we have a locale, everything else is extra path info if(path != null && path.trim().length() > 0) { - + String[] pathElements = path.split("/", 2); if(this.isLocale(pathElements[0])) { this.locale = pathElements[0]; - + // everything else is path info if(pathElements.length == 2) { this.pathInfo = pathElements[1]; @@ -118,46 +118,46 @@ public WeblogRequest(HttpServletRequest request) this.pathInfo = path; } } - + if(log.isDebugEnabled()) { log.debug("handle = "+this.weblogHandle); log.debug("locale = "+this.locale); log.debug("pathInfo = "+this.pathInfo); } } - + /** * Convenience method which determines if the given string is a valid * locale string. */ protected boolean isLocale(String potentialLocale) { - + boolean isLocale = false; - + // we only support 2 or 5 character locale strings, so check that first - if(potentialLocale != null && + if(potentialLocale != null && (potentialLocale.length() == 2 || potentialLocale.length() == 5)) { - + // now make sure that the format is proper ... e.g. "en_US" // we are not going to be picky about capitalization String[] langCountry = potentialLocale.split("_"); - if(langCountry.length == 1 && + if(langCountry.length == 1 && langCountry[0] != null && langCountry[0].length() == 2) { isLocale = true; - - } else if(langCountry.length == 2 && - langCountry[0] != null && langCountry[0].length() == 2 && + + } else if(langCountry.length == 2 && + langCountry[0] != null && langCountry[0].length() == 2 && langCountry[1] != null && langCountry[1].length() == 2) { - + isLocale = true; } } - + return isLocale; } - - + + public String getWeblogHandle() { return weblogHandle; } @@ -165,7 +165,7 @@ public String getWeblogHandle() { public void setWeblogHandle(String weblogHandle) { this.weblogHandle = weblogHandle; } - + public String getLocale() { return locale; } @@ -183,7 +183,7 @@ public void setPathInfo(String pathInfo) { } public Weblog getWeblog() { - + if(weblog == null && weblogHandle != null) { try { weblog = WebloggerFactory.getWeblogger().getWeblogManager() @@ -192,15 +192,15 @@ public Weblog getWeblog() { log.error("Error looking up weblog "+weblogHandle, ex); } } - + return weblog; } public void setWeblog(Weblog weblog) { this.weblog = weblog; } - - + + /** * Get the Locale instance to be used for this request. * @@ -209,7 +209,7 @@ public void setWeblog(Weblog weblog) { * 2. if no locale is specified, then use the weblog default locale */ public Locale getLocaleInstance() { - + if(localeInstance == null && locale != null) { String[] langCountry = locale.split("_"); if(langCountry.length == 1) { @@ -220,12 +220,12 @@ public Locale getLocaleInstance() { } else if(localeInstance == null) { localeInstance = getWeblog().getLocaleInstance(); } - + return localeInstance; } public void setLocaleInstance(Locale localeInstance) { this.localeInstance = localeInstance; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogResourceRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogResourceRequest.java index 7a2f1c855d..56143caf5b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogResourceRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogResourceRequest.java @@ -30,66 +30,66 @@ * /roller-ui/rendering/resources/* */ public class WeblogResourceRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogResourceRequest.class); - + // lightweight attributes private String resourcePath = null; - - + + public WeblogResourceRequest() {} - - + + /** * Construct the WeblogResourceRequest by parsing the incoming url */ - public WeblogResourceRequest(HttpServletRequest request) + public WeblogResourceRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // parse the request object and figure out what we've got log.debug("parsing path "+pathInfo); - - - /* + + + /* * any path is okay ... * * /// */ if(pathInfo != null && pathInfo.trim().length() > 1) { - + this.resourcePath = pathInfo; if(pathInfo.startsWith("/")) { this.resourcePath = pathInfo.substring(1); } - + // Fix for ROL-1065: even though a + should mean space in a URL, folks // who upload files with plus signs expect them to work without // escaping. This is essentially what other systems do (e.g. JIRA) to // enable this. this.resourcePath = this.resourcePath.replaceAll("\\+", "%2B"); - + // now we really decode the URL this.resourcePath = URLUtilities.decode(this.resourcePath); - + } else { throw new InvalidRequestException("invalid resource path info, "+ request.getRequestURL()); } - + if(log.isDebugEnabled()) { log.debug("resourcePath = "+this.resourcePath); } } - + public String getResourcePath() { return resourcePath; } @@ -97,9 +97,9 @@ public String getResourcePath() { public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } - + protected boolean isLocale(String potentialLocale) { - // We don't support locales in the resource Servlet so we've got to + // We don't support locales in the resource Servlet so we've got to // keep parent from treating upload sub-directory name as a locale. return false; } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java index e5e6ff9754..c076f77a02 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java @@ -32,47 +32,47 @@ * Represents a request for a weblog preview. */ public class WeblogSearchRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogSearchRequest.class); - + private static final String SEARCH_SERVLET = "/roller-ui/rendering/search"; - + // lightweight attributes private String query = null; private int pageNum = 0; private String weblogCategoryName = null; - + // heavyweight attributes private WeblogCategory weblogCategory = null; - - + + public WeblogSearchRequest() {} - - - public WeblogSearchRequest(HttpServletRequest request) + + + public WeblogSearchRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // was this request bound for the search servlet? if(servlet == null || !SEARCH_SERVLET.equals(servlet)) { throw new InvalidRequestException("not a weblog search request, "+ request.getRequestURL()); } - + if(pathInfo != null) { throw new InvalidRequestException("invalid path info, "+ request.getRequestURL()); } - - + + /* * parse request parameters * @@ -85,7 +85,7 @@ public WeblogSearchRequest(HttpServletRequest request) request.getParameter("q").trim().length() > 0) { this.query = request.getParameter("q"); } - + if(request.getParameter("page") != null) { String pageInt = request.getParameter("page"); try { @@ -94,12 +94,12 @@ public WeblogSearchRequest(HttpServletRequest request) // ignored, bad input } } - + if(request.getParameter("cat") != null && request.getParameter("cat").trim().length() > 0) { - this.weblogCategoryName = + this.weblogCategoryName = URLUtilities.decode(request.getParameter("cat")); - + // all categories must start with a / if(!this.weblogCategoryName.startsWith("/")) { this.weblogCategoryName = "/"+this.weblogCategoryName; @@ -132,7 +132,7 @@ public void setWeblogCategoryName(String weblogCategory) { } public WeblogCategory getWeblogCategory() { - + if(weblogCategory == null && weblogCategoryName != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -141,12 +141,12 @@ public WeblogCategory getWeblogCategory() { log.error("Error getting weblog category "+weblogCategoryName, ex); } } - + return weblogCategory; } public void setWeblogCategory(WeblogCategory weblogCategory) { this.weblogCategory = weblogCategory; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogTrackbackRequest.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogTrackbackRequest.java index abf0223139..6f32bd3496 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogTrackbackRequest.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogTrackbackRequest.java @@ -33,82 +33,82 @@ * Represents a request to post a weblog entry trackback. */ public class WeblogTrackbackRequest extends WeblogRequest { - + private static Log log = LogFactory.getLog(WeblogTrackbackRequest.class); - + private static final String TRACKBACK_SERVLET = "/roller-ui/rendering/trackback"; - + // lightweight attributes private String blogName = null; private String url = null; private String excerpt = null; private String title = null; private String weblogAnchor = null; - + // heavyweight attributes private WeblogEntry weblogEntry = null; - - + + public WeblogTrackbackRequest() {} - - - public WeblogTrackbackRequest(HttpServletRequest request) + + + public WeblogTrackbackRequest(HttpServletRequest request) throws InvalidRequestException { - + // let our parent take care of their business first // parent determines weblog handle and locale if specified super(request); - + String servlet = request.getServletPath(); - + // we only want the path info left over from after our parents parsing String pathInfo = this.getPathInfo(); - + // was this request bound for the comment servlet? if(servlet == null || !TRACKBACK_SERVLET.equals(servlet)) { throw new InvalidRequestException("not a weblog trackback request, "+ request.getRequestURL()); } - - + + /* * parse path info. we expect ... * * /entry/ - permalink */ if(pathInfo != null && pathInfo.trim().length() > 0) { - + // we should only ever get 2 path elements String[] pathElements = pathInfo.split("/"); if(pathElements.length == 2) { - + String context = pathElements[0]; if("entry".equals(context)) { try { - this.weblogAnchor = + this.weblogAnchor = URLDecoder.decode(pathElements[1], "UTF-8"); } catch (UnsupportedEncodingException ex) { // should never happen log.error(ex); } - + } else { throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - + } else { throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - + } else { // bad request throw new InvalidRequestException("bad path info, "+ request.getRequestURL()); } - - + + /* * parse request parameters * @@ -121,27 +121,27 @@ public WeblogTrackbackRequest(HttpServletRequest request) if(request.getParameter("blog_name") != null) { this.blogName = request.getParameter("blog_name"); } - + if(request.getParameter("url") != null) { this.url = request.getParameter("url"); } - + if(request.getParameter("excerpt") != null) { this.excerpt = request.getParameter("excerpt"); } - + if(request.getParameter("title") != null) { this.title = request.getParameter("title"); } - + // a little bit of validation, trackbacks enforce that all params // must have a value, so any nulls equals a bad request - if(this.blogName == null || this.url == null || + if(this.blogName == null || this.url == null || this.excerpt == null || this.title == null) { throw new InvalidRequestException("bad request data. did not "+ "receive values for all trackback params (blog_name, url, excerpt, title)"); } - + if(log.isDebugEnabled()) { log.debug("name = "+this.blogName); log.debug("url = "+this.url); @@ -192,7 +192,7 @@ public void setWeblogAnchor(String weblogAnchor) { } public WeblogEntry getWeblogEntry() { - + if(weblogEntry == null && weblogAnchor != null) { try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); @@ -201,12 +201,12 @@ public WeblogEntry getWeblogEntry() { log.error("Error getting weblog entry "+weblogAnchor, ex); } } - + return weblogEntry; } public void setWeblogEntry(WeblogEntry weblogEntry) { this.weblogEntry = weblogEntry; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java index 8b4851d71b..3640f3e352 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java @@ -40,51 +40,51 @@ * Cache for planet content. */ public class PlanetCache { - + private static Log log = LogFactory.getLog(PlanetCache.class); - + // a unique identifier for this cache, this is used as the prefix for // roller config properties that apply to this cache public static final String CACHE_ID = "cache.planet"; - + // keep cached content private boolean cacheEnabled = true; private Cache contentCache = null; - + // keep a cached version of last expired time private ExpiringCacheEntry lastUpdateTime = null; private long timeout = 15 * 60 * 1000; - + // reference to our singleton instance private static PlanetCache singletonInstance = new PlanetCache(); - - + + private PlanetCache() { - + cacheEnabled = WebloggerConfig.getBooleanProperty(CACHE_ID+".enabled"); - + Map cacheProps = new HashMap(); cacheProps.put("id", CACHE_ID); Enumeration allProps = WebloggerConfig.keys(); String prop = null; while(allProps.hasMoreElements()) { prop = (String) allProps.nextElement(); - + // we are only interested in props for this cache if(prop.startsWith(CACHE_ID+".")) { - cacheProps.put(prop.substring(CACHE_ID.length()+1), + cacheProps.put(prop.substring(CACHE_ID.length()+1), WebloggerConfig.getProperty(prop)); } } - + log.info("Planet cache = "+cacheProps); - + if(cacheEnabled) { contentCache = CacheManager.constructCache(null, cacheProps); } else { log.warn("Caching has been DISABLED"); } - + // lookup our timeout value String timeoutString = WebloggerConfig.getProperty("cache.planet.timeout"); try { @@ -94,88 +94,88 @@ private PlanetCache() { // ignored ... illegal value } } - - + + public static PlanetCache getInstance() { return singletonInstance; } - - + + public Object get(String key) { - + if(!cacheEnabled) return null; - + Object entry = contentCache.get(key); - + if(entry == null) { log.debug("MISS "+key); } else { log.debug("HIT "+key); } - + return entry; } - - + + public void put(String key, Object value) { - + if(!cacheEnabled) return; - + contentCache.put(key, value); log.debug("PUT "+key); } - - + + public void remove(String key) { - + if(!cacheEnabled) return; - + contentCache.remove(key); log.debug("REMOVE "+key); } - - + + public void clear() { - + if(!cacheEnabled) return; - + contentCache.clear(); this.lastUpdateTime = null; log.debug("CLEAR"); } - - + + public Date getLastModified() { - + Date lastModified = null; - + // first try our cached version if(this.lastUpdateTime != null) { lastModified = (Date) this.lastUpdateTime.getValue(); } - + // still null, we need to get a fresh value if(lastModified == null) { - + // TODO: ROLLER40 last updated for planet lastModified = null; // PlanetFactory.getPlanet().getPlanetManager().getLastUpdated(); - + if (lastModified == null) { lastModified = new Date(); log.warn("Can't get lastUpdate time, using current time instead"); } - + this.lastUpdateTime = new ExpiringCacheEntry(lastModified, this.timeout); } - + return lastModified; } - - + + /** * Generate a cache key from a parsed planet request. * This generates a key of the form ... @@ -192,21 +192,21 @@ public Date getLastModified() { * */ public String generateKey(PlanetRequest planetRequest) { - + StringBuffer key = new StringBuffer(); - + key.append(this.CACHE_ID).append(":"); key.append(planetRequest.getContext()); key.append("/"); key.append(planetRequest.getType()); - + if(planetRequest.getFlavor() != null) { key.append("/").append(planetRequest.getFlavor()); } - + // add language key.append("/").append(planetRequest.getLanguage()); - + if(planetRequest.getFlavor() != null) { // add excerpts if(planetRequest.isExcerpts()) { @@ -218,7 +218,7 @@ public String generateKey(PlanetRequest planetRequest) { key.append("/user=").append(planetRequest.getAuthenticUser()); } } - + // add group if (planetRequest.getGroup() != null) { key.append("/group=").append(planetRequest.getGroup()); @@ -226,5 +226,5 @@ public String generateKey(PlanetRequest planetRequest) { return key.toString(); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java index b7362ea961..ef872f3d97 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java @@ -53,125 +53,125 @@ * Cache for site-wide weblog content. */ public class SiteWideCache implements CacheHandler { - + private static Log log = LogFactory.getLog(SiteWideCache.class); - + // a unique identifier for this cache, this is used as the prefix for // roller config properties that apply to this cache public static final String CACHE_ID = "cache.sitewide"; - + // keep cached content private boolean cacheEnabled = true; private Cache contentCache = null; - + // keep a cached version of last expired time private ExpiringCacheEntry lastUpdateTime = null; private long timeout = 15 * 60 * 1000; - + // reference to our singleton instance private static SiteWideCache singletonInstance = new SiteWideCache(); - - + + private SiteWideCache() { - + cacheEnabled = WebloggerConfig.getBooleanProperty(CACHE_ID+".enabled"); - + Map cacheProps = new HashMap(); cacheProps.put("id", CACHE_ID); Enumeration allProps = WebloggerConfig.keys(); String prop = null; while(allProps.hasMoreElements()) { prop = (String) allProps.nextElement(); - + // we are only interested in props for this cache if(prop.startsWith(CACHE_ID+".")) { - cacheProps.put(prop.substring(CACHE_ID.length()+1), + cacheProps.put(prop.substring(CACHE_ID.length()+1), WebloggerConfig.getProperty(prop)); } } - + log.info(cacheProps); - + if(cacheEnabled) { contentCache = CacheManager.constructCache(this, cacheProps); } else { log.warn("Caching has been DISABLED"); } } - - + + public static SiteWideCache getInstance() { return singletonInstance; } - - + + public Object get(String key) { - + if(!cacheEnabled) return null; - + Object entry = contentCache.get(key); - + if(entry == null) { log.debug("MISS "+key); } else { log.debug("HIT "+key); } - + return entry; } - - + + public void put(String key, Object value) { - + if(!cacheEnabled) return; - + contentCache.put(key, value); log.debug("PUT "+key); } - + public void remove(String key) { - + if(!cacheEnabled) return; - + contentCache.remove(key); log.debug("REMOVE "+key); } - - + + public void clear() { - + if(!cacheEnabled) return; - + contentCache.clear(); this.lastUpdateTime = null; log.debug("CLEAR"); } - - + + public Date getLastModified() { - + Date lastModified = null; - + // first try our cached version if(this.lastUpdateTime != null) { lastModified = (Date) this.lastUpdateTime.getValue(); } - + // still null, we need to get a fresh value if(lastModified == null) { lastModified = new Date(); this.lastUpdateTime = new ExpiringCacheEntry(lastModified, this.timeout); } - + return lastModified; } - - + + /** * Generate a cache key from a parsed weblog page request. * This generates a key of the form ... @@ -190,13 +190,13 @@ public Date getLastModified() { * */ public String generateKey(WeblogPageRequest pageRequest) { - + StringBuffer key = new StringBuffer(); - + key.append(this.CACHE_ID).append(":"); key.append("page/"); key.append(pageRequest.getWeblogHandle()); - + if(pageRequest.getWeblogAnchor() != null) { String anchor = null; try { @@ -205,18 +205,18 @@ public String generateKey(WeblogPageRequest pageRequest) { } catch(UnsupportedEncodingException ex) { // ignored } - + key.append("/entry/").append(anchor); } else { - + if(pageRequest.getWeblogPageName() != null) { key.append("/page/").append(pageRequest.getWeblogPageName()); } - + if(pageRequest.getWeblogDate() != null) { key.append("/").append(pageRequest.getWeblogDate()); } - + if(pageRequest.getWeblogCategoryName() != null) { String cat = null; try { @@ -225,10 +225,10 @@ public String generateKey(WeblogPageRequest pageRequest) { } catch(UnsupportedEncodingException ex) { // ignored } - + key.append("/").append(cat); } - + if("tags".equals(pageRequest.getContext())) { key.append("/tags/"); if(pageRequest.getTags() != null && pageRequest.getTags().size() > 0) { @@ -238,32 +238,32 @@ public String generateKey(WeblogPageRequest pageRequest) { } } } - + if(pageRequest.getLocale() != null) { key.append("/").append(pageRequest.getLocale()); } - + // add page number when applicable if(pageRequest.getWeblogAnchor() == null) { key.append("/page=").append(pageRequest.getPageNum()); } - + // add login state if(pageRequest.getAuthenticUser() != null) { key.append("/user=").append(pageRequest.getAuthenticUser()); } - + // we allow for arbitrary query params for custom pages if(pageRequest.getCustomParams().size() > 0) { String queryString = paramsToString(pageRequest.getCustomParams()); - + key.append("/qp=").append(queryString); } return key.toString(); } - - + + /** * Generate a cache key from a parsed weblog feed request. * This generates a key of the form ... @@ -278,20 +278,20 @@ public String generateKey(WeblogPageRequest pageRequest) { * */ public String generateKey(WeblogFeedRequest feedRequest) { - + StringBuffer key = new StringBuffer(); - + key.append(this.CACHE_ID).append(":"); key.append("feed/"); key.append(feedRequest.getWeblogHandle()); - + key.append("/").append(feedRequest.getType()); key.append("/").append(feedRequest.getFormat()); - + if (feedRequest.getTerm() != null) { key.append("/search/").append(feedRequest.getTerm()); } - + if(feedRequest.getWeblogCategoryName() != null) { String cat = feedRequest.getWeblogCategoryName(); try { @@ -299,54 +299,54 @@ public String generateKey(WeblogFeedRequest feedRequest) { } catch (UnsupportedEncodingException ex) { // should never happen, utf-8 is always supported } - + key.append("/").append(cat); } - + if(feedRequest.getLocale() != null) { key.append("/").append(feedRequest.getLocale()); } - + if(feedRequest.isExcerpts()) { key.append("/excerpts"); } - + if(feedRequest.getTags() != null && feedRequest.getTags().size() > 0) { String[] tags = new String[feedRequest.getTags().size()]; new TreeSet(feedRequest.getTags()).toArray(tags); key.append("/tags/").append(Utilities.stringArrayToString(tags,"+")); - } - + } + return key.toString(); } - - + + /** * A weblog entry has changed. */ public void invalidate(WeblogEntry entry) { - + if(!cacheEnabled) return; - + this.contentCache.clear(); this.lastUpdateTime = null; } - - + + /** * A weblog has changed. */ public void invalidate(Weblog website) { - + if(!cacheEnabled) return; - + this.contentCache.clear(); this.lastUpdateTime = null; } - - + + /** * A bookmark has changed. */ @@ -355,8 +355,8 @@ public void invalidate(WeblogBookmark bookmark) { invalidate(bookmark.getWebsite()); } } - - + + /** * A folder has changed. */ @@ -365,8 +365,8 @@ public void invalidate(WeblogBookmarkFolder folder) { invalidate(folder.getWebsite()); } } - - + + /** * A comment has changed. */ @@ -375,24 +375,24 @@ public void invalidate(WeblogEntryComment comment) { invalidate(comment.getWeblogEntry().getWebsite()); } } - - + + /** * A referer has changed. */ public void invalidate(WeblogReferrer referer) { // ignored } - - + + /** * A user profile has changed. */ public void invalidate(User user) { // ignored } - - + + /** * A category has changed. */ @@ -401,8 +401,8 @@ public void invalidate(WeblogCategory category) { invalidate(category.getWebsite()); } } - - + + /** * A weblog template has changed. */ @@ -411,29 +411,29 @@ public void invalidate(WeblogTemplate template) { invalidate(template.getWebsite()); } } - - + + private String paramsToString(Map map) { - + if(map == null) { return null; } - + StringBuffer string = new StringBuffer(); - + String key = null; String[] value = null; Iterator keys = map.keySet().iterator(); while(keys.hasNext()) { key = (String) keys.next(); value = (String[]) map.get(key); - + if(value != null) { string.append(",").append(key).append("=").append(value[0]); } } - + return Utilities.toBase64(string.toString().substring(1).getBytes()); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java index 067bbbac2c..193dcb80ba 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java @@ -50,122 +50,122 @@ * Currently only supports warming up the feed cache. */ public class WeblogCacheWarmupJob implements Job { - + private static Log log = LogFactory.getLog(WeblogCacheWarmupJob.class); - + // inputs from the user private Map inputs = null; - - + + public void execute() { - + log.debug("starting"); - + // check inputs to see what work we are going to do if(inputs != null) { - + // what weblogs will we handle? List weblogs = (List) inputs.get("weblogs"); if(weblogs == null) { return; } - + // should we do rss entries feeds? if("true".equals((String) inputs.get("feed-entries-rss"))) { this.warmupFeedCache(weblogs, "entries", "rss"); } - + // should we do atom entries feeds? if("true".equals((String) inputs.get("feed-entries-atom"))) { this.warmupFeedCache(weblogs, "entries", "atom"); } } - + log.debug("finished"); } - - + + public Map output() { - return null; + return null; } - - + + public void input(Map input) { this.inputs = input; } - - + + private void warmupFeedCache(List weblogs, String type, String format) { - + if(weblogs == null) { return; } - + // we are working on the feed cache WeblogFeedCache feedCache = WeblogFeedCache.getInstance(); - + long start = System.currentTimeMillis(); - + Iterator allWeblogs = weblogs.iterator(); String weblogHandle = null; while(allWeblogs.hasNext()) { weblogHandle = (String) allWeblogs.next(); log.debug("doing weblog "+weblogHandle); - + try { // we need a feed request to represent the data WeblogFeedRequest feedRequest = new WeblogFeedRequest(); feedRequest.setWeblogHandle(weblogHandle); feedRequest.setType(type); feedRequest.setFormat(format); - - + + // populate the rendering model HashMap model = new HashMap(); Map initData = new HashMap(); initData.put("request", null); initData.put("feedRequest", feedRequest); initData.put("weblogRequest", feedRequest); - + // Load models for feeds String feedModels = WebloggerConfig.getProperty("rendering.feedModels"); ModelLoader.loadModels(feedModels, model, initData, true); - + // TODO: re-enable custom models when they are actually used // Load weblog custom models //ModelLoader.loadCustomModels(weblog, model, initData); - - + + // lookup Renderer we are going to use Renderer renderer = null; Template template = new StaticTemplate("templates/feeds/weblog-"+type+"-"+format+".vm", "velocity"); renderer = RendererManager.getRenderer(template); - - + + // render content. use default size of about 24K for a standard page CachedContent rendererOutput = new CachedContent(24567); renderer.render(model, rendererOutput.getCachedWriter()); - - + + // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); - + // now just put it in the cache String key = feedCache.generateKey(feedRequest); feedCache.put(key, rendererOutput); - + } catch(Exception e) { // bummer, error during rendering log.error("Error rendering for weblog "+weblogHandle, e); } } - + long end = System.currentTimeMillis(); long time = (end-start)*1000; - + log.info("Completed warmup for "+type+"/"+format+" in "+time+" secs."); - + } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java index a12ca8bc05..36f175950b 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java @@ -39,110 +39,110 @@ * Cache for weblog feed content. */ public class WeblogFeedCache { - + private static Log log = LogFactory.getLog(WeblogFeedCache.class); - + // a unique identifier for this cache, this is used as the prefix for // roller config properties that apply to this cache public static final String CACHE_ID = "cache.weblogfeed"; - + // keep cached content private boolean cacheEnabled = true; private Cache contentCache = null; - + // reference to our singleton instance private static WeblogFeedCache singletonInstance = new WeblogFeedCache(); - - + + private WeblogFeedCache() { - + cacheEnabled = WebloggerConfig.getBooleanProperty(CACHE_ID+".enabled"); - + Map cacheProps = new HashMap(); cacheProps.put("id", CACHE_ID); Enumeration allProps = WebloggerConfig.keys(); String prop = null; while(allProps.hasMoreElements()) { prop = (String) allProps.nextElement(); - + // we are only interested in props for this cache if(prop.startsWith(CACHE_ID+".")) { - cacheProps.put(prop.substring(CACHE_ID.length()+1), + cacheProps.put(prop.substring(CACHE_ID.length()+1), WebloggerConfig.getProperty(prop)); } } - + log.info(cacheProps); - + if(cacheEnabled) { contentCache = CacheManager.constructCache(null, cacheProps); } else { log.warn("Caching has been DISABLED"); } } - - + + public static WeblogFeedCache getInstance() { return singletonInstance; } - - + + public Object get(String key, long lastModified) { - + if(!cacheEnabled) return null; - + Object entry = null; - + LazyExpiringCacheEntry lazyEntry = (LazyExpiringCacheEntry) this.contentCache.get(key); if(lazyEntry != null) { entry = lazyEntry.getValue(lastModified); - + if(entry != null) { log.debug("HIT "+key); } else { log.debug("HIT-EXPIRED "+key); } - + } else { log.debug("MISS "+key); } - + return entry; } - - + + public void put(String key, Object value) { - + if(!cacheEnabled) return; - + contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); } - - + + public void remove(String key) { - + if(!cacheEnabled) return; - + contentCache.remove(key); log.debug("REMOVE "+key); } - - + + public void clear() { - + if(!cacheEnabled) return; - + contentCache.clear(); log.debug("CLEAR"); } - - + + /** * Generate a cache key from a parsed weblog feed request. * This generates a key of the form ... @@ -157,19 +157,19 @@ public void clear() { * */ public String generateKey(WeblogFeedRequest feedRequest) { - + StringBuffer key = new StringBuffer(); - + key.append(this.CACHE_ID).append(":"); key.append(feedRequest.getWeblogHandle()); - + key.append("/").append(feedRequest.getType()); key.append("/").append(feedRequest.getFormat()); - + if (feedRequest.getTerm() != null) { key.append("/search/").append(feedRequest.getTerm()); } - + if(feedRequest.getWeblogCategoryName() != null) { String cat = feedRequest.getWeblogCategoryName(); try { @@ -177,25 +177,25 @@ public String generateKey(WeblogFeedRequest feedRequest) { } catch (UnsupportedEncodingException ex) { // should never happen, utf-8 is always supported } - + key.append("/").append(cat); } - + if(feedRequest.getTags() != null && feedRequest.getTags().size() > 0) { Set ordered = new TreeSet(feedRequest.getTags()); - String[] tags = (String[]) ordered.toArray(new String[ordered.size()]); + String[] tags = (String[]) ordered.toArray(new String[ordered.size()]); key.append("/tags/").append(Utilities.stringArrayToString(tags,"+")); - } - + } + if(feedRequest.getLocale() != null) { key.append("/").append(feedRequest.getLocale()); } - + if(feedRequest.isExcerpts()) { key.append("/excerpts"); } - + return key.toString(); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java index 8d2d67d6e6..f772fcf412 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java @@ -40,110 +40,110 @@ * Cache for weblog page content. */ public class WeblogPageCache { - + private static Log log = LogFactory.getLog(WeblogPageCache.class); - + // a unique identifier for this cache, this is used as the prefix for // roller config properties that apply to this cache public static final String CACHE_ID = "cache.weblogpage"; - + // keep cached content private boolean cacheEnabled = true; private Cache contentCache = null; - + // reference to our singleton instance private static WeblogPageCache singletonInstance = new WeblogPageCache(); - - + + private WeblogPageCache() { - + cacheEnabled = WebloggerConfig.getBooleanProperty(CACHE_ID+".enabled"); - + Map cacheProps = new HashMap(); cacheProps.put("id", CACHE_ID); Enumeration allProps = WebloggerConfig.keys(); String prop = null; while(allProps.hasMoreElements()) { prop = (String) allProps.nextElement(); - + // we are only interested in props for this cache if(prop.startsWith(CACHE_ID+".")) { - cacheProps.put(prop.substring(CACHE_ID.length()+1), + cacheProps.put(prop.substring(CACHE_ID.length()+1), WebloggerConfig.getProperty(prop)); } } - + log.info(cacheProps); - + if(cacheEnabled) { contentCache = CacheManager.constructCache(null, cacheProps); } else { log.warn("Caching has been DISABLED"); } } - - + + public static WeblogPageCache getInstance() { return singletonInstance; } - - + + public Object get(String key, long lastModified) { - + if(!cacheEnabled) return null; - + Object entry = null; - + LazyExpiringCacheEntry lazyEntry = (LazyExpiringCacheEntry) this.contentCache.get(key); if(lazyEntry != null) { entry = lazyEntry.getValue(lastModified); - + if(entry != null) { log.debug("HIT "+key); } else { log.debug("HIT-EXPIRED "+key); } - + } else { log.debug("MISS "+key); } - + return entry; } - - + + public void put(String key, Object value) { - + if(!cacheEnabled) return; - + contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); } - - + + public void remove(String key) { - + if(!cacheEnabled) return; - + contentCache.remove(key); log.debug("REMOVE "+key); } - - + + public void clear() { - + if(!cacheEnabled) return; - + contentCache.clear(); log.debug("CLEAR"); } - - + + /** * Generate a cache key from a parsed weblog page request. * This generates a key of the form ... @@ -162,14 +162,14 @@ public void clear() { * */ public String generateKey(WeblogPageRequest pageRequest) { - + StringBuffer key = new StringBuffer(); - + key.append(this.CACHE_ID).append(":"); key.append(pageRequest.getWeblogHandle()); - + if(pageRequest.getWeblogAnchor() != null) { - + String anchor = null; try { // may contain spaces or other bad chars @@ -177,18 +177,18 @@ public String generateKey(WeblogPageRequest pageRequest) { } catch(UnsupportedEncodingException ex) { // ignored } - + key.append("/entry/").append(anchor); } else { - + if(pageRequest.getWeblogPageName() != null) { key.append("/page/").append(pageRequest.getWeblogPageName()); } - + if(pageRequest.getWeblogDate() != null) { key.append("/").append(pageRequest.getWeblogDate()); } - + if(pageRequest.getWeblogCategoryName() != null) { String cat = null; try { @@ -197,10 +197,10 @@ public String generateKey(WeblogPageRequest pageRequest) { } catch(UnsupportedEncodingException ex) { // ignored } - + key.append("/").append(cat); } - + if("tags".equals(pageRequest.getContext())) { key.append("/tags/"); if(pageRequest.getTags() != null && pageRequest.getTags().size() > 0) { @@ -210,54 +210,54 @@ public String generateKey(WeblogPageRequest pageRequest) { } } } - + if(pageRequest.getLocale() != null) { key.append("/").append(pageRequest.getLocale()); } - + // add page number when applicable if(pageRequest.getWeblogAnchor() == null) { key.append("/page=").append(pageRequest.getPageNum()); } - + // add login state if(pageRequest.getAuthenticUser() != null) { key.append("/user=").append(pageRequest.getAuthenticUser()); } - + // we allow for arbitrary query params for custom pages if(pageRequest.getWeblogPageName() != null && pageRequest.getCustomParams().size() > 0) { String queryString = paramsToString(pageRequest.getCustomParams()); - + key.append("/qp=").append(queryString); } - + return key.toString(); } - - + + private String paramsToString(Map map) { - + if(map == null) { return null; } - + StringBuffer string = new StringBuffer(); - + String key = null; String[] value = null; Iterator keys = map.keySet().iterator(); while(keys.hasNext()) { key = (String) keys.next(); value = (String[]) map.get(key); - + if(value != null) { string.append(",").append(key).append("=").append(value[0]); } } - + return Utilities.toBase64(string.toString().substring(1).getBytes()); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java index 0c7904fe9b..ae9e87892f 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java @@ -34,34 +34,34 @@ /** * This is a simple template file loader that loads templates * from the Roller instance instead of plain files. - * + * * RollerResourceLoader makes use of WebloggerFactory. - * + * * @author
    Lance Lavandowska * @version $Id: RollerResourceLoader.java,v 1.9 2005/01/15 03:32:49 snoopdave Exp $ */ public class RollerResourceLoader extends ResourceLoader { - + private static Log mLogger = LogFactory.getLog(RollerResourceLoader.class); - - + + public void init(ExtendedProperties configuration) { if (mLogger.isDebugEnabled()) { mLogger.debug(configuration); } } - - + + public boolean isSourceModified(Resource resource) { return (resource.getLastModified() != readLastModified(resource, "checking timestamp")); } - - + + public long getLastModified(Resource resource) { return readLastModified(resource, "getting timestamp"); } - + /** * Get an InputStream so that the Runtime can build a * template with it. @@ -71,15 +71,15 @@ public long getLastModified(Resource resource) { */ public InputStream getResourceStream(String name) throws ResourceNotFoundException { - + if (name == null || name.length() == 0) { throw new ResourceNotFoundException("Need to specify a template name!"); } - + try { - WeblogTemplate page = + WeblogTemplate page = WebloggerFactory.getWeblogger().getWeblogManager().getPage(name); - + if (page == null) { throw new ResourceNotFoundException( "RollerResourceLoader: page \"" + @@ -98,8 +98,8 @@ public InputStream getResourceStream(String name) throw new ResourceNotFoundException(msg); } } - - + + /** * Fetches the last modification time of the resource * @@ -109,15 +109,15 @@ public InputStream getResourceStream(String name) * @return timestamp as long */ private long readLastModified(Resource resource, String i_operation) { - + /* * get the template name from the resource */ String name = resource.getName(); try { - WeblogTemplate page = + WeblogTemplate page = WebloggerFactory.getWeblogger().getWeblogManager().getPage(name); - + if (mLogger.isDebugEnabled()) { mLogger.debug(name + ": resource=" + resource.getLastModified() + " vs. page=" + page.getLastModified().getTime()); @@ -128,5 +128,5 @@ private long readLastModified(Resource resource, String i_operation) { } return 0; } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocity.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocity.java index 2cb678433d..57bba1a68d 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocity.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocity.java @@ -37,49 +37,49 @@ * access to the instance via the Singleton getInstance() method. */ public class RollerVelocity { - + public static final String VELOCITY_CONFIG = "/WEB-INF/velocity.properties"; - + private static Log log = LogFactory.getLog(RollerVelocity.class); - + private static VelocityEngine velocityEngine = null; - - + + static { log.info("Initializing Velocity Rendering Engine"); - + // initialize the Velocity engine Properties velocityProps = new Properties(); - + try { InputStream instream = RollerContext.getServletContext().getResourceAsStream(VELOCITY_CONFIG); - + velocityProps.load(instream); - + // need to dynamically add old macro libraries if they are enabled if(WebloggerConfig.getBooleanProperty("rendering.legacyModels.enabled")) { String macroLibraries = (String) velocityProps.get("velocimacro.library"); String oldLibraries = WebloggerConfig.getProperty("velocity.oldMacroLibraries"); - + // set the new value velocityProps.setProperty("velocimacro.library", oldLibraries+","+macroLibraries); } - + log.debug("Velocity engine props = "+velocityProps); - + // construct the VelocityEngine velocityEngine = new VelocityEngine(); - + // init velocity with our properties velocityEngine.init(velocityProps); - + } catch (Exception e) { throw new RuntimeException(e); } } - - + + /** * Access to the VelocityEngine. * @@ -89,8 +89,8 @@ public class RollerVelocity { public static VelocityEngine getEngine() { return velocityEngine; } - - + + /** * Convenience static method for looking up a template. */ @@ -98,8 +98,8 @@ public static Template getTemplate(String name) throws ResourceNotFoundException, ParseErrorException, Exception { return velocityEngine.getTemplate(name); } - - + + /** * Convenience static method for looking up a template. */ @@ -107,5 +107,5 @@ public static Template getTemplate(String name, String encoding) throws ResourceNotFoundException, ParseErrorException, Exception { return velocityEngine.getTemplate(name, encoding); } - + } diff --git a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java index ccc888c903..f2abd60987 100644 --- a/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java +++ b/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java @@ -47,101 +47,101 @@ * @author Allen Gilliland */ public class ThemeResourceLoader extends ResourceLoader { - - private static Log mLogger = + + private static Log mLogger = LogFactory.getFactory().getInstance(ThemeResourceLoader.class); - - + + public void init(ExtendedProperties configuration) { mLogger.debug(configuration); } - - + + public InputStream getResourceStream( String name ) throws ResourceNotFoundException { - + mLogger.debug("Looking up resource named ... "+name); - + if (name == null || name.length() < 1) { throw new ResourceNotFoundException("Need to specify a template name!"); } - + try { // parse the name ... theme templates name are :