cleanup + misc. fixes
authorzapata <zapata>
Sat, 1 Oct 2005 18:40:40 +0000 (18:40 +0000)
committerzapata <zapata>
Sat, 1 Oct 2005 18:40:40 +0000 (18:40 +0000)
51 files changed:
etc/producer/article.template
source/Mir.java
source/OpenMir.java
source/default.properties
source/mir/config/MirPropertiesConfiguration.java
source/mir/log/log4j/LoggerImpl.java
source/mir/servlet/AbstractServlet.java
source/mir/servlet/AdminServletModule.java [new file with mode: 0755]
source/mir/servlet/ServletModule.java
source/mir/servlet/ServletModuleDispatch.java [deleted file]
source/mir/servlet/ServletModuleExc.java
source/mir/util/HTMLRoutines.java
source/mir/util/URLBuilder.java
source/mircoders/global/MirGlobal.java
source/mircoders/localizer/MirCachingLocalizerDecorator.java
source/mircoders/localizer/MirLocalizer.java
source/mircoders/localizer/MirOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicArticlePostingHandler.java
source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java
source/mircoders/localizer/basic/MirBasicEmailArticleHandler.java
source/mircoders/localizer/basic/MirBasicLocalizer.java
source/mircoders/localizer/basic/MirBasicMediaLocalizer.java
source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java
source/mircoders/media/MediaHandlerImagesExtern.java
source/mircoders/media/MediaHelper.java
source/mircoders/pdf/PDFGenerator.java
source/mircoders/servlet/ServletHelper.java
source/mircoders/servlet/ServletModuleAbuse.java
source/mircoders/servlet/ServletModuleAdmin.java
source/mircoders/servlet/ServletModuleArticleType.java
source/mircoders/servlet/ServletModuleAudio.java
source/mircoders/servlet/ServletModuleBreaking.java
source/mircoders/servlet/ServletModuleComment.java
source/mircoders/servlet/ServletModuleCommentStatus.java
source/mircoders/servlet/ServletModuleContent.java
source/mircoders/servlet/ServletModuleFileEdit.java
source/mircoders/servlet/ServletModuleHidden.java
source/mircoders/servlet/ServletModuleImages.java
source/mircoders/servlet/ServletModuleLanguage.java
source/mircoders/servlet/ServletModuleLocalizer.java
source/mircoders/servlet/ServletModuleMediaType.java
source/mircoders/servlet/ServletModuleMediafolder.java
source/mircoders/servlet/ServletModuleMessage.java
source/mircoders/servlet/ServletModuleOpenIndy.java
source/mircoders/servlet/ServletModuleOtherMedia.java
source/mircoders/servlet/ServletModuleProducer.java
source/mircoders/servlet/ServletModuleTopics.java
source/mircoders/servlet/ServletModuleUploadedMedia.java
source/mircoders/servlet/ServletModuleUsers.java
source/mircoders/servlet/ServletModuleVideo.java

index b67cbbd..cf4695a 100755 (executable)
               <img src="../../../img/mail_small.gif" width="12" height="10" border="0" alt="-"> ${lang("article.email.prefix")}: <a href="mailto:${utility.encodeHTML(article.creator_email)}">${utility.encodeHTML(article.creator_email)}</a><br>
             </if>
             <if article.creator_main_url>
-              <img src="../../../img/link_small.gif" width="12" height="10" border="0" alt=""> ${lang("article.homepage.prefix")}: <a href="${utitlity.encodeHTML(article.creator_main_url)}" target="extern">${utility.encodeHTML(article.creator_main_url)}</a><br>
+              <img src="../../../img/link_small.gif" width="12" height="10" border="0" alt=""> ${lang("article.homepage.prefix")}: <a href="${utility.encodeHTML(article.creator_main_url)}" target="extern">${utility.encodeHTML(article.creator_main_url)}</a><br>
             </if>
             </font>
             </p>
index 7fdcd32..5545de5 100755 (executable)
@@ -43,7 +43,6 @@ import javax.servlet.http.*;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
-import java.lang.reflect.Method;
 import java.util.*;
 
 import mircoders.module.ModuleUsers;
@@ -53,7 +52,7 @@ import mircoders.entity.EntityUsers;
 
 public class Mir extends AbstractServlet {
   private static ModuleUsers usersModule = null;
-  private final static Map servletModuleInstanceHash = new HashMap();
+  private final static Map servletModules = new HashMap();
   private static Locale fallbackLocale = null;
 
   private static List loginLanguages = null;
@@ -153,9 +152,7 @@ public class Mir extends AbstractServlet {
       return user;
     }
     catch (Throwable t) {
-      t.printStackTrace();
-
-      throw new ServletException(t.toString());
+      throw new ServletException(t.getMessage());
     }
   }
 
@@ -191,7 +188,6 @@ public class Mir extends AbstractServlet {
           moduleName="Admin";
         }
 
-
         if (moduleName.equals("login")) {
           String target = (String) session.getAttribute("login.target");
 
@@ -210,8 +206,8 @@ public class Mir extends AbstractServlet {
         }
         else {
           try {
-            ServletModule servletModule = getServletModuleForName(moduleName);
-            ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);
+            AdminServletModule servletModule = getServletModuleForName(moduleName);
+            servletModule.handleRequest(aRequest, aResponse);
 
             sessionConnectTime = System.currentTimeMillis() - startTime;
             logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
@@ -231,8 +227,6 @@ public class Mir extends AbstractServlet {
       }
     }
     catch (Throwable t) {
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
       throw new ServletException(t.toString());
     }
   }
@@ -240,42 +234,12 @@ public class Mir extends AbstractServlet {
   /**
    * caching routine to get a module for a module name
    *
-   * @param moduleName the module name
+   * @param aModuleName the module name
    * @return the requested module
    * @throws ServletModuleExc
    */
-
-  private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
-    // Instance in Map ?
-    if (!servletModuleInstanceHash.containsKey(moduleName)) {
-      // was not found in hash...
-      try {
-        Class theServletModuleClass = null;
-
-        try {
-          // first we try to get ServletModule from stern.che3.servlet
-          theServletModuleClass =
-            Class.forName("mircoders.servlet.ServletModule" + moduleName);
-        }
-        catch (ClassNotFoundException e) {
-          // on failure, we try to get it from lib-layer
-          theServletModuleClass =
-            Class.forName("mir.servlet.ServletModule" + moduleName);
-        }
-
-        Method m = theServletModuleClass.getMethod("getInstance", null);
-        ServletModule smod = (ServletModule) m.invoke(null, null);
-
-        // we put it into map for further reference
-        servletModuleInstanceHash.put(moduleName, smod);
-
-        return smod;
-      }
-      catch (Exception e) {
-        throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
-      }
-    }
-               return (ServletModule) servletModuleInstanceHash.get(moduleName);
+  private static AdminServletModule getServletModuleForName(String aModuleName) throws ServletModuleExc {
+    return ServletHelper.getServletModule(aModuleName);
   }
 
   private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
index ebb3213..32c73a9 100755 (executable)
@@ -37,7 +37,6 @@ import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
 import mir.servlet.AbstractServlet;
-import mir.servlet.ServletModuleDispatch;
 import mir.servlet.ServletModuleUserExc;
 import mir.util.ExceptionRoutines;
 import mircoders.servlet.ServletModuleOpenIndy;
@@ -46,21 +45,29 @@ import mircoders.servlet.ServletModuleOpenIndy;
  *  OpenMir.java - main servlet for open posting and comment feature to articles
  *
  *  @author RK 1999-2001, the mir-coders group
- *  @version $Id: OpenMir.java,v 1.35.2.6 2005/08/21 17:09:18 zapata Exp $
+ *  @version $Id: OpenMir.java,v 1.35.2.7 2005/10/01 18:40:40 zapata Exp $
  *
  */
 
 
 public class OpenMir extends AbstractServlet {
-  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
-        throws ServletException, IOException {
-    if ((configuration.getString("RootUri") == null) ||
-        configuration.getString("RootUri").equals("")) {
+  private ServletModuleOpenIndy servletModule;
+
+  private synchronized ServletModuleOpenIndy getServletModule() {
+    if (servletModule == null) {
+      servletModule = new ServletModuleOpenIndy();
+    }
+
+    return servletModule;
+  }
+
+  public void process(HttpServletRequest aRequest,
+                      HttpServletResponse aResponse) throws ServletException, IOException {
+    if ("".equals(configuration.getString("RootUri", ""))) {
       configuration.setProperty("RootUri", aRequest.getContextPath());
     }
 
     long startTime = System.currentTimeMillis();
-    long sessionConnectTime=0;
 
     HttpSession session = aRequest.getSession();
 
@@ -75,30 +82,34 @@ public class OpenMir extends AbstractServlet {
       // call appropriate ServletModuleOpenIndy method 
       // as specified in http request 
       // example: OpenMir?do=opensession calls the opensession method
-      ServletModuleDispatch.dispatch(ServletModuleOpenIndy.getInstance(), aRequest, aResponse);
+
+      getServletModule().handleRequest(aRequest, aResponse);
     }
     catch (Throwable e) {
       logger.warn("Error in open publishing", e);
 
       Throwable cause = ExceptionRoutines.traceCauseException(e);
 
-      if (cause instanceof ServletModuleUserExc)
+      if (cause instanceof ServletModuleUserExc) {
         handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
-      else
+      }
+      else {
         handleError(aRequest, aResponse, aResponse.getWriter(), cause);
+      }
     }
 
-    sessionConnectTime = System.currentTimeMillis() - startTime;
+    long sessionConnectTime = System.currentTimeMillis() - startTime;
+
     logger.debug("EXECTIME (ServletModuleOpenIndy): " + sessionConnectTime + " ms");
   }
 
   private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
-                               PrintWriter out, ServletModuleUserExc anException) {
-    ((ServletModuleOpenIndy) ServletModuleOpenIndy.getInstance()).handleUserError(aRequest, aResponse, out, anException);
+                               PrintWriter anOutputWriter, ServletModuleUserExc anException) {
+    getServletModule().handleUserError(aRequest, aResponse, anOutputWriter, anException);
   }
 
   private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
-    ((ServletModuleOpenIndy) ServletModuleOpenIndy.getInstance()).handleError(aRequest, aResponse, out, anException);
+    getServletModule().handleError(aRequest, aResponse, out, anException);
   }
 
   public String getServletInfo(){
index 208d2e7..cc015f1 100755 (executable)
@@ -2,7 +2,7 @@
 # GENERAL SETUP
 #
 # This is a full list of defaults options. To configure your site
-# do NOT change this file. You can override all of these values in 
+# do NOT change this file. You can override all of these values in
 # your etc/config.properties
 #
 
@@ -17,7 +17,6 @@ Mir.Public-email.address=mir-coders@lists.indymedia.org
 Mir.Public-email.name=mir-coders mailinglist
 
 Mir.Version=1.1.0rc0
-DirectOpenposting=yes
 
 # The name of the abuse config file (relative to the WEB-INF dir)
 Abuse.Config=abuse.properties
@@ -86,7 +85,7 @@ Mir.Localizer.OpenPosting.GeneratorLibrary= default=freemarker(etc/open/)
 # be presented?
 # 0 = links, 1 = checkboxes, 2 = a listbox
 Mir.Localizer.Admin.ListOperationsFlavor=2
-                            
+
 # Article previews, a comma seperated list of name = generator
 Mir.Localizer.Admin.ArticlePreview = \
   default = preview::article.template
@@ -394,7 +393,7 @@ Mir.DefaultDateTimeFormat = yyyy-MM-dd HH:mm
 Localizer.OpenSession.PersistentUploadedFiles = 0
 
 # Should support for ftp-like uploads (uploads done
-# outside of mir, but included into postings) be 
+# outside of mir, but included into postings) be
 # supported at all?
 Localizer.OpenSession.AllowFTPUploads = 0
 
index 198ff3a..2b3089e 100755 (executable)
@@ -165,22 +165,25 @@ public class MirPropertiesConfiguration extends ExtendedProperties {
 
   /**
    * @return the value of this property as String
-   * @param key the key of the property
-   * @param defaultValue the default value of this property if it is null
+   * @param aKey the key of the property
+   * @param aDefaultValue the default value of this property if it is null
    * @see org.apache.commons.collections.ExtendedProperties#getString(java.lang.String, java.lang.String)
    */
-  public String getString(String key, String defaultValue) {
-    Object object = getProperty(key);
-    if(object == null){
-      if (defaultValue == null) {
-        return new String();
-      }
-      return defaultValue;
+  public String getString(String aKey, String aDefaultValue) {
+    if (aDefaultValue == null) {
+      aDefaultValue = "";
     }
-    if (object instanceof String) {
-      return (String)object;
+    Object result = getProperty(aKey);
+
+    if (result == null){
+      return aDefaultValue;
     }
-    return object.toString();
+
+    if (result instanceof String) {
+      return (String) result;
+    }
+
+    return result.toString();
   }
 
   public boolean getBoolean(String aKey, boolean aDefaultValue) {
@@ -196,7 +199,7 @@ public class MirPropertiesConfiguration extends ExtendedProperties {
     String value = getString(aKey).trim();
 
     return "1".equals(value) || "y".equalsIgnoreCase(value) ||
-        "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value);
+           "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value);
   }
 
   /**
index 582854d..42c40e9 100755 (executable)
@@ -41,7 +41,7 @@ import org.apache.log4j.PropertyConfigurator;
 
 
 public class LoggerImpl implements mir.log.Logger {
-  private static Map loggers = new HashMap();
+  private static final Map loggers = new HashMap();
 
   public LoggerImpl() throws LoggerExc {
     reload();
index d42d2e9..ac3fdcb 100755 (executable)
@@ -52,7 +52,7 @@ import mircoders.global.MirGlobal;
  * Copyright:    Copyright (c) 2001, 2002
  * Company:      Mir-coders group
  * @author       idfx, the Mir-coders group
- * @version      $Id: AbstractServlet.java,v 1.30.2.9 2005/08/21 17:09:21 zapata Exp $
+ * @version      $Id: AbstractServlet.java,v 1.30.2.10 2005/10/01 18:40:40 zapata Exp $
  */
 
 public abstract class AbstractServlet extends HttpServlet {
@@ -72,9 +72,9 @@ public abstract class AbstractServlet extends HttpServlet {
   /**
    * Bind the language to the session
    */
-  protected void setLanguage(HttpSession session, String language) {
-    session.setAttribute("language", language);
-    session.setAttribute("locale", new Locale(language, ""));
+  protected void setLanguage(HttpSession aRequest, String aLanguage) {
+    aRequest.setAttribute("language", aLanguage);
+    aRequest.setAttribute("locale", new Locale(aLanguage, ""));
   }
 
   /**
@@ -105,9 +105,8 @@ public abstract class AbstractServlet extends HttpServlet {
    */
   protected String getAcceptLanguage(HttpServletRequest aRequest) {
     Locale locale = aRequest.getLocale();
-    String language = locale.getLanguage();
 
-    return language;
+    return locale.getLanguage();
   }
 
   /**
@@ -134,9 +133,8 @@ public abstract class AbstractServlet extends HttpServlet {
       throw new ServletException("can't get localizer: " + t.toString());
     }
 
-    Connection connection;
     try {
-      connection = MirGlobal.getDatabaseEngine().obtainConnection();
+      Connection connection = MirGlobal.getDatabaseEngine().obtainConnection();
       MirGlobal.getDatabaseEngine().releaseConnection(connection);
     }
     catch (Throwable t) {
@@ -159,37 +157,34 @@ public abstract class AbstractServlet extends HttpServlet {
     catch (NoSuchMethodException e) {
     }
     catch (SecurityException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
+      logger.error(e.getMessage(), e);
     }
     catch (IllegalArgumentException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
+      logger.error(e.getMessage(), e);
     }
     catch (IllegalAccessException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
+      logger.error(e.getMessage(), e);
     }
     catch (InvocationTargetException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
+      logger.error(e.getMessage(), e);
     }
   }
 
-  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    doPost(request, response);
+  protected final void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException {
+    doPost(aRequest, aResponse);
   }
 
-  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {
-      configuration.setProperty("RootUri", request.getContextPath());
+  protected final void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException {
+    if ((configuration.getString("RootUri") == null) ||
+         configuration.getString("RootUri").equals("")) {
+      configuration.setProperty("RootUri", aRequest.getContextPath());
     }
 
-    setEncoding(request);
-    process(request, response);
+    setEncoding(aRequest);
+    process(aRequest, aResponse);
   }
 
-  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
+  public abstract void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException;
 
   /**
    * Selects the language for the response.
diff --git a/source/mir/servlet/AdminServletModule.java b/source/mir/servlet/AdminServletModule.java
new file mode 100755 (executable)
index 0000000..402b5c5
--- /dev/null
@@ -0,0 +1,425 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.servlet;
+
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.module.AbstractModule;
+import mir.module.ModuleExc;
+import mir.storage.Database;
+import mir.util.HTTPRequestParser;
+import mir.util.URLBuilder;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.servlet.ServletHelper;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.io.IOException;
+
+/**
+ *
+ */
+
+public abstract class AdminServletModule extends ServletModule {
+  protected AbstractModule mainModule;
+  protected String definition;
+  private EntityAdapterModel model;
+
+  protected String listGenerator;
+  protected String editGenerator;
+  protected String deleteConfirmationGenerator;
+  protected int nrEntitiesPerListPage;
+
+  /** the list of parameters that need to be propagated in the list */
+  private Set propagatedParameters = new HashSet();
+
+  protected void addPropagatedParameter(String aParameter) {
+    propagatedParameters.add(aParameter);
+  }
+
+  protected AdminServletModule(){
+    addPropagatedParameter("searchfield");
+    addPropagatedParameter("searchtext");
+    addPropagatedParameter("searchispublished");
+    addPropagatedParameter("searchstatus");
+    addPropagatedParameter("searchorder");
+
+    definition = null;
+    try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+    }
+    catch (MirLocalizerExc e) {
+      getLogger().error("Can't create model: " + e.toString());
+
+      throw new ServletModuleFailure("Can't retrieve model", e);
+    }
+
+    listGenerator = getConfiguration().getString("ServletModule." + getName() + ".ListTemplate");
+    editGenerator = getConfiguration().getString("ServletModule." + getName() + ".EditTemplate");
+    deleteConfirmationGenerator = getConfiguration().getString("ServletModule." + getName() + ".DeleteConfirmationTemplate");
+    nrEntitiesPerListPage =
+        getConfiguration().getInt("ServletModule."+getName()+".ListSize",
+        getConfiguration().getInt("ServletModule.Default.ListSize", 20));
+
+  }
+
+  protected EntityAdapterModel getModel() {
+    return model;
+  }
+
+  protected void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {
+    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + anObject, aDescription);
+  }
+
+  /**
+   * Function to specify the default ordering for lists. May be overridden.
+   */
+  protected String getDefaultListOrdering() {
+
+    if (mainModule!=null && mainModule.getStorageObject()!=null &&
+        mainModule.getStorageObject().hasField("webdb_create")) {
+      return "webdb_create desc";
+    }
+    else {
+      return "id asc";
+    }
+  }
+
+  /**
+   * Generic list servlet method
+   */
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String where = requestParser.getParameter("where");
+    String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());
+    int offset = requestParser.getIntegerWithDefault("offset", 0);
+
+    returnList(aRequest, aResponse, where, order, offset);
+  }
+
+
+  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+                         String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
+    returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, Collections.EMPTY_MAP);
+  }
+
+  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+                         String aWhereClause, String anOrderByClause, int anOffset,
+                         Map anOverridingRequestParameters) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest, anOverridingRequestParameters);
+    URLBuilder urlBuilder = new URLBuilder();
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+      List list =
+         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
+
+      responseData.put("nexturl", null);
+      responseData.put("prevurl", null);
+      responseData.put("module", getName());
+
+      urlBuilder.setValue("module", getName());
+      urlBuilder.setValue("do", "list");
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+
+      urlBuilder.setValue("offset", anOffset);
+      responseData.put("offset" , Integer.toString(anOffset));
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      propagateFields(requestParser, urlBuilder, responseData);
+
+      if (list.size()>=nrEntitiesPerListPage) {
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
+        responseData.put("nexturl" , urlBuilder.getQuery());
+      }
+
+      if (anOffset>0) {
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
+        responseData.put("prevurl" , urlBuilder.getQuery());
+      }
+
+      responseData.put("entities", list);
+      responseData.put("from" , Integer.toString(anOffset+1));
+      responseData.put("count", "?");
+      responseData.put("to", Integer.toString(anOffset+list.size()-1));
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {
+    try {
+      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+      responseData.put("module", getName());
+      responseData.put("entity", anObject);
+      responseData.put("new", Boolean.valueOf(anIsNew));
+
+
+      urlBuilder.setValue("module", getName());
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+      if (anIsNew) {
+        urlBuilder.setValue("do", "add");
+      }
+      else {
+        urlBuilder.setValue("id", anId);
+        urlBuilder.setValue("do", "edit");
+      }
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * Generic add servlet method
+   */
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+
+    Map object = new HashMap();
+
+    Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
+
+    while (i.hasNext()) {
+      object.put(i.next(), "");
+    }
+
+    initializeNewObject(object, aRequest, aResponse);
+
+    editObject(aRequest, aResponse, object, true, null);
+  }
+
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+  }
+
+  /**
+   * Generic edit servlet method
+   */
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    edit(aRequest, aResponse, aRequest.getParameter("id"));
+  }
+
+  /**
+   */
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * Generic update servlet method
+   */
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      String id = aRequest.getParameter("id");
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+      mainModule.set(withValues);
+
+      logAdminUsage(aRequest, id, "object modified");
+
+      String returnUrl = requestParser.getParameter("returnurl");
+
+      if (returnUrl!=null) {
+        ServletHelper.redirect(aResponse, returnUrl);
+      }
+      else {
+        edit(aRequest, aResponse, id);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * Generic insert servlet method
+   */
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());
+
+      String id = processInstertedObject(object, aRequest, aResponse);
+
+      logAdminUsage(aRequest, id, "object inserted");
+
+      String returnUrl = requestParser.getParameter("returnurl");
+
+      if (returnUrl!=null) {
+        ServletHelper.redirect(aResponse, returnUrl);
+      }
+      else {
+        edit(aRequest, aResponse, id);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *
+   */
+  public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      return mainModule.add(anObject);
+    }
+    catch (ModuleExc t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  /**
+   * Generic delete confirmation servlet method
+   */
+  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      String idParam = aRequest.getParameter("id");
+      String confirmParam = aRequest.getParameter("confirm");
+
+      if (confirmParam != null && !"".equals(confirmParam)) {
+        mainModule.deleteById(idParam);
+        logAdminUsage(aRequest, idParam, "object deleted");
+        ServletHelper.redirect(aResponse, aRequest.getParameter("okurl"));
+      }
+      else {
+        ServletHelper.redirect(aResponse, aRequest.getParameter("cancelurl"));
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  /**
+   * Generic delete servlet method
+   */
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    String idParam = aRequest.getParameter("id");
+
+    if (idParam == null) {
+      throw new ServletModuleExc("Invalid call to delete: no id supplied");
+    }
+
+    Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+    responseData.put("module", getName());
+    responseData.put("id", idParam);
+    responseData.put("cancelurl", aRequest.getParameter("cancelurl"));
+    responseData.put("okurl", aRequest.getParameter("okurl"));
+
+    try {
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);
+    }
+    catch (IOException e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * Gets the fields from a httprequest and matches them with the metadata from
+   * the database object. Returns the keys that match, with their values.
+   *
+   * @return Map with the values
+   */
+  public Map getIntersectingValues(HttpServletRequest aRequest, Database aDatabase)
+      throws ServletModuleExc, ServletModuleFailure {
+
+    HTTPRequestParser parser = new HTTPRequestParser(aRequest);
+
+    List fields = aDatabase.getFieldNames();
+
+    Map result = new HashMap();
+    for (int i = 0; i < fields.size(); i++) {
+      String aField = (String) fields.get(i);
+
+      String aValue = parser.getParameter(aField);
+      if (aValue != null) {
+        result.put(aField, aValue);
+      }
+    }
+
+    return result;
+  }
+
+  private void propagateFields(HTTPRequestParser aRequest, URLBuilder aUrlBuilder, Map aResponseData) {
+    Iterator i = propagatedParameters.iterator();
+    while (i.hasNext()) {
+      String parameter = (String) i.next();
+      String value = aRequest.getParameter(parameter);
+      aUrlBuilder.setValue(parameter, value);
+      aResponseData.put(parameter, value);
+    }
+  }
+}
\ No newline at end of file
index 30aadc5..18c46c8 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.servlet;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityAdapterEngine;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.storage.Database;
-import mir.util.HTTPRequestParser;
-import mir.util.URLBuilder;
-import mircoders.global.MirGlobal;
-import mircoders.localizer.MirLocalizerExc;
-import mircoders.servlet.ServletHelper;
-
-/**
- *
- */
-
-public abstract class ServletModule {
-  public String defaultAction;
-  protected LoggerWrapper logger;
-  protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
-  private static Locale fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");
-
-  protected AbstractModule mainModule;
-  protected String definition;
-  protected EntityAdapterModel model;
-
-  protected String listGenerator;
-  protected String editGenerator;
-  protected String deleteConfirmationGenerator;
-  protected int nrEntitiesPerListPage;
-
-  /** the list of parameters that need to be propagated in the list */
-  protected List propagatedParameters = new ArrayList();
-
-  public ServletModule(){
-    propagatedParameters.add("searchfield");
-    propagatedParameters.add("searchtext");
-    propagatedParameters.add("searchispublished");
-    propagatedParameters.add("searchstatus");
-    propagatedParameters.add("searchorder");
-
-    definition = null;
-    try {
-      model = MirGlobal.localizer().dataModel().adapterModel();
-    }
-    catch (MirLocalizerExc e) {
-      logger.error("Can't create model: " + e.toString());
-      throw new ServletModuleFailure("Can't retrieve model", e);
-    }
-
-    listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate");
-    editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate");
-    deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate");
-    nrEntitiesPerListPage =
-        configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize",
-        configuration.getInt("ServletModule.Default.ListSize", 20));
-
-  }
-
-
-  public void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {
-    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + anObject, aDescription);
-  }
-
-  /**
-   * Singleton instance retrievel method. MUST be overridden in subclasses.
-   *
-   * @return ServletModule the single instance of the servletmodule class
-   */
-  public static ServletModule getInstance() {
-    return null;
-  }
-
-  /**
-   * Return the module name
-   */
-  protected String getOperationModuleName() {
-    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
-  }
-
-  public static Locale[] getLocales(HttpServletRequest aRequest) {
-    return new Locale[] { getLocale(aRequest), fallbackLocale };
-  }
-
-  /**
-   * Return the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public static Locale getLocale(HttpServletRequest aRequest) {
-    Locale locale = null;
-    HttpSession session = aRequest.getSession(false);
-    if (session != null) {
-      // session can be null in case of logout
-      locale = (Locale) session.getAttribute("locale");
-    }
-    // if there is nothing in the session get it fron the accept-language
-    if (locale == null) {
-      locale = aRequest.getLocale();
-    }
-    return locale;
-  }
-
-  /**
-   * get the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public Locale getFallbackLocale(HttpServletRequest aRequest) {
-    return fallbackLocale;
-  }
-
-  /**
-   * Function to specify the default ordering for lists. May be overridden.
-   *
-   *
-   * @return
-   */
-  public String getDefaultListOrdering() {
-
-    if (mainModule!=null && mainModule.getStorageObject()!=null) {
-      if (mainModule.getStorageObject().hasField("webdb_create"))
-        return "webdb_create desc";
-    }
-
-    return "id asc";
-  }
-
-  /**
-   * Generic list servlet method
-   */
-
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String where = requestParser.getParameter("where");
-    String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());
-    int offset = requestParser.getIntegerWithDefault("offset", 0);
-
-    returnList(aRequest, aResponse, where, order, offset);
-  }
-
-
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
-    returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, Collections.EMPTY_MAP);
-  }
-
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
-     String aWhereClause, String anOrderByClause, int anOffset, Map anOverridingRequestParameters) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest, anOverridingRequestParameters);
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      List list =
-         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
-
-      responseData.put("nexturl", null);
-      responseData.put("prevurl", null);
-      responseData.put("module", getOperationModuleName());
-
-      urlBuilder.setValue("module", getOperationModuleName());
-      urlBuilder.setValue("do", "list");
-      urlBuilder.setValue("where", aWhereClause);
-      urlBuilder.setValue("order", anOrderByClause);
-
-
-      urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
-      responseData.put("thisurl" , urlBuilder.getQuery());
-
-      propagateFields(requestParser, urlBuilder, responseData);
-
-      if (list.size()>=nrEntitiesPerListPage) {
-        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
-        responseData.put("nexturl" , urlBuilder.getQuery());
-      }
-
-      if (anOffset>0) {
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
-        responseData.put("prevurl" , urlBuilder.getQuery());
-      }
-
-      responseData.put("entities", list);
-      responseData.put("from" , Integer.toString(anOffset+1));
-      responseData.put("count", "?");
-      responseData.put("to", Integer.toString(anOffset+list.size()-1));
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {
-    try {
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      responseData.put("module", getOperationModuleName());
-      responseData.put("entity", anObject);
-      responseData.put("new", new Boolean(anIsNew));
-
-
-      urlBuilder.setValue("module", getOperationModuleName());
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
-      if (anIsNew)
-        urlBuilder.setValue("do", "add");
-      else {
-        urlBuilder.setValue("id", anId);
-        urlBuilder.setValue("do", "edit");
-      }
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic add servlet method
-   */
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-
-    Map object = new HashMap();
-
-    Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
-
-    while (i.hasNext())
-      object.put(i.next(), "");
-
-    initializeNewObject(object, aRequest, aResponse);
-
-    editObject(aRequest, aResponse, object, true, null);
-  }
-
-  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-  }
-
-  /**
-   * Generic edit servlet method
-   */
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    edit(aRequest, aResponse, aRequest.getParameter("id"));
-  }
-
-  /**
-   */
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic update servlet method
-   */
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      String id = aRequest.getParameter("id");
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
-      mainModule.set(withValues);
-
-      logAdminUsage(aRequest, id, "object modified");
-
-      String returnUrl = requestParser.getParameter("returnurl");
-
-      if (returnUrl!=null) {
-        ServletHelper.redirect(aResponse, returnUrl);
-      }
-      else {
-        edit(aRequest, aResponse, id);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic insert servlet method
-   */
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());
-
-      String id = processInstertedObject(object, aRequest, aResponse);
-
-      logAdminUsage(aRequest, id, "object inserted");
-
-      String returnUrl = requestParser.getParameter("returnurl");
-
-      if (returnUrl!=null) {
-        ServletHelper.redirect(aResponse, returnUrl);
-      }
-      else {
-        edit(aRequest, aResponse, id);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *
-   */
-  public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      return mainModule.add(anObject);
-    }
-    catch (ModuleExc t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   * Generic delete confirmation servlet method
-   */
-  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      String idParam = aRequest.getParameter("id");
-      String confirmParam = aRequest.getParameter("confirm");
-
-      if (confirmParam != null && !confirmParam.equals("")) {
-        mainModule.deleteById(idParam);
-        logAdminUsage(aRequest, idParam, "object deleted");
-        ServletHelper.redirect(aResponse, aRequest.getParameter("okurl"));
-      }
-      else
-        ServletHelper.redirect(aResponse, aRequest.getParameter("cancelurl"));
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   * Generic delete servlet method
-   */
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      String idParam = aRequest.getParameter("id");
-
-      if (idParam == null)
-        throw new ServletModuleExc("Invalid call to delete: no id supplied");
-
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      responseData.put("module", getOperationModuleName());
-      responseData.put("id", idParam);
-      responseData.put("cancelurl", aRequest.getParameter("cancelurl"));
-      responseData.put("okurl", aRequest.getParameter("okurl"));
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   */
-  public String defaultAction() {
-    return defaultAction;
-  }
-
-  /**
-   * Gets the fields from a httprequest and matches them with the metadata from
-   * the database object. Returns the keys that match, with their values.
-   *
-   * @return Map with the values
-   */
-  public Map getIntersectingValues(HttpServletRequest aRequest, Database theStorage)
-      throws ServletModuleExc, ServletModuleFailure {
-
-    HTTPRequestParser parser;
-    List theFieldList;
-
-    parser = new HTTPRequestParser(aRequest);
-
-    theFieldList = theStorage.getFieldNames();
-
-    Map withValues = new HashMap();
-    String aField, aValue;
-
-    for (int i = 0; i < theFieldList.size(); i++) {
-      aField = (String) theFieldList.get(i);
-
-      aValue = parser.getParameter(aField);
-      if (aValue != null)
-        withValues.put(aField, aValue);
-    }
-    return withValues;
-  }
-
-  private void propagateFields(HTTPRequestParser aRequest, URLBuilder aUrlBuilder, Map aResponseData) {
-    Iterator i = propagatedParameters.iterator();
-    while (i.hasNext()) {
-      String parameter = (String) i.next();
-      String value = aRequest.getParameter(parameter);
-      aUrlBuilder.setValue(parameter, value);
-      aResponseData.put(parameter, value);
-    }
-  }
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.config.MirPropertiesConfiguration;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+import java.lang.reflect.Method;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Locale;\r
+\r
+public abstract class ServletModule {\r
+  private LoggerWrapper logger = new LoggerWrapper("ServletModule." + getName());\r
+  private MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
+  private final Locale fallbackLocale = new Locale(\r
+      getConfiguration().getString("Mir.Admin.FallbackLanguage", "en"), "");\r
+\r
+  protected ServletModule() {\r
+  }\r
+\r
+  /**\r
+   * Return the name of this module\r
+   */\r
+  protected String getName() {\r
+    return getClass().getName().substring("mircoders.servlet.ServletModule".length());\r
+  }\r
+\r
+  /**\r
+   * Return the logger for this module\r
+   */\r
+  protected LoggerWrapper getLogger() {\r
+    return logger;\r
+  }\r
+\r
+  /**\r
+   * Return the global mir configuration\r
+   */\r
+  protected MirPropertiesConfiguration getConfiguration() {\r
+    return configuration;\r
+  }\r
+\r
+  /**\r
+   * signature of request handling methods\r
+   */\r
+  private static final Class[] HANDLER_METHOD_SIGNATURE = {\r
+      HttpServletRequest.class, HttpServletResponse.class\r
+  };\r
+\r
+  protected void defaultAction(HttpServletRequest aRequest,\r
+                               HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleFailure, ServletModuleUserExc {\r
+    throw new ServletModuleExc("default action not defined for module " + getName());\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  protected Locale getFallbackLocale(HttpServletRequest aRequest) {\r
+    return fallbackLocale;\r
+  }\r
+\r
+  public Locale[] getLocales(HttpServletRequest aRequest) {\r
+    return new Locale[] { getLocale(aRequest), fallbackLocale };\r
+  }\r
+\r
+  /**\r
+   * Return the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public static Locale getLocale(HttpServletRequest aRequest) {\r
+    Locale locale = null;\r
+    HttpSession session = aRequest.getSession(false);\r
+    if (session != null) {\r
+      // session can be null in case of logout\r
+      locale = (Locale) session.getAttribute("locale");\r
+    }\r
+    // if there is nothing in the session get it fron the accept-language\r
+    if (locale == null) {\r
+      locale = aRequest.getLocale();\r
+    }\r
+    return locale;\r
+  }\r
+\r
+  public void handleRequest(HttpServletRequest aRequest,\r
+                            HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {\r
+    // look for requested method's name in the "do" http request param,\r
+    // if not present, use default action\r
+    String handlerName = aRequest.getParameter("do");\r
+    getLogger().debug("ServletModuleDispatch: " + getClass().getName() + "." + handlerName);\r
+\r
+    if (handlerName ==null) {\r
+      handlerName = "defaultAction";\r
+    }\r
+\r
+    Method method;\r
+    try {\r
+      method = getClass().getMethod(handlerName, HANDLER_METHOD_SIGNATURE);\r
+    }\r
+    catch (NoSuchMethodException e) {\r
+      throw new ServletModuleFailure("No handler found", e);\r
+    }\r
+\r
+    // ok, we have the method's name, now call it\r
+    try {\r
+        method.invoke(this, new Object[] { aRequest,aResponse });\r
+    }\r
+    catch (InvocationTargetException e) {\r
+      getLogger().error("Error while dispatching: " + e.getTargetException().getMessage(),\r
+          e.getTargetException());\r
+      e.getTargetException().printStackTrace(getLogger().asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+\r
+      throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());\r
+    }\r
+    catch (IllegalAccessException e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+}\r
diff --git a/source/mir/servlet/ServletModuleDispatch.java b/source/mir/servlet/ServletModuleDispatch.java
deleted file mode 100755 (executable)
index 5fd290e..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mir.servlet;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-
-
-/**
- * Dispatcher, calls the method passed to ServletModule Class, through the "do"
- * Parameter (via POST or GET)
- *
- * @version $Id: ServletModuleDispatch.java,v 1.15.2.3 2005/07/27 11:46:14 grok Exp $
- *
- * @author rk
- */
-public final class ServletModuleDispatch {
-
-  private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Dispatch");
-  private static final Class[] SIGNATURE = { HttpServletRequest.class, HttpServletResponse.class };
-
-  /**
-   * private parameter-less constructor to prevent unwanted instantiation
-   */
-
-  private ServletModuleDispatch () {
-  }
-
-  /**
-   * Method to dispatch servletmodule requests.
-   *
-   * @param aServletModule
-   * @param aRequest
-   * @param aResponse
-   * @throws ServletModuleExc
-   * @throws ServletModuleFailure
-   */
-
-  public static void dispatch(ServletModule aServletModule, HttpServletRequest aRequest,
-       HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
-    // look for requested method's name in the "do" http request param, 
-    // if not present, use default action 
-    String doParam = aRequest.getParameter("do");
-    logger.debug("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam);
-
-    if (doParam == null) {
-      if (aServletModule.defaultAction() != null)
-        doParam = aServletModule.defaultAction();
-      else
-        throw new ServletModuleExc("no parameter do supplied!");
-    }
-
-    // ok, we have the method's name, now call it
-    try {
-      Method method = aServletModule.getClass().getMethod(doParam,SIGNATURE);
-      if (method != null) {
-        method.invoke(aServletModule,new Object[] {aRequest,aResponse} );
-        return;
-      }
-      else logger.debug("method lookup unsuccesful");
-    }
-    catch ( InvocationTargetException e) {
-      logger.error( "invocation target exception: " + e.toString());
-      e.getTargetException().printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
-      throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());
-    }
-    catch (Throwable t) {
-      logger.error( "ServletModuleDispatch: " + t.toString());
-      throw new ServletModuleFailure(t);
-    }
-  }
-}
index 0e2bbe0..f4f5910 100755 (executable)
@@ -32,6 +32,10 @@ package mir.servlet;
 import multex.Exc;
 
 public class ServletModuleExc extends Exc {
+  public ServletModuleExc(String aMessage, Exception aCause) {
+    super(aMessage, aCause);
+  }
+  
   public ServletModuleExc(String aMessage) {
     super(aMessage);
   }
index c532e51..c4a2e84 100755 (executable)
@@ -35,6 +35,9 @@ import java.util.HashMap;
 import java.util.Map;
 
 public class HTMLRoutines {
+  private HTMLRoutines() {
+  }
+  
   /**
    * Encodes a URL: escapes reserved URL characters like &, = into % escape
    *    constructions.
@@ -44,24 +47,19 @@ public class HTMLRoutines {
   }
 
   public static String encodeURL(String aString, String anEncoding) {
-    try {
-      return URLEncoder.encode(aString);
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.getMessage());
-    }
+    return URLEncoder.encode(aString);
   }
 
-  public static String encodeHTML(String aText) {
-    final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"' };
-    final String[] ESCAPE_CODES = { "&amp;", "&lt;", "&gt;", "&quot;" };
+  private static final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"' };
+  private static final String[] ESCAPE_CODES = { "&amp;", "&lt;", "&gt;", "&quot;" };
 
+  public static String encodeHTML(String aText) {
     return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES);
   }
 
   public static String prettyEncodeHTML(String aText) throws UtilExc {
-    return
-        StringRoutines.performRegularExpressionReplacement(encodeHTML(aText), "\\n", "<br>\n");
+    return StringRoutines.performRegularExpressionReplacement(
+        encodeHTML(aText), "\\n", "<br>\n");
   }
 
   public static String encodeXML(String aText) {
index ecb1ef3..e6db493 100755 (executable)
@@ -47,10 +47,12 @@ public class URLBuilder {
   }
 
   public void setValue(String aKey, String aValue) {
-    if (aValue!=null)
+    if (aValue!=null) {
       keyValues.put(aKey, aValue);
-    else
+    }
+    else {
       deleteKey(aKey);
+    }
   }
 
   public void setValue(String aKey, int aValue) {
@@ -63,9 +65,7 @@ public class URLBuilder {
 
   public String getQuery() {
     StringBuffer query = new StringBuffer();
-    Iterator i;
-
-    i = keyValues.entrySet().iterator();
+    Iterator i = keyValues.entrySet().iterator();
 
     while(i.hasNext()) {
       Map.Entry entry = (Map.Entry) i.next();
@@ -74,8 +74,9 @@ public class URLBuilder {
       query.append("=");
       query.append(HTMLRoutines.encodeURL((String) entry.getValue()));
 
-      if (i.hasNext())
+      if (i.hasNext()) {
         query.append("&");
+      }
     }
 
     return query.toString();
index 1c21e32..69473bb 100755 (executable)
@@ -62,8 +62,8 @@ public class MirGlobal {
   static private AccessControl accessControl;
   static private Map articleOperations;
   static private Map commentOperations;
-  static private Map loggedInUsers = new HashMap();
-  static private Map loggedInUserIds = new HashMap();
+  static private final Map loggedInUsers = new HashMap();
+  static private final Map loggedInUserIds = new HashMap();
   static private LoggerWrapper logger = new LoggerWrapper("Global");
   static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");
 //  static private ChangeEngine changeEngine = new ChangeEngine();
index 14450ba..68ce0d3 100755 (executable)
@@ -53,7 +53,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     localizer = aLocalizer;
   }
 
-  public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirProducerLocalizer producers() throws MirLocalizerFailure {
     if (producerLocalizer==null) {
       producerLocalizer = localizer.producers();
     }
@@ -61,7 +61,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return producerLocalizer;
   }
 
-  public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirGeneratorLocalizer generators() throws MirLocalizerFailure {
     if (generatorLocalizer==null) {
       generatorLocalizer = new MirCachingGeneratorLocalizer(localizer.generators());
     }
@@ -69,7 +69,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return generatorLocalizer;
   }
 
-  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure {
     if (openPostingsLocalizer==null) {
       openPostingsLocalizer = localizer.openPostings();
     }
@@ -77,7 +77,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return openPostingsLocalizer;
   }
 
-  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure {
     if (producerAssistantLocalizer==null) {
       producerAssistantLocalizer = localizer.producerAssistant();
     }
@@ -85,7 +85,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return producerAssistantLocalizer;
   }
 
-  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure {
     if (dataModelLocalizer==null) {
       dataModelLocalizer = new MirCachingDatamodelLocalizer(localizer.dataModel());
     }
@@ -93,7 +93,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return dataModelLocalizer;
   }
 
-  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure {
     if (adminInterfaceLocalizer==null) {
       adminInterfaceLocalizer = localizer.adminInterface();
     }
@@ -101,7 +101,7 @@ public class MirCachingLocalizerDecorator implements MirLocalizer {
     return adminInterfaceLocalizer;
   }
 
-  public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirMediaLocalizer media() throws MirLocalizerFailure {
     if (mediaLocalizer==null) {
       mediaLocalizer = localizer.media();
     }
index 228193a..ec2c3c6 100755 (executable)
@@ -50,11 +50,11 @@ package mircoders.localizer;
  */
 
 public interface MirLocalizer {
-  public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc;
-  public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc;
+  public MirProducerLocalizer producers() throws MirLocalizerFailure;
+  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure;
+  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure;
+  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure;
+  public MirGeneratorLocalizer generators() throws MirLocalizerFailure;
+  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure;
+  public MirMediaLocalizer media() throws MirLocalizerFailure;
 }
\ No newline at end of file
index fccebe3..875309d 100755 (executable)
@@ -53,11 +53,19 @@ public interface MirOpenPostingLocalizer {
   /**
    * This method will be called after an article is posted via the open posting interface.
    */
-  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;
+  public void afterArticlePosting(EntityContent anArticle) throws MirLocalizerExc, MirLocalizerFailure;
 
   /**
    *
    */
 
   public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;
+
+  /**
+   * This method should return <code>true</code> if the article should be visible
+   * to "open posting" users. This method is used to determine whether the request
+   * for a pdf, or an email for the article should be allowed. It is however
+   * <emph>not</emph> used by default by the production subsystem
+   */
+  public boolean allowArticlePublication(EntityContent anArticle);
 }
index da19f7a..d9fb68a 100755 (executable)
@@ -195,7 +195,7 @@ public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler
 
     MirGlobal.abuse().checkArticle(article, aRequest, null);
     try {
-      MirGlobal.localizer().openPostings().afterContentPosting(article);
+      MirGlobal.localizer().openPostings().afterArticlePosting(article);
     }
     catch (Throwable t) {
       throw new SessionFailure(t);
index 5313a1d..0c5714a 100755 (executable)
@@ -42,6 +42,7 @@ import mir.util.JDBCStringRoutines;
 import mir.util.ParameterExpander;
 import mir.util.StructuredContentParser;
 import mircoders.entity.EntityUploadedMedia;
+import mircoders.entity.EntityContent;
 import mircoders.global.MirGlobal;
 import mircoders.localizer.MirAdminInterfaceLocalizer;
 import mircoders.localizer.MirDataModelLocalizer;
@@ -117,6 +118,21 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {
       anEntityAdapterDefinition.addCalculatedField("to_translations", new ContentToTranslationsField());
       anEntityAdapterDefinition.addCalculatedField("to_translation", new ContentToTranslationField());
 
+      anEntityAdapterDefinition.addCalculatedField("allow_publication",
+          new EntityAdapterDefinition.CalculatedField() {
+
+            public Object getValue(EntityAdapter anEntityAdapter) {
+              try {
+                return Boolean.valueOf(MirGlobal.localizer().openPostings().
+                    allowArticlePublication((EntityContent) anEntityAdapter.getEntity()));
+              }
+              catch (Throwable t) {
+                return  Boolean.FALSE;
+              }
+            }
+          }
+      );
+
       anEntityAdapterDefinition.addCalculatedField("previews", new EntityAdapterDefinition.CalculatedField() {
         public Object getValue(EntityAdapter anEntityAdapter) {
           try {
index bcfc089..0c96b79 100755 (executable)
@@ -117,21 +117,32 @@ public class MirBasicEmailArticleHandler implements SessionHandler {
     if (articleID == null){
       throw new SessionExc("makeInitialResponse: article id not set!");
     }
-    else {
-      aSession.setAttribute("email.aid",articleID);
-      aResponse.setResponseValue("errors", null);
-
-      String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
-      aResponse.setResponseValue("mail_language",mail_language);
-      aResponse.setResponseValue("mail_to","");
-      aResponse.setResponseValue("mail_from","");
-      aResponse.setResponseValue("mail_from_name","");
-      aResponse.setResponseValue("mail_comment","");
 
-      aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
+    EntityContent article;
+    try {
+      article = (EntityContent) (new ModuleContent()).getById(articleID);
+    }
+    catch (Throwable t) {
+      throw new SessionExc("Unknown article: " + articleID);
+    }
 
+    if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
 
     }
+
+
+
+    aSession.setAttribute("email.aid",articleID);
+    aResponse.setResponseValue("errors", null);
+
+    String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
+    aResponse.setResponseValue("mail_language",mail_language);
+    aResponse.setResponseValue("mail_to","");
+    aResponse.setResponseValue("mail_from","");
+    aResponse.setResponseValue("mail_from_name","");
+    aResponse.setResponseValue("mail_comment","");
+
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
   }
 
   protected boolean shouldSendMail(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
index 156cc1c..adf397c 100755 (executable)
@@ -33,31 +33,31 @@ import mircoders.localizer.*;
 
 public class MirBasicLocalizer implements MirLocalizer {
 
-  public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirProducerLocalizer producers() throws MirLocalizerFailure {
     return new MirBasicProducerLocalizer();
   }
 
-  public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirGeneratorLocalizer generators() throws MirLocalizerFailure {
     return new MirBasicGeneratorLocalizer();
   }
 
-  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure {
     return new MirBasicOpenPostingLocalizer();
   }
 
-  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure {
     return new MirBasicProducerAssistantLocalizer();
   }
 
-  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure {
     return new MirBasicDataModelLocalizer();
   }
 
-  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure {
     return new MirBasicAdminInterfaceLocalizer();
   }
 
-  public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
+  public MirMediaLocalizer media() throws MirLocalizerFailure{
     return new MirBasicMediaLocalizer();
   }
 }
index b5bdd7f..0dce0b6 100755 (executable)
  */
 package mircoders.localizer.basic;
 
-import java.util.HashMap;
-import java.util.Map;
-
 import mir.config.MirPropertiesConfiguration;
 import mir.media.MediaHandler;
-import mircoders.localizer.MirLocalizerExc;
 import mircoders.localizer.MirLocalizerFailure;
 import mircoders.localizer.MirMediaLocalizer;
-import mircoders.media.MediaHandlerAudio;
-import mircoders.media.MediaHandlerGeneric;
-import mircoders.media.MediaHandlerImagesExtern;
-import mircoders.media.MediaHandlerImagesJpeg;
-import mircoders.media.MediaHandlerImagesPng;
-import mircoders.media.MediaHandlerMp3;
-import mircoders.media.MediaHandlerOgg;
-import mircoders.media.MediaHandlerRealAudio;
-import mircoders.media.MediaHandlerRealVideo;
-import mircoders.media.MediaHandlerVideo;
-import mircoders.media.URLMediaHandler;
+import mircoders.media.*;
 
-/**
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import java.util.HashMap;
+import java.util.Map;
 
 public class MirBasicMediaLocalizer implements MirMediaLocalizer {
-  private Map mediaHandlers;
+  private final Map mediaHandlers = new HashMap();
 
-  /**
-   *
-   * @throws MirLocalizerExc
-   * @throws MirLocalizerFailure
-   */
-  public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+  public MirBasicMediaLocalizer() throws MirLocalizerFailure {
     MirPropertiesConfiguration configuration;
 
     try {
@@ -76,9 +51,6 @@ public class MirBasicMediaLocalizer implements MirMediaLocalizer {
       throw new MirLocalizerFailure("Can't get configuration", t);
     }
 
-    mediaHandlers = new HashMap();
-
-
     registerMediaHandler("Audio", new MediaHandlerAudio());
     registerMediaHandler("Generic", new MediaHandlerGeneric());
     registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern());
index 0009383..b6833ed 100755 (executable)
@@ -61,7 +61,7 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
   protected LoggerWrapper logger;
   protected MirPropertiesConfiguration configuration;
 
-  public MirBasicOpenPostingLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+  public MirBasicOpenPostingLocalizer() throws MirLocalizerFailure {
     logger = new LoggerWrapper("Localizer.Basic.OpenPosting");
 
     try {
@@ -133,10 +133,18 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
     }
   }
 
-  public void afterContentPosting(EntityContent aContent) {
+  public void afterArticlePosting() {
     afterContentPosting();
   }
 
+  public void afterArticlePosting(EntityContent anArticle) {
+    afterContentPosting(anArticle);
+  }
+
+  public void afterContentPosting(EntityContent anArticle) {
+    afterArticlePosting();
+  }
+
   public void afterCommentPosting(EntityComment aComment) {
     afterCommentPosting();
   }
@@ -175,6 +183,10 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
     return filterTypes;
   }
 
+  public boolean allowArticlePublication(EntityContent anArticle){
+    return (anArticle!=null) && "t".equals(anArticle.getFieldValue("is_published"));
+  }
+
   public void removeSimpleAntiAbuseFilterType(String aName) {
     filterTypes.remove(filterTypesMap.get(aName));
     filterTypesMap.remove(aName);
index d26fab5..40c95cd 100755 (executable)
@@ -70,7 +70,7 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL
   private RE regularExpressionLT;
   private RE regularExpressionGT;
 
-  public MirBasicProducerAssistantLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+  public MirBasicProducerAssistantLocalizer() throws MirLocalizerFailure {
       try{
           regularExpressionLT = new RE("<");
           regularExpressionGT = new RE(">");
index ac96478..58e1a0b 100755 (executable)
@@ -108,8 +108,7 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric
       }
     }
     catch(Throwable t) {
-      logger.error("MediaHandlerImagesExtern.execute: " + t.toString());
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      logger.error("MediaHandlerImagesExtern.execute: " + t.getMessage(), t);
       throw new MediaFailure(t.getMessage(), t);
     }
   }
index 762cce0..4222dc7 100755 (executable)
  */
 package mircoders.media;
 
-import java.util.HashMap;
-import java.util.Map;
-
 import mir.entity.Entity;
 import mir.media.MediaExc;
 import mir.media.MediaFailure;
 import mir.media.MediaHandler;
 import mir.storage.Database;
 import mircoders.global.MirGlobal;
-import mircoders.localizer.MirLocalizerExc;
 import mircoders.storage.DatabaseAudio;
 import mircoders.storage.DatabaseImages;
 import mircoders.storage.DatabaseOther;
@@ -53,23 +49,10 @@ import mircoders.storage.DatabaseVideo;
  */
 
 public final class MediaHelper {
-  private static Map nameToMediaHandler = new HashMap();
-  
-  public static void addHandler(String aName, MediaHandler aHandler) {
-    synchronized (nameToMediaHandler) {
-      nameToMediaHandler.put(aName, aHandler);
-    }
-  }
-
   public static MediaHandler getHandler(Entity aMediaType) throws MediaExc, MediaFailure {
     String handlerName = aMediaType.getFieldValue("classname");
 
-    try {
-      return MirGlobal.localizer().media().getHandler(handlerName);
-    }
-    catch (MirLocalizerExc e) {
-      throw new MediaFailure(e);
-    }
+    return MirGlobal.localizer().media().getHandler(handlerName);
   }
 
   public static Database getStorage(Entity mediaType, String aTable) throws MediaExc, MediaFailure {
index ebfe984..1a15868 100755 (executable)
@@ -65,9 +65,9 @@ import com.lowagie.text.pdf.ColumnText;
 import com.lowagie.text.pdf.PdfContentByte;
 import com.lowagie.text.pdf.PdfTemplate;
 import com.lowagie.text.pdf.PdfWriter;
+import multex.Failure;
 
-public class PDFGenerator{
-
+public class PDFGenerator {
   public Document document;
   public PdfWriter writer;
   public PdfContentByte cb;
@@ -83,8 +83,8 @@ public class PDFGenerator{
   public float rightEdge;
   public float leftEdge;
 
-  public int    maxImageHeight;
-  public int    maxImageWidth;
+  public int maxImageHeight;
+  public int maxImageWidth;
   protected LoggerWrapper logger;
 
   public int indexFontSize;
@@ -118,264 +118,262 @@ public class PDFGenerator{
   protected MirPropertiesConfiguration configuration;
 
 
-  public PDFGenerator(ByteArrayOutputStream out){
+  public PDFGenerator(ByteArrayOutputStream out) {
     logger = new LoggerWrapper("PDFGenerator");
     configuration = MirPropertiesConfiguration.instance();
-    localImageDir=configuration.getString("Producer.Image.Path");
+    localImageDir = configuration.getString("Producer.Image.Path");
 
     try {
-      indexFontSize   = Integer.parseInt(configuration.getString("PDF.Index.FontSize"));
+      indexFontSize = Integer.parseInt(configuration.getString("PDF.Index.FontSize"));
       indexLineHeight = Integer.parseInt(configuration.getString("PDF.Index.LineHeight"));
       indexFontFamily = getFontByName(configuration.getString("PDF.Index.FontFamily"));
 
       footerText = configuration.getString("PDF.Footer.String");
-      footerFontSize   = Integer.parseInt(configuration.getString("PDF.Footer.FontSize"));
+      footerFontSize = Integer.parseInt(configuration.getString("PDF.Footer.FontSize"));
       footerFontFamily = getFontByName(configuration.getString("PDF.Footer.FontFamily"));
       footerHeight = Integer.parseInt(configuration.getString("PDF.Footer.Height"));
 
-      metaFontSize   = Integer.parseInt(configuration.getString("PDF.Meta.FontSize"));
+      metaFontSize = Integer.parseInt(configuration.getString("PDF.Meta.FontSize"));
       metaFontFamily = getFontByName(configuration.getString("PDF.Meta.FontFamily"));
       metaHeight = Integer.parseInt(configuration.getString("PDF.Meta.Height"));
 
-      descriptionFontSize   = Integer.parseInt(configuration.getString("PDF.Description.FontSize"));
+      descriptionFontSize = Integer.parseInt(configuration.getString("PDF.Description.FontSize"));
       descriptionLineHeight = Integer.parseInt(configuration.getString("PDF.Description.LineHeight"));
       descriptionFontFamily = getFontByName(configuration.getString("PDF.Description.FontFamily"));
 
-      contentFontSize   = Integer.parseInt(configuration.getString("PDF.Content.FontSize"));
+      contentFontSize = Integer.parseInt(configuration.getString("PDF.Content.FontSize"));
       contentLineHeight = Integer.parseInt(configuration.getString("PDF.Content.LineHeight"));
       contentFontFamily = getFontByName(configuration.getString("PDF.Content.FontFamily"));
 
-      sourceFontSize   = Integer.parseInt(configuration.getString("PDF.Source.FontSize"));
+      sourceFontSize = Integer.parseInt(configuration.getString("PDF.Source.FontSize"));
       sourceLineHeight = Integer.parseInt(configuration.getString("PDF.Source.LineHeight"));
       sourceFontFamily = getFontByName(configuration.getString("PDF.Source.FontFamily"));
 
-      bigImageCaptionFontSize   = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize"));
+      bigImageCaptionFontSize = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize"));
       bigImageCaptionFontFamily = getFontByName(configuration.getString("PDF.BigImageCaption.FontFamily"));
 
     }
-    catch (NumberFormatException e){
-      e.printStackTrace();
+    catch (NumberFormatException e) {
+      throw new Failure(e.getMessage(), e);
     }
 
     // step 1: make a document
 
     String pageSize = configuration.getString("PDF.Pagesize");
 
-    if (pageSize.equals("LETTER")){
+    if (pageSize.equals("LETTER")) {
       document = new Document(PageSize.LETTER);
       pageWidth = 612;
       pageHeight = 792;
-    }
-    else {
-       document = new Document(PageSize.A4);
-       pageWidth=595;
-       pageHeight=842;
+    } else {
+      document = new Document(PageSize.A4);
+      pageWidth = 595;
+      pageHeight = 842;
     }
 
-    maxImageHeight    = 250;
-    maxImageWidth     = 250;
+    maxImageHeight = 250;
+    maxImageWidth = 250;
 
 
     verticalMargin = 20;
     horizontalMargin = 20;
 
 
+    topEdge = pageHeight - verticalMargin;
+    bottomEdge = verticalMargin;
+    rightEdge = pageWidth - horizontalMargin;
+    leftEdge = horizontalMargin;
 
-    topEdge=pageHeight-verticalMargin;
-    bottomEdge=verticalMargin;
-    rightEdge=pageWidth-horizontalMargin;
-    leftEdge=horizontalMargin;
-
-    currentYPosition=topEdge;
+    currentYPosition = topEdge;
     currentPage = 1;
 
     String headerText = configuration.getString("PDF.Title.String");
 
-    try{
+    try {
       writer = PdfWriter.getInstance(document, out);
       cb = writer.getDirectContent();
 
       document.open();
       addHeader(headerText);
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
   }
 
-  public void stop(){
+  public void stop() {
     addFooter();
     document.close();
   }
 
-  public void addHeader(String headerText){
-    int titleFontSize=Integer.parseInt(configuration.getString("PDF.Title.FontSize"));
-    int titleLineHeight=Integer.parseInt(configuration.getString("PDF.Title.LineHeight"));
-    String titleFontFamily=configuration.getString("PDF.Title.FontFamily");
-    String headerImage=configuration.getString("PDF.Header.Image");
+  public void addHeader(String headerText) {
+    int titleFontSize = Integer.parseInt(configuration.getString("PDF.Title.FontSize"));
+    int titleLineHeight = Integer.parseInt(configuration.getString("PDF.Title.LineHeight"));
+    String titleFontFamily = configuration.getString("PDF.Title.FontFamily");
+    String headerImage = configuration.getString("PDF.Header.Image");
     int headerImageHeight = Integer.parseInt(configuration.getString("PDF.Header.ImageHeight"));
 
     try {
-      if ((! headerImage.equals("")) && headerImageHeight != 0){
-  PdfTemplate template = cb.createTemplate(rightEdge-horizontalMargin,headerImageHeight);
+      if ((! headerImage.equals("")) && headerImageHeight != 0) {
+        PdfTemplate template = cb.createTemplate(rightEdge - horizontalMargin, headerImageHeight);
 
-  float toYPosition=currentYPosition - headerImageHeight;
-  Image theImage = Image.getInstance(headerImage);
-  theImage.setAbsolutePosition(0,0);
-  //   theImage.scaleAbsolute(img_width,img_height);
-  template.addImage(theImage);
+        float toYPosition = currentYPosition - headerImageHeight;
+        Image theImage = Image.getInstance(headerImage);
+        theImage.setAbsolutePosition(0, 0);
+        //     theImage.scaleAbsolute(img_width,img_height);
+        template.addImage(theImage);
 
 
-  cb.addTemplate(template,leftEdge,toYPosition);
-  currentYPosition = toYPosition;
+        cb.addTemplate(template, leftEdge, toYPosition);
+        currentYPosition = toYPosition;
       }
-      if (! headerText.equals("")){
-  ColumnText ct = new ColumnText(cb);
-  //add a basic header
-  ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize,Font.BOLD)));
-  float[] rightCol = {rightEdge,currentYPosition,rightEdge,currentYPosition-titleLineHeight};
-  float[] leftCol = {leftEdge,currentYPosition,leftEdge,currentYPosition-titleLineHeight};
-  ct.setColumns(leftCol,rightCol);
-  ct.setYLine(currentYPosition);
-  ct.setAlignment(Element.ALIGN_CENTER);
-  ct.go();
-
-  currentYPosition = currentYPosition - titleLineHeight;
+      if (! headerText.equals("")) {
+        ColumnText ct = new ColumnText(cb);
+        //add a basic header
+        ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize, Font.BOLD)));
+        float[] rightCol = {rightEdge, currentYPosition, rightEdge, currentYPosition - titleLineHeight};
+        float[] leftCol = {leftEdge, currentYPosition, leftEdge, currentYPosition - titleLineHeight};
+        ct.setColumns(leftCol, rightCol);
+        ct.setYLine(currentYPosition);
+        ct.setAlignment(Element.ALIGN_CENTER);
+        ct.go();
+
+        currentYPosition = currentYPosition - titleLineHeight;
       }
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
-    catch(MalformedURLException de) {
+    catch (MalformedURLException de) {
       logger.error(de.getMessage());
     }
-    catch(IOException de) {
+    catch (IOException de) {
       logger.error(de.getMessage());
     }
   }
-  public void addIndexItem(EntityContent entityContent){
+
+  public void addIndexItem(EntityContent entityContent) {
     try {
 
       ColumnText ict = new ColumnText(cb);
       String theTitle = entityContent.getFieldValue("title");
       String theCreator = entityContent.getFieldValue("creator");
-      Phrase titleP=new Phrase(" - " +  theTitle,new Font(indexFontFamily,indexFontSize,Font.BOLD));
-      Phrase creatorP=new Phrase( " :: " + theCreator,new Font(indexFontFamily,indexFontSize));
+      Phrase titleP = new Phrase(" - " + theTitle, new Font(indexFontFamily, indexFontSize, Font.BOLD));
+      Phrase creatorP = new Phrase(" :: " + theCreator, new Font(indexFontFamily, indexFontSize));
       float toYPosition = currentYPosition - indexLineHeight;
-      float[] leftIndexCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
-      float[] rightIndexCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
+      float[] leftIndexCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+      float[] rightIndexCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
       ict.addText(titleP);
       ict.addText(creatorP);
-      ict.setColumns(leftIndexCols,rightIndexCols);
+      ict.setColumns(leftIndexCols, rightIndexCols);
       ict.setYLine(currentYPosition);
       ict.setAlignment(Element.ALIGN_LEFT);
       ict.go();
       currentYPosition = toYPosition;
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
 
 
-
   }
 
-  private int addTextLine(ColumnText ct,int lineHeight,int alignment,float left, float right){
+  private int addTextLine(ColumnText ct, int lineHeight, int alignment, float left, float right) {
     logger.debug("adding a line of text");
-    if (! enoughY(lineHeight)){
+    if (! enoughY(lineHeight)) {
       newPage();
     }
     float toYPosition = currentYPosition - lineHeight;
-    float[] leftContentCols = {left,currentYPosition,left,toYPosition};
-    float[] rightContentCols = {right,currentYPosition,right,toYPosition};
-    ct.setColumns(leftContentCols,rightContentCols);
+    float[] leftContentCols = {left, currentYPosition, left, toYPosition};
+    float[] rightContentCols = {right, currentYPosition, right, toYPosition};
+    ct.setColumns(leftContentCols, rightContentCols);
     ct.setYLine(currentYPosition);
     ct.setAlignment(alignment);
-    try{
-      int status=ct.go();
+    try {
+      int status = ct.go();
       currentYPosition = toYPosition;
       return status;
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
     return 0;
   }
 
-  public void addLine(){
+  public void addLine() {
     cb.setLineWidth(1f);
-    cb.moveTo(rightEdge, currentYPosition-5);
-    cb.lineTo(leftEdge, currentYPosition-5);
+    cb.moveTo(rightEdge, currentYPosition - 5);
+    cb.lineTo(leftEdge, currentYPosition - 5);
     cb.stroke();
     currentYPosition = currentYPosition - 10;
 
   }
 
-  public void addFooter(){
-    try{
-    ColumnText fct = new ColumnText(cb);
-    cb.setLineWidth(1f);
-    cb.moveTo(rightEdge, bottomEdge+footerHeight-5);
-    cb.lineTo(leftEdge, bottomEdge+footerHeight-5);
-    cb.stroke();
-    float[] leftFooterCols = {leftEdge,bottomEdge+footerHeight-1,leftEdge,bottomEdge};
-    float[] rightFooterCols = {rightEdge,bottomEdge+footerHeight-1,rightEdge,bottomEdge};
+  public void addFooter() {
+    try {
+      ColumnText fct = new ColumnText(cb);
+      cb.setLineWidth(1f);
+      cb.moveTo(rightEdge, bottomEdge + footerHeight - 5);
+      cb.lineTo(leftEdge, bottomEdge + footerHeight - 5);
+      cb.stroke();
+      float[] leftFooterCols = {leftEdge, bottomEdge + footerHeight - 1, leftEdge, bottomEdge};
+      float[] rightFooterCols = {rightEdge, bottomEdge + footerHeight - 1, rightEdge, bottomEdge};
 
-    Paragraph footerP=new Paragraph(footerText,new Font(footerFontFamily,footerFontSize));
-    fct.addText(footerP);
+      Paragraph footerP = new Paragraph(footerText, new Font(footerFontFamily, footerFontSize));
+      fct.addText(footerP);
 
-    fct.setColumns(leftFooterCols,rightFooterCols);
-    fct.setYLine(bottomEdge+footerHeight-1);
-    fct.setAlignment(Element.ALIGN_JUSTIFIED);
-    fct.go();
+      fct.setColumns(leftFooterCols, rightFooterCols);
+      fct.setYLine(bottomEdge + footerHeight - 1);
+      fct.setAlignment(Element.ALIGN_JUSTIFIED);
+      fct.go();
 
-    Paragraph numberP=new Paragraph((new Integer(currentPage)).toString(),new Font(footerFontFamily,footerFontSize,Font.BOLD));
-    fct.addText(numberP);
-    fct.setAlignment(Element.ALIGN_RIGHT);
-    fct.go();
+      Paragraph numberP = new Paragraph((new Integer(currentPage)).toString(), new Font(footerFontFamily, footerFontSize, Font.BOLD));
+      fct.addText(numberP);
+      fct.setAlignment(Element.ALIGN_RIGHT);
+      fct.go();
 
     }
-    catch (DocumentException de){
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
 
 
   }
 
-  public void newPage(){
-    try{
+  public void newPage() {
+    try {
       //add a footer
       addFooter();
       document.newPage();
       currentPage++;
-      currentYPosition=topEdge;
+      currentYPosition = topEdge;
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
   }
 
-  public void addArticleSeparator(){
+  public void addArticleSeparator() {
     // make a line
-    if (! enoughY(10)){
+    if (! enoughY(10)) {
       newPage();
     }
     cb.setLineWidth(1f);
-    cb.moveTo(rightEdge, currentYPosition-5);
-    cb.lineTo(leftEdge, currentYPosition-5);
+    cb.moveTo(rightEdge, currentYPosition - 5);
+    cb.lineTo(leftEdge, currentYPosition - 5);
     cb.stroke();
     currentYPosition = currentYPosition - 10;
   }
 
-  public void addArticleMetaInfo(ColumnText ct,String theTitle,String theCreator,String theDate){
-      //see if we have room for the author and title
+  public void addArticleMetaInfo(ColumnText ct, String theTitle, String theCreator, String theDate) {
+    //see if we have room for the author and title
 
-    if (! enoughY(metaHeight)){
-  newPage();
-      }
+    if (! enoughY(metaHeight)) {
+      newPage();
+    }
 
-    Paragraph titleP=new Paragraph(theTitle+"\n",new Font(metaFontFamily,metaFontSize,Font.BOLD));
-    Paragraph whowhenP=new Paragraph(theCreator + "  " + theDate ,new Font(metaFontFamily,metaFontSize));
+    Paragraph titleP = new Paragraph(theTitle + "\n", new Font(metaFontFamily, metaFontSize, Font.BOLD));
+    Paragraph whowhenP = new Paragraph(theCreator + "  " + theDate, new Font(metaFontFamily, metaFontSize));
     ct.addText(titleP);
     ct.addText(whowhenP);
 
@@ -383,243 +381,240 @@ public class PDFGenerator{
     ct.setAlignment(Element.ALIGN_LEFT);
 
     float toYPosition = currentYPosition - metaHeight;
-    float[] leftHeadCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
-    float[] rightHeadCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
+    float[] leftHeadCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+    float[] rightHeadCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
 
-    ct.setColumns(leftHeadCols,rightHeadCols);
+    ct.setColumns(leftHeadCols, rightHeadCols);
     try {
       ct.go();
       currentYPosition = toYPosition;
     }
-    catch(DocumentException de) {
+    catch (DocumentException de) {
       logger.error(de.getMessage());
     }
 
   }
 
-  public void addArticleDescription(ColumnText ct,String theDescription){
+  public void addArticleDescription(ColumnText ct, String theDescription) {
     // Now we add the description, one line at a time, the ct should be empty at this point
 
 
-    Paragraph descP=new Paragraph(theDescription,new Font(descriptionFontFamily,descriptionFontSize,Font.BOLD));
+    Paragraph descP = new Paragraph(theDescription, new Font(descriptionFontFamily, descriptionFontSize, Font.BOLD));
     ct.addText(descP);
 
     // every article has a description, so we can assume that:
     int status = ColumnText.NO_MORE_COLUMN;
 
-    int brake=1000;
-    while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake >0){
+    int brake = 1000;
+    while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0) {
       //there is still text left in the description.
-      status = addTextLine(ct,descriptionLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+      status = addTextLine(ct, descriptionLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
       brake--;
     }
     if (brake == 0)
       logger.error("runaway description...try increasing the line height or decreasing the font size");
   }
 
-  public void addArticleContent(ColumnText ct,String theContent,Iterator images){
+  public void addArticleContent(ColumnText ct, String theContent, Iterator images) {
     //let's go ahead and add in all the body text
-    Paragraph contentP=new Paragraph(theContent,new Font(contentFontFamily,contentFontSize));
+    Paragraph contentP = new Paragraph(theContent, new Font(contentFontFamily, contentFontSize));
     ct.addText(contentP);
 
-    int contentLinesBeforeImages=3;
+    int contentLinesBeforeImages = 3;
     //and assume we have at least one line of text in the content
     int status = ColumnText.NO_MORE_COLUMN;
 
     // let's add a little bit of text, like a couple of lines
     int x = 0;
-    while (((status & ColumnText.NO_MORE_TEXT) == 0) && x<contentLinesBeforeImages){
-      status=addTextLine(ct,contentLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+    while (((status & ColumnText.NO_MORE_TEXT) == 0) && x < contentLinesBeforeImages) {
+      status = addTextLine(ct, contentLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
       x++;
     }
 
     boolean addImageOnLeft = true; //we will alternate within articles
-    while (images.hasNext()){
-
-      EntityImages currentImage=(EntityImages) images.next();
-      float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue();
-      float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue();
-      if (img_height>maxImageHeight){
-  img_width=(new Float((new Float(img_width*(maxImageHeight/img_height))).intValue())).floatValue();
-  img_height=maxImageHeight;
+    while (images.hasNext()) {
+
+      EntityImages currentImage = (EntityImages) images.next();
+      float img_width = (new Float(currentImage.getFieldValue("img_width"))).floatValue();
+      float img_height = (new Float(currentImage.getFieldValue("img_height"))).floatValue();
+      if (img_height > maxImageHeight) {
+        img_width = (new Float((new Float(img_width * (maxImageHeight / img_height))).intValue())).floatValue();
+        img_height = maxImageHeight;
       }
-      if (img_width>maxImageWidth){
-  img_height=(new Float((new Float(img_height*(maxImageWidth/img_width))).intValue())).floatValue();
-  img_width=maxImageWidth;
+      if (img_width > maxImageWidth) {
+        img_height = (new Float((new Float(img_height * (maxImageWidth / img_width))).intValue())).floatValue();
+        img_width = maxImageWidth;
       }
 
-      String img_title=currentImage.getFieldValue("title");
-      String img_path=currentImage.getFieldValue("publish_path");
-
-      if ((status & ColumnText.NO_MORE_TEXT) == 0){
-  // there is still text, so add an image which will have text wrapped around it, then add the text which
-  // will be on the left or the right of the image
-
-  float templateMinimumHeight = img_height+20;
-  float templateWidth = img_width+10;
-  float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
-
-  PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
-
-
-  //here we need a page check
-  if (! enoughY((new Float(templateHeight)).intValue())){
-    //ok, well just fill text to the bottom then
-    float toYPosition = bottomEdge+footerHeight;
-    float[] leftBottomCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
-    float[] rightBottomCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
-    ct.setColumns(leftBottomCols,rightBottomCols);
-    ct.setYLine(currentYPosition);
-    ct.setAlignment(Element.ALIGN_JUSTIFIED);
-    try{
-      status=ct.go();
-    }
-    catch(DocumentException de) {
-      logger.error(de.getMessage());
-    }
-    newPage();
-  }
-
-  float toYPosition=currentYPosition - templateHeight;
-
-  try {
-    Image theImage = Image.getInstance(localImageDir+img_path);
-    theImage.scaleAbsolute(img_width,img_height);
-    theImage.setAbsolutePosition(5,13);
-
-    template.addImage(theImage);
-    template.beginText();
-    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
-    template.setFontAndSize(bf, 8);
-    template.setTextMatrix(5, 3);
-    template.showText(img_title);
-    template.endText();
-  }
-  catch(BadElementException de) {
-    logger.error(de.getMessage());
-  }
-  catch(DocumentException de) {
-    logger.error(de.getMessage());
-  }
-  catch (MalformedURLException de){
-   logger.error(de.getMessage());
-  }
-  catch (IOException de){
-    logger.error(de.getMessage());
-  }
-
-
-  float leftImageTextEdge=leftEdge;
-  float rightImageTextEdge=rightEdge;
-
-
-  if (addImageOnLeft){
-    cb.addTemplate(template,leftEdge,toYPosition);
-    leftImageTextEdge=leftEdge+templateWidth+5;
-    addImageOnLeft = false;
-  }
-  else {
-    cb.addTemplate(template,rightEdge-templateWidth,toYPosition);
-    rightImageTextEdge = rightEdge-templateWidth-5;
-    addImageOnLeft = true;
-  }
-
-  logger.debug("adding template at " + leftEdge + "," + toYPosition);
-
-  //and fill some text while we are at it
-
-  float[] leftBottomCols = {leftImageTextEdge,currentYPosition,leftImageTextEdge,toYPosition};
-  float[] rightBottomCols = {rightImageTextEdge,currentYPosition,rightImageTextEdge,toYPosition};
-  ct.setColumns(leftBottomCols,rightBottomCols);
-  ct.setYLine(currentYPosition);
-  ct.setAlignment(Element.ALIGN_JUSTIFIED);
-  try{
-  status=ct.go();
-  currentYPosition=toYPosition;
-  }
-  catch(DocumentException de) {
-    logger.error(de.getMessage());
-  }
-
-
-      }
-      else {
-  //add an image on the left with a big caption to the right
-  currentYPosition = currentYPosition - 10;
-  float templateMinimumHeight = img_height;
-  float templateWidth = img_width;
-  float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
-  PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
-  if (! enoughY((new Float(templateHeight)).intValue())){
-    newPage();
-  }
-  float toYPosition=currentYPosition - templateHeight;
-  try{
-    Image theImage = Image.getInstance(localImageDir+img_path);
-    theImage.setAbsolutePosition(0,13);
-    theImage.scaleAbsolute(img_width,img_height);
-    template.addImage(theImage);
-  }
-  catch(BadElementException de) {
-    logger.error(de.getMessage());
-  }
-  catch(DocumentException de) {
-    logger.error(de.getMessage());
-  }
-  catch(MalformedURLException de) {
-    logger.error(de.getMessage());
-  }
-  catch(IOException de) {
-    logger.error(de.getMessage());
-  }
-
-  cb.addTemplate(template,leftEdge,toYPosition);
-
-  // add a big caption
-  ColumnText cct = new ColumnText(cb);
-  float[] leftCaptionCols = {leftEdge+templateWidth+5,currentYPosition-5,leftEdge+templateWidth+5,toYPosition};
-  float[] rightCaptionCols = {rightEdge,currentYPosition-5,rightEdge,toYPosition};
-
-  Paragraph captionP=new Paragraph(img_title,new Font(bigImageCaptionFontFamily,bigImageCaptionFontSize,Font.BOLD));
-  cct.addText(captionP);
-  cct.setColumns(leftCaptionCols,rightCaptionCols);
-  cct.setYLine(currentYPosition-5);
-  cct.setAlignment(Element.ALIGN_LEFT);
-  try{
-    cct.go();
-    currentYPosition=toYPosition;
-  }
-  catch(DocumentException de) {
-    logger.error(de.getMessage());
-  }
+      String img_title = currentImage.getFieldValue("title");
+      String img_path = currentImage.getFieldValue("publish_path");
+
+      if ((status & ColumnText.NO_MORE_TEXT) == 0) {
+        // there is still text, so add an image which will have text wrapped around it, then add the text which
+        // will be on the left or the right of the image
+
+        float templateMinimumHeight = img_height + 20;
+        float templateWidth = img_width + 10;
+        float templateHeight = templateMinimumHeight + contentLineHeight - (templateMinimumHeight % contentLineHeight);
+
+        PdfTemplate template = cb.createTemplate(templateWidth, templateHeight);
+
+        //here we need a page check
+        if (! enoughY((new Float(templateHeight)).intValue())) {
+          //ok, well just fill text to the bottom then
+          float toYPosition = bottomEdge + footerHeight;
+          float[] leftBottomCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+          float[] rightBottomCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
+          ct.setColumns(leftBottomCols, rightBottomCols);
+          ct.setYLine(currentYPosition);
+          ct.setAlignment(Element.ALIGN_JUSTIFIED);
+          try {
+            status = ct.go();
+          }
+          catch (DocumentException de) {
+            logger.error(de.getMessage());
+          }
+          newPage();
+        }
+
+        float toYPosition = currentYPosition - templateHeight;
+
+        try {
+          Image theImage = Image.getInstance(localImageDir + img_path);
+          theImage.scaleAbsolute(img_width, img_height);
+          theImage.setAbsolutePosition(5, 13);
+
+          template.addImage(theImage);
+          template.beginText();
+          BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
+          template.setFontAndSize(bf, 8);
+          template.setTextMatrix(5, 3);
+          template.showText(img_title);
+          template.endText();
+        }
+        catch (BadElementException de) {
+          logger.error(de.getMessage());
+        }
+        catch (DocumentException de) {
+          logger.error(de.getMessage());
+        }
+        catch (MalformedURLException de) {
+          logger.error(de.getMessage());
+        }
+        catch (IOException de) {
+          logger.error(de.getMessage());
+        }
+
+
+        float leftImageTextEdge = leftEdge;
+        float rightImageTextEdge = rightEdge;
+
+
+        if (addImageOnLeft) {
+          cb.addTemplate(template, leftEdge, toYPosition);
+          leftImageTextEdge = leftEdge + templateWidth + 5;
+          addImageOnLeft = false;
+        } else {
+          cb.addTemplate(template, rightEdge - templateWidth, toYPosition);
+          rightImageTextEdge = rightEdge - templateWidth - 5;
+          addImageOnLeft = true;
+        }
+
+        logger.debug("adding template at " + leftEdge + "," + toYPosition);
+
+        //and fill some text while we are at it
+
+        float[] leftBottomCols = {leftImageTextEdge, currentYPosition, leftImageTextEdge, toYPosition};
+        float[] rightBottomCols = {rightImageTextEdge, currentYPosition, rightImageTextEdge, toYPosition};
+        ct.setColumns(leftBottomCols, rightBottomCols);
+        ct.setYLine(currentYPosition);
+        ct.setAlignment(Element.ALIGN_JUSTIFIED);
+        try {
+          status = ct.go();
+          currentYPosition = toYPosition;
+        }
+        catch (DocumentException de) {
+          logger.error(de.getMessage());
+        }
+
+
+      } else {
+        //add an image on the left with a big caption to the right
+        currentYPosition = currentYPosition - 10;
+        float templateMinimumHeight = img_height;
+        float templateWidth = img_width;
+        float templateHeight = templateMinimumHeight + contentLineHeight - (templateMinimumHeight % contentLineHeight);
+        PdfTemplate template = cb.createTemplate(templateWidth, templateHeight);
+        if (! enoughY((new Float(templateHeight)).intValue())) {
+          newPage();
+        }
+        float toYPosition = currentYPosition - templateHeight;
+        try {
+          Image theImage = Image.getInstance(localImageDir + img_path);
+          theImage.setAbsolutePosition(0, 13);
+          theImage.scaleAbsolute(img_width, img_height);
+          template.addImage(theImage);
+        }
+        catch (BadElementException de) {
+          logger.error(de.getMessage());
+        }
+        catch (DocumentException de) {
+          logger.error(de.getMessage());
+        }
+        catch (MalformedURLException de) {
+          logger.error(de.getMessage());
+        }
+        catch (IOException de) {
+          logger.error(de.getMessage());
+        }
+
+        cb.addTemplate(template, leftEdge, toYPosition);
+
+        // add a big caption
+        ColumnText cct = new ColumnText(cb);
+        float[] leftCaptionCols = {leftEdge + templateWidth + 5, currentYPosition - 5, leftEdge + templateWidth + 5, toYPosition};
+        float[] rightCaptionCols = {rightEdge, currentYPosition - 5, rightEdge, toYPosition};
+
+        Paragraph captionP = new Paragraph(img_title, new Font(bigImageCaptionFontFamily, bigImageCaptionFontSize, Font.BOLD));
+        cct.addText(captionP);
+        cct.setColumns(leftCaptionCols, rightCaptionCols);
+        cct.setYLine(currentYPosition - 5);
+        cct.setAlignment(Element.ALIGN_LEFT);
+        try {
+          cct.go();
+          currentYPosition = toYPosition;
+        }
+        catch (DocumentException de) {
+          logger.error(de.getMessage());
+        }
       }
     }
 
     //add the rest of the text which might be left
     int brake = 10000;
-    while ((status & ColumnText.NO_MORE_TEXT) == 0  && brake > 0){
-      status=addTextLine(ct,contentLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+    while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0) {
+      status = addTextLine(ct, contentLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
       brake --;
     }
     if (brake == 0)
       logger.error("runaway content....try decreasing font size or increasing line height");
   }
 
-  private void addArticleSource(ColumnText ct,String theSource){
-    Paragraph sourceP = new Paragraph(theSource,new Font(sourceFontFamily,sourceFontSize,Font.BOLD));
+  private void addArticleSource(ColumnText ct, String theSource) {
+    Paragraph sourceP = new Paragraph(theSource, new Font(sourceFontFamily, sourceFontSize, Font.BOLD));
     ct.addText(sourceP);
-    addTextLine(ct,sourceLineHeight,Element.ALIGN_RIGHT,leftEdge,rightEdge);
+    addTextLine(ct, sourceLineHeight, Element.ALIGN_RIGHT, leftEdge, rightEdge);
   }
 
 
-  private boolean enoughY(int heightOfBlockToAdd){
-    if ((currentYPosition - heightOfBlockToAdd - footerHeight) < bottomEdge )
+  private boolean enoughY(int heightOfBlockToAdd) {
+    if ((currentYPosition - heightOfBlockToAdd - footerHeight) < bottomEdge)
       return false;
-               return true;
+    return true;
   }
 
 
-  public void add(EntityContent entityContent){
+  public void add(EntityContent entityContent) {
     logger.error("adding a content Entity");
 
     /*
@@ -637,11 +632,11 @@ public class PDFGenerator{
     List extraTables = new ArrayList();
     extraTables.add("content_x_media cxm");
     Iterator images = new EntityBrowser(
-      DatabaseImages.getInstance(), "i", extraTables,
-        "cxm.content_id="+entityContent.getId()+"and cxm.media_id=i.id",
+        DatabaseImages.getInstance(), "i", extraTables,
+        "cxm.content_id=" + entityContent.getId() + "and cxm.media_id=i.id",
         "i.id desc", 30, -1, 0);
 
-    String isHTML  = entityContent.getFieldValue("is_html");
+    String isHTML = entityContent.getFieldValue("is_html");
     String theTitle = entityContent.getFieldValue("title");
     String theCreator = entityContent.getFieldValue("creator");
     String theDate = DateTimeRoutines.advancedDateFormat(
@@ -652,115 +647,112 @@ public class PDFGenerator{
 
     String theDescriptionRaw = entityContent.getFieldValue("description");
     String theContentRaw = entityContent.getFieldValue("content_data");
-    String theSource =  configuration.getString("Producer.PublicationHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getFieldValue("publish_path") + entityContent.getFieldValue("id") + ".shtml";
-
+    String theSource = configuration.getString("Producer.PublicationHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getFieldValue("publish_path") + entityContent.getFieldValue("id") + ".shtml";
 
 
     String theContent = "";
     String theDescription = "";
 
-    if (isHTML.equals("1")){
-
+    if (isHTML.equals("1")) {
 
 
       try {
-  RE nobackslashr = new RE("\r");
-  theContent= nobackslashr.substituteAll(theContentRaw,"");
-  theDescription= nobackslashr.substituteAll(theDescriptionRaw,"");
-
-  RE HxTag = new RE("</?h[1-6][^>]*>",RE.REG_ICASE);
-  theContent = HxTag.substituteAll(theContent,"\n\n");
-  theDescription = HxTag.substituteAll(theDescription,"\n\n");
-
-  RE ListItemTag = new RE("<li[^>]*>",RE.REG_ICASE);
-  theContent = ListItemTag.substituteAll(theContent,"\n * ");
-  theDescription = ListItemTag.substituteAll(theDescription,"\n * ");
-
-  RE ListTag = new RE("<(u|o)l[^>]*>",RE.REG_ICASE);
-  theContent = ListTag.substituteAll(theContent,"\n");
-  theDescription = ListTag.substituteAll(theDescription,"\n");
-
-  RE DivTag = new RE("</?div[^>]*>",RE.REG_ICASE);
-  theContent= DivTag.substituteAll(theContent,"\n");
-  theDescription= DivTag.substituteAll(theDescription,"\n");
-
-  RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
-  theContent= PTag.substituteAll(theContent,"\n    ");
-  theDescription= PTag.substituteAll(theDescription,"\n    ");
-
-  RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
-  theContent= PTagClose.substituteAll(theContent,"\n");
-  theDescription= PTagClose.substituteAll(theDescription,"\n");
-
-  RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
-  theContent= BRTag.substituteAll(theContent,"\n");
-  theDescription= BRTag.substituteAll(theDescription,"\n");
-
-  RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>",RE.REG_ICASE);
-  REMatchEnumeration atags= ATagAll.getMatchEnumeration(theContent);
-  String theContentCopy=theContent;
-  while (atags.hasMoreMatches()){
-    REMatch atag = atags.nextMatch();
-    String atagString=atag.toString();
-    String atagStringHref=atag.toString(1);
-    String atagStringText=atag.toString(2);
-    int begin=theContentCopy.indexOf(atagString);
-    theContentCopy=theContentCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theContentCopy.substring(begin+atagString.length());
-  }
-  theContent=theContentCopy;
-
-  REMatchEnumeration atags2= ATagAll.getMatchEnumeration(theDescription);
-  String theDescriptionCopy=theDescription;
-  while (atags2.hasMoreMatches()){
-    REMatch atag = atags2.nextMatch();
-    String atagString=atag.toString();
-    String atagStringHref=atag.toString(1);
-    String atagStringText=atag.toString(2);
-    int begin=theDescriptionCopy.indexOf(atagString);
-    theDescriptionCopy=theDescriptionCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theDescriptionCopy.substring(begin+atagString.length());
-  }
-  theDescription=theDescriptionCopy;
-
-
-  RE noTags = new RE("<[^>]*>");
-  theContent= noTags.substituteAll(theContent," ");
-  theDescription= noTags.substituteAll(theDescription," ");
-
-  theContent = HTMLRoutines.resolveHTMLEntites(theContent);
-  theDescription = HTMLRoutines.resolveHTMLEntites(theDescription);
-
-  RE re1 = new RE("\r?\n\r?\n");
-  String theDescription1 = re1.substituteAll(theDescription,"BREAKHERE");
-
-  RE re2 = new RE("\r?\n");
-  String theDescription2 = re2.substituteAll(theDescription1," ");
-
-  RE re3 = new RE("BREAKHERE");
-  theDescription = re3.substituteAll(theDescription2,"\n    ");
+        RE nobackslashr = new RE("\r");
+        theContent = nobackslashr.substituteAll(theContentRaw, "");
+        theDescription = nobackslashr.substituteAll(theDescriptionRaw, "");
+
+        RE HxTag = new RE("</?h[1-6][^>]*>", RE.REG_ICASE);
+        theContent = HxTag.substituteAll(theContent, "\n\n");
+        theDescription = HxTag.substituteAll(theDescription, "\n\n");
+
+        RE ListItemTag = new RE("<li[^>]*>", RE.REG_ICASE);
+        theContent = ListItemTag.substituteAll(theContent, "\n * ");
+        theDescription = ListItemTag.substituteAll(theDescription, "\n * ");
+
+        RE ListTag = new RE("<(u|o)l[^>]*>", RE.REG_ICASE);
+        theContent = ListTag.substituteAll(theContent, "\n");
+        theDescription = ListTag.substituteAll(theDescription, "\n");
+
+        RE DivTag = new RE("</?div[^>]*>", RE.REG_ICASE);
+        theContent = DivTag.substituteAll(theContent, "\n");
+        theDescription = DivTag.substituteAll(theDescription, "\n");
+
+        RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
+        theContent = PTag.substituteAll(theContent, "\n    ");
+        theDescription = PTag.substituteAll(theDescription, "\n    ");
+
+        RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
+        theContent = PTagClose.substituteAll(theContent, "\n");
+        theDescription = PTagClose.substituteAll(theDescription, "\n");
+
+        RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
+        theContent = BRTag.substituteAll(theContent, "\n");
+        theDescription = BRTag.substituteAll(theDescription, "\n");
+
+        RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>", RE.REG_ICASE);
+        REMatchEnumeration atags = ATagAll.getMatchEnumeration(theContent);
+        String theContentCopy = theContent;
+        while (atags.hasMoreMatches()) {
+          REMatch atag = atags.nextMatch();
+          String atagString = atag.toString();
+          String atagStringHref = atag.toString(1);
+          String atagStringText = atag.toString(2);
+          int begin = theContentCopy.indexOf(atagString);
+          theContentCopy = theContentCopy.substring(0, begin) + atagStringText + " [" + atagStringHref + "] " + theContentCopy.substring(begin + atagString.length());
+        }
+        theContent = theContentCopy;
+
+        REMatchEnumeration atags2 = ATagAll.getMatchEnumeration(theDescription);
+        String theDescriptionCopy = theDescription;
+        while (atags2.hasMoreMatches()) {
+          REMatch atag = atags2.nextMatch();
+          String atagString = atag.toString();
+          String atagStringHref = atag.toString(1);
+          String atagStringText = atag.toString(2);
+          int begin = theDescriptionCopy.indexOf(atagString);
+          theDescriptionCopy = theDescriptionCopy.substring(0, begin) + atagStringText + " [" + atagStringHref + "] " + theDescriptionCopy.substring(begin + atagString.length());
+        }
+        theDescription = theDescriptionCopy;
+
+
+        RE noTags = new RE("<[^>]*>");
+        theContent = noTags.substituteAll(theContent, " ");
+        theDescription = noTags.substituteAll(theDescription, " ");
+
+        theContent = HTMLRoutines.resolveHTMLEntites(theContent);
+        theDescription = HTMLRoutines.resolveHTMLEntites(theDescription);
+
+        RE re1 = new RE("\r?\n\r?\n");
+        String theDescription1 = re1.substituteAll(theDescription, "BREAKHERE");
+
+        RE re2 = new RE("\r?\n");
+        String theDescription2 = re2.substituteAll(theDescription1, " ");
+
+        RE re3 = new RE("BREAKHERE");
+        theDescription = re3.substituteAll(theDescription2, "\n    ");
 
 
       }
-      catch(REException ree){
-  logger.error(ree.getMessage());
+      catch (REException ree) {
+        logger.error(ree.getMessage());
       }
-    }
-    else {
+    } else {
       try {
-  RE re1 = new RE("\r?\n\r?\n");
-  String theContent1 = re1.substituteAll(theContentRaw,"BREAKHERE");
-  String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
+        RE re1 = new RE("\r?\n\r?\n");
+        String theContent1 = re1.substituteAll(theContentRaw, "BREAKHERE");
+        String theDescription1 = re1.substituteAll(theDescriptionRaw, "BREAKHERE");
 
-  RE re2 = new RE("\r?\n");
-  String theContent2 = re2.substituteAll(theContent1," ");
-  String theDescription2 = re2.substituteAll(theDescription1," ");
+        RE re2 = new RE("\r?\n");
+        String theContent2 = re2.substituteAll(theContent1, " ");
+        String theDescription2 = re2.substituteAll(theDescription1, " ");
 
-  RE re3 = new RE("BREAKHERE");
-  theContent = "    " + re3.substituteAll(theContent2,"\n    ");
-  theDescription = re3.substituteAll(theDescription2,"\n    ");
+        RE re3 = new RE("BREAKHERE");
+        theContent = "    " + re3.substituteAll(theContent2, "\n    ");
+        theDescription = re3.substituteAll(theDescription2, "\n    ");
 
       }
-      catch(REException ree){
-  logger.error(ree.getMessage());
+      catch (REException ree) {
+        logger.error(ree.getMessage());
       }
     }
 
@@ -768,36 +760,28 @@ public class PDFGenerator{
 
     ColumnText ct = new ColumnText(cb);
 
-    addArticleMetaInfo(ct,theTitle,theCreator,theDate);
-    addArticleDescription(ct,theDescription);
-    addArticleContent(ct,theContent,images);
-    addArticleSource(ct,theSource);
-
+    addArticleMetaInfo(ct, theTitle, theCreator, theDate);
+    addArticleDescription(ct, theDescription);
+    addArticleContent(ct, theContent, images);
+    addArticleSource(ct, theSource);
   }
 
   public int getFontByName(String fontName) {
     int theFont = 0;
-    if (fontName.equalsIgnoreCase("helvetica")){
+    if ("helvetica".equalsIgnoreCase(fontName)) {
       theFont = Font.HELVETICA;
     }
+    else if ("courier".equalsIgnoreCase(fontName)) {
+      theFont = Font.COURIER;
+    }
+    else if ("times".equalsIgnoreCase(fontName)) {
+      theFont = Font.TIMES_ROMAN;
+    }
     else {
-      if (fontName.equalsIgnoreCase("courier")) {
-  theFont = Font.COURIER;
-      }
-      else {
-  if (fontName.equalsIgnoreCase("times")) {
-    theFont = Font.TIMES_ROMAN;
-  }
-  else {
-    logger.error("using helvetica because I can't get font for name: "+fontName);
-    theFont = Font.HELVETICA;
-  }
-      }
+      logger.error("using helvetica because I can't get font for name: " + fontName);
+      theFont = Font.HELVETICA;
     }
 
     return theFont;
-
   }
-}
-
-
+}
\ No newline at end of file
index 7963a03..3869a3d 100755 (executable)
@@ -33,37 +33,43 @@ import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.Locale;
 import java.util.Map;
+import java.util.HashMap;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.entity.adapter.EntityAdapter;
+import mir.entity.Entity;
 import mir.generator.Generator;
 import mir.generator.GeneratorHelper;
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
+import mir.servlet.AdminServletModule;
 import mircoders.entity.EntityUsers;
 import mircoders.global.MirGlobal;
 
 
 public class ServletHelper {
-  private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");
+  private static final LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");
 
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {
+  private ServletHelper() {
+  }
+
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) {
     return makeGenerationData(aRequest, aResponse, aLocales, "etc/bundles/adminlocal", "bundles/admin");
   }
 
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) {
     return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);
   }
 
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) {
     try {
       MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
       Map result = GeneratorHelper.makeBasicGenerationData(aLocales, aBundle, aDefaultBundle);
-      if (configuration.getString("Mir.Admin.ShowLoggedinUsers").equals("1")) {
+      if (configuration.getBoolean("Mir.Admin.ShowLoggedinUsers")) {
         result.put("loggedinusers", MirGlobal.getLoggedInUsers());
       }
       else {
@@ -85,13 +91,11 @@ public class ServletHelper {
     }
   }
 
-  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
+  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) {
     logger.debug("generator used: " + aGenerator);
 
-    Generator generator;
-
     try {
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);
+      Generator generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);
 
       generator.generate(aWriter, aGenerationData, logger);
     }
@@ -100,11 +104,9 @@ public class ServletHelper {
     }
   }
 
-  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
-    Generator generator;
-
+  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) {
     try {
-      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
+      Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
 
       generator.generate(aWriter, aGenerationData, logger);
     }
@@ -114,7 +116,7 @@ public class ServletHelper {
   }
 
   public static void generateInfoMessage(HttpServletRequest aRequest, HttpServletResponse aResponse,
-      Locale[] aLocales, String aBundle, String aDefaultBundle, String aMessage, String anArgument1, String anArgument2) throws ServletModuleExc {
+      Locale[] aLocales, String aBundle, String aDefaultBundle, String aMessage, String anArgument1, String anArgument2) {
     Map responseData = makeGenerationData(aRequest, aResponse, aLocales, aBundle, aDefaultBundle);
     responseData.put("message", aMessage);
     responseData.put("argument1", anArgument1);
@@ -128,7 +130,7 @@ public class ServletHelper {
     }
   }
 
-  public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {
+  public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleFailure {
     try {
       aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));
     }
@@ -137,15 +139,17 @@ public class ServletHelper {
     }
   }
 
-  public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure {
+  public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleFailure {
     redirect(aResponse, "module="+aModule+"&do="+aMethod);
   }
 
   public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {
-    if (aUser!=null)
+    if (aUser!=null) {
       aRequest.getSession().setAttribute("login.uid", aUser);
-    else
+    }
+    else {
       aRequest.getSession().removeAttribute("login.uid");
+    }
   }
 
   public static EntityUsers getUser(HttpServletRequest aRequest) {
@@ -154,7 +158,8 @@ public class ServletHelper {
 
   public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {
     try {
-      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid"));
+      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("user",
+          (Entity) aRequest.getSession().getAttribute("login.uid"));
     }
     catch (Throwable t) {
       throw new ServletModuleFailure (t);
@@ -164,8 +169,58 @@ public class ServletHelper {
   public static String getUserName(HttpServletRequest aRequest) {
     EntityUsers user = getUser(aRequest);
 
-    if (user!=null)
+    if (user!=null) {
       return user.getFieldValue("login");
-               return "nobody";
+    }
+
+    return "nobody";
+  }
+
+  private static final Map servletModules = new HashMap();
+
+  public static AdminServletModule getServletModule(String aName) throws ServletModuleExc {
+    synchronized (servletModules) {
+      if (!servletModules.containsKey(aName)) {
+        // was not found in the cache...
+        try {
+          Class servletModuleClass =
+            Class.forName("mircoders.servlet.ServletModule" + aName);
+
+          AdminServletModule module = (AdminServletModule)
+              servletModuleClass.newInstance();
+
+          // we put it into our cache for future calls
+          servletModules.put(aName, module);
+
+          return module;
+        }
+        catch (Exception e) {
+          throw new ServletModuleExc("*** error resolving classname for " + aName + " -- " + e.getMessage());
+        }
+      }
+
+      return (AdminServletModule) servletModules.get(aName);
+    }
+  }
+
+  public static ServletModuleFileEdit getServletModuleFileEdit() throws ServletModuleExc {
+    return (ServletModuleFileEdit) getServletModule("FileEdit");
+  }
+
+  public static ServletModuleLocalizer getServletModuleLocalizer() throws ServletModuleExc {
+    return (ServletModuleLocalizer) getServletModule("Localizer");
   }
+
+  public static ServletModuleAdmin getServletModuleAdmin() throws ServletModuleExc {
+    return (ServletModuleAdmin) getServletModule("Admin");
+  }
+
+  public static ServletModuleContent getServletModuleContent() throws ServletModuleExc {
+    return (ServletModuleContent) getServletModule("Content");
+  }
+
+  public static ServletModuleComment getServletModuleComment() throws ServletModuleExc {
+    return (ServletModuleComment) getServletModule("Comment");
+  }
+
 }
index 4ceb5e7..a8afbb2 100755 (executable)
 
 package mircoders.servlet;
 
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.storage.DatabaseExc;
@@ -45,8 +39,11 @@ import mir.util.URLBuilder;
 import mircoders.abuse.FilterEngine;
 import mircoders.global.MirGlobal;
 
-public class ServletModuleAbuse extends ServletModule {
-  private static ServletModuleAbuse instance = new ServletModuleAbuse();
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Map;
+
+public class ServletModuleAbuse extends AdminServletModule {
   private String editFilterTemplate;
   private String listFiltersTemplate;
   private String editFilterGroupTemplate;
@@ -54,18 +51,17 @@ public class ServletModuleAbuse extends ServletModule {
   private String mainTemplate;
   private String viewLogTemplate;
 
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleAbuse() {
-    logger = new LoggerWrapper("ServletModule.Abuse");
-    defaultAction = "showsettings";
+  public ServletModuleAbuse() {
+    editFilterTemplate = getConfiguration().getString("ServletModule.Abuse.EditFilter.Template");
+    listFiltersTemplate = getConfiguration().getString("ServletModule.Abuse.ListFilters.Template");
+    editFilterGroupTemplate = getConfiguration().getString("ServletModule.Abuse.EditFilterGroup.Template");
+    listFilterGroupsTemplate = getConfiguration().getString("ServletModule.Abuse.ListFilterGroups.Template");
+    viewLogTemplate = getConfiguration().getString("ServletModule.Abuse.ViewLog.Template");
+    mainTemplate = getConfiguration().getString("ServletModule.Abuse.Main.Template");
+  }
 
-    editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template");
-    listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template");
-    editFilterGroupTemplate = configuration.getString("ServletModule.Abuse.EditFilterGroup.Template");
-    listFilterGroupsTemplate = configuration.getString("ServletModule.Abuse.ListFilterGroups.Template");
-    viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template");
-    mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template");
+  protected void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    showsettings(aRequest, aResponse);
   }
 
   public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
@@ -164,7 +160,7 @@ public class ServletModuleAbuse extends ServletModule {
     String id=requestParser.getParameter("id");
     String groupid=requestParser.getParameter("groupid");
     MirGlobal.abuse().getFilterEngine().deleteFilter(groupid, id);
-    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + "filter:"+groupid+":"+id, "filter deleted");
+    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filter:"+groupid+":"+id, "filter deleted");
 
     listfilters(aRequest, aResponse);
   }
@@ -175,7 +171,7 @@ public class ServletModuleAbuse extends ServletModule {
     String groupid=requestParser.getParameter("groupid");
     MirGlobal.abuse().getFilterEngine().deleteFilterGroup(groupid);
 
-    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + "filtergroup:"+groupid, "filter group deleted");
+    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filtergroup:"+groupid, "filter group deleted");
 
     showfiltergroups(aRequest, aResponse);
   }
index 2057259..737bc01 100755 (executable)
  */
 package mircoders.servlet;
 
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Map;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.adapter.EntityIteratorAdapter;
 import mir.entity.adapter.EntityAdapterEngine;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
-import mir.util.CachingRewindableIterator;
 import mir.util.URLBuilder;
 import mircoders.global.MirGlobal;
 
-public class ServletModuleAdmin extends ServletModule
-{
-  private static ServletModuleAdmin instance = new ServletModuleAdmin();
-  public static ServletModule getInstance() { return instance; }
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.List;
+import java.util.Map;
 
-  private ServletModuleAdmin() {
-    logger = new LoggerWrapper("ServletModule.Admin");
-    defaultAction = "start";
+public class ServletModuleAdmin extends AdminServletModule {
+  public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    start(aRequest, aResponse);
   }
 
   public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {
@@ -113,18 +104,21 @@ public class ServletModuleAdmin extends ServletModule
   }
 
   public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    String defaultStartTemplate = configuration.getString("Mir.StartTemplate");
+    String defaultStartTemplate = getConfiguration().getString("Mir.StartTemplate");
 
     try {
       Map templateData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest),
           "bundles/admin", "etc/bundles/adminlocal");
 
-      List messages = EntityAdapterEngine.retrieveAdapterList(model, "internalMessage", "", "webdb_create desc", 10, 0);
+      List messages = EntityAdapterEngine.retrieveAdapterList(getModel(),
+          "internalMessage", "", "webdb_create desc", 10, 0);
 
       templateData.put("messages", messages);
 
-      templateData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
-      templateData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
+      templateData.put("fileeditentries",
+          ServletHelper.getServletModuleFileEdit().getEntries());
+      templateData.put("administeroperations",
+          ServletHelper.getServletModuleLocalizer().getAdministerOperations());
 
       templateData.put("searchvalue", null);
       templateData.put("searchfield", null);
index 1a99da2..a123238 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleArticleType;
 
 /**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * ServletModule for managing article types
  */
-public class ServletModuleArticleType extends ServletModule
-{
-  private static ServletModuleArticleType instance = new ServletModuleArticleType();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleArticleType() {
-    logger = new LoggerWrapper("ServletModule.ArticleType");
-
-    try {
-      definition = "articleType";
-      mainModule = new ModuleArticleType();
-    }
-    catch (Exception e) {
-      logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
-    }
+public class ServletModuleArticleType extends AdminServletModule {
+  public ServletModuleArticleType() {
+    definition = "articleType";
+    mainModule = new ModuleArticleType();
   }
 }
index 4ef89ed..7595b81 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseAudio;
 
-/*
- *
- *
- * @author br1
+/**
+ * ServletModule for managing Audio uploads
  */
-
 public class ServletModuleAudio extends ServletModuleUploadedMedia {
-  private static ServletModuleAudio instance = new ServletModuleAudio();
-
-  public static ServletModule getInstance() {
-    return instance;
-  }
-
-  private ServletModuleAudio() {
-    logger = new LoggerWrapper("ServletModule.Audio");
-
-    moduleName = "Audio";
-
-    try {
-      definition = "audio";
-      mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance());
-    }
-    catch (Throwable e) {
-      logger.error("servletmodule audio could not be initialized: " + e.getMessage());
-    }
+  public ServletModuleAudio() {
+    super("Audio");
+    definition = "audio";
+    mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance());
   }
 }
 
index c18ffc7..2ea482e 100755 (executable)
 
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleBreaking;
 
 /**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * ServletModule for managing breaking news
  */
 
-public class ServletModuleBreaking extends ServletModule
-{
-  private static ServletModuleBreaking instance = new ServletModuleBreaking();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleBreaking() {
-    logger = new LoggerWrapper("ServletModule.Breaking");
-
-    try {
-      definition = "breakingNews";
-      mainModule = new ModuleBreaking();
-    }
-    catch (Exception e) {
-      logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage());
-    }
+public class ServletModuleBreaking extends AdminServletModule {
+  public ServletModuleBreaking() {
+    definition = "breakingNews";
+    mainModule = new ModuleBreaking();
   }
 }
index eff08cd..8f6bbeb 100755 (executable)
@@ -32,8 +32,7 @@ package mircoders.servlet;
 
 import mir.entity.adapter.EntityAdapterEngine;
 import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.servlet.ServletModuleUserExc;
@@ -48,29 +47,20 @@ import mircoders.storage.DatabaseComment;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.util.*;
-
-/*
- *  ServletModuleComment - controls navigation for Comments
- *
- *
- *  @author the mir-coders
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * ServletModule for managing Comments
  */
 
-public class ServletModuleComment extends ServletModule
-{
-  private static ServletModuleComment instance = new ServletModuleComment();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleComment() {
-    logger = new LoggerWrapper("ServletModule.Comment");
-    try {
-      mainModule = new ModuleComment();
-      definition = "comment";
-    }
-    catch (Exception e) {
-      logger.error("servletmodule comment could not be initialized:" + e.getMessage());
-    }
+public class ServletModuleComment extends AdminServletModule {
+  public ServletModuleComment() {
+    mainModule = new ModuleComment();
+    definition = "comment";
   }
 
   public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
@@ -84,12 +74,12 @@ public class ServletModuleComment extends ServletModule
     }
   }
 
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
     String idParam = aRequest.getParameter("id");
 
-    if (idParam == null)
+    if (idParam == null) {
       throw new ServletModuleExc("Invalid call: id not supplied ");
+    }
 
     editObject(aRequest, aResponse, idParam);
   }
@@ -139,7 +129,9 @@ public class ServletModuleComment extends ServletModule
     String  mediaIdParam = aRequest.getParameter("mid");
     String  commentId = aRequest.getParameter("commentid");
 
-    if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
+    if (commentId == null || mediaIdParam==null) {
+      throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
+    }
 
     try {
       EntityComment comment = (EntityComment) mainModule.getById(commentId);
@@ -158,10 +150,12 @@ public class ServletModuleComment extends ServletModule
   {
     String  commentId = aRequest.getParameter("commentid");
     String  midParam = aRequest.getParameter("mid");
-    if (commentId == null)
+    if (commentId == null) {
       throw new ServletModuleExc("smod comment :: dettach :: commentid missing");
-    if (midParam == null)
+    }
+    if (midParam == null) {
       throw new ServletModuleExc("smod comment :: dettach :: mid missing");
+    }
 
     try {
       EntityComment comment = (EntityComment)mainModule.getById(commentId);
@@ -199,10 +193,10 @@ public class ServletModuleComment extends ServletModule
     String searchStatus = requestParser.getParameter("searchstatus");
     String searchOrder = requestParser.getParameter("searchorder");
 
-    if (searchIsPublished.equals("0")) {
+    if ("0".equals(searchIsPublished)) {
       queryBuilder.appendAndCondition("is_published='f'");
     }
-    else if (searchIsPublished.equals("1")) {
+    else if ("1".equals(searchIsPublished)) {
       queryBuilder.appendAndCondition("is_published='t'");
     }
 
@@ -217,26 +211,27 @@ public class ServletModuleComment extends ServletModule
     }
 
     if (searchOrder.length()>0) {
-      if (searchOrder.equals("datedesc"))
+      if ("datedesc".equals(searchOrder)) {
         queryBuilder.appendDescendingOrder("webdb_create");
-      else if (searchOrder.equals("dateasc"))
+      }
+      else if ("dateasc".equals(searchOrder)) {
         queryBuilder.appendAscendingOrder("webdb_create");
-      else if (searchOrder.equals("articletitle"))
+      }
+      else if ("articletitle".equals(searchOrder)) {
         queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");
-      else if (searchOrder.equals("creator"))
+      }
+      else if ("creator".equals(searchOrder)) {
         queryBuilder.appendDescendingOrder("creator");
+      }
     }
 
     returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
   }
 
-  public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
+  public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
     String articleIdString = aRequest.getParameter("articleid");
-    int articleId;
-
     try {
-      articleId  = Integer.parseInt(articleIdString);
+      int articleId  = Integer.parseInt(articleIdString);
 
       returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0);
     }
@@ -255,7 +250,8 @@ public class ServletModuleComment extends ServletModule
       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
 
       List commentList =
-         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
+         EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause,
+             anOrderByClause, nrEntitiesPerListPage, anOffset);
 
       responseData.put("nexturl", null);
       responseData.put("prevurl", null);
@@ -278,7 +274,7 @@ public class ServletModuleComment extends ServletModule
       responseData.put("searchorder", requestParser.getParameter("searchorder"));
 
       urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("offset" , Integer.toString(anOffset));
       responseData.put("thisurl" , urlBuilder.getQuery());
 
       if (commentList.size()>=nrEntitiesPerListPage) {
@@ -310,19 +306,23 @@ public class ServletModuleComment extends ServletModule
       String returnUrl = requestParser.getParameter("returnurl");
 
       String idParam = aRequest.getParameter("id");
-      if (idParam == null)
+      if (idParam == null) {
         throw new ServletModuleExc("Wrong call: (id) is missing");
+      }
 
       Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance());
 
-      if (!withValues.containsKey("is_published"))
+      if (!withValues.containsKey("is_published")) {
         withValues.put("is_published","0");
-      if (!withValues.containsKey("is_html"))
+      }
+      if (!withValues.containsKey("is_html")) {
         withValues.put("is_html","0");
+      }
 
       String webdbCreate = (String) withValues.get("webdb_create");
-      if (webdbCreate==null || webdbCreate.trim().length()==0)
+      if (webdbCreate==null || webdbCreate.trim().length()==0) {
         withValues.remove("webdb_create");
+      }
 
       String id = mainModule.set(withValues);
 
@@ -331,8 +331,9 @@ public class ServletModuleComment extends ServletModule
       if (returnUrl!=null){
         ServletHelper.redirect(aResponse, returnUrl);
       }
-      else
+      else {
         editObject(aRequest, aResponse, idParam);
+      }
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
index 71767a0..881f91f 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleCommentStatus;
 
 
-public class ServletModuleCommentStatus extends ServletModule
-{
-  private static ServletModuleCommentStatus instance = new ServletModuleCommentStatus();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleCommentStatus() {
-    logger = new LoggerWrapper("ServletModule.CommentStatus");
-
-    try {
-      definition = "commentStatus";
-      mainModule = new ModuleCommentStatus();
-    }
-    catch (Throwable e) {
-      logger.error("Initialization of ServletModuleCommentStatus failed!: " + e.getMessage());
-    }
+public class ServletModuleCommentStatus extends AdminServletModule {
+  public ServletModuleCommentStatus() {
+    definition = "commentStatus";
+    mainModule = new ModuleCommentStatus();
   }
 }
index 7bd4dba..563fde8 100755 (executable)
@@ -34,12 +34,15 @@ import mir.entity.adapter.EntityAdapter;
 import mir.entity.adapter.EntityAdapterEngine;
 import mir.entity.adapter.EntityAdapterModel;
 import mir.generator.Generator;
-import mir.log.LoggerWrapper;
 import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
-import mir.util.*;
+import mir.util.HTTPRequestParser;
+import mir.util.JDBCStringRoutines;
+import mir.util.SQLQueryBuilder;
+import mir.util.StringRoutines;
+import mir.util.URLBuilder;
 import mircoders.entity.EntityContent;
 import mircoders.entity.EntityUsers;
 import mircoders.global.MirGlobal;
@@ -49,32 +52,26 @@ import mircoders.storage.DatabaseContentToTopics;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
 
 /**
  * Article admin interface code
  */
 
-public class ServletModuleContent extends ServletModule {
-  private static ServletModuleContent instance = new ServletModuleContent();
-  public static ServletModule getInstance() { return instance; }
-  private static ModuleContent contentModule;
+public class ServletModuleContent extends AdminServletModule {
+  private ModuleContent contentModule = new ModuleContent();
 
-  private ServletModuleContent() {
-    super();
-
-    propagatedParameters.add("selectarticleurl");
-
-    logger = new LoggerWrapper("ServletModule.Content");
-
-    try {
-      definition = "content";
-      contentModule = new ModuleContent();
-      mainModule = contentModule;
-    }
-    catch (Throwable e) {
-      logger.fatal("ServletModuleContent could not be initialized: " + e.toString());
-    }
+  public ServletModuleContent() {
+    addPropagatedParameter("selectarticleurl");
+    definition = "content";
+    mainModule = contentModule;
   }
 
   public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
@@ -88,24 +85,29 @@ public class ServletModuleContent extends ServletModule {
       String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
 
       if (searchValue.length()>0) {
-        if (searchField.equals("id"))
+        if ("id".equals(searchField)) {
           queryBuilder.appendAndCondition(
             "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
-        else if (searchField.equals("contents"))
+        }
+        else if ("contents".equals(searchField)) {
           queryBuilder.appendAndCondition(
             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
-        else
+        }
+        else {
           queryBuilder.appendAndCondition(
             "lower("+ searchField + ") like " +
             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
+        }
       }
 
       if (searchispublished.length()>0) {
-        if (searchispublished.equals("0"))
+        if ("0".equals(searchispublished)) {
           queryBuilder.appendAndCondition("is_published='f'");
-        else
+        }
+        else {
           queryBuilder.appendAndCondition("is_published='t'");
+        }
       }
 
       if (searchArticleType.length()>0) {
@@ -113,14 +115,18 @@ public class ServletModuleContent extends ServletModule {
       }
 
       if (searchOrder.length()>0) {
-        if (searchOrder.equals("datedesc"))
+        if ("datedesc".equals(searchOrder)) {
           queryBuilder.appendDescendingOrder("webdb_create");
-        else if (searchOrder.equals("dateasc"))
+        }
+        else if ("dateasc".equals(searchOrder)) {
           queryBuilder.appendAscendingOrder("webdb_create");
-        else if (searchOrder.equals("title"))
+        }
+        else if ("title".equals(searchOrder)) {
           queryBuilder.appendAscendingOrder("title");
-        else if (searchOrder.equals("creator"))
+        }
+        else if ("creator".equals(searchOrder)) {
           queryBuilder.appendAscendingOrder("creator");
+        }
       }
 
       returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
@@ -143,14 +149,17 @@ public class ServletModuleContent extends ServletModule {
       withValues.put("publish_path", StringUtil.webdbDate2path(now));
       withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
       withValues.put("is_produced", "0");
-      if (!withValues.containsKey("is_published"))
+      if (!withValues.containsKey("is_published")) {
         withValues.put("is_published","0");
-      if (!withValues.containsKey("is_html"))
+      }
+      if (!withValues.containsKey("is_html")) {
         withValues.put("is_html","0");
+      }
 
       String webdbCreate = (String) withValues.get("webdb_create");
-      if (webdbCreate==null || webdbCreate.trim().length()==0)
+      if (webdbCreate==null || webdbCreate.trim().length()==0) {
         withValues.remove("webdb_create");
+      }
 
       String id = mainModule.add(withValues);
       logAdminUsage(aRequest, id, "object added");
@@ -177,21 +186,22 @@ public class ServletModuleContent extends ServletModule {
   public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
     String  mediaIdParam = aRequest.getParameter("mid");
     String  articleId = aRequest.getParameter("articleid");
-    if (articleId == null || mediaIdParam==null)
+    if (articleId == null || mediaIdParam==null) {
       throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
+    }
+
     // check if mediaIdParam and articleid are correct integers
-    try
-    {
+    try {
       Integer.parseInt(mediaIdParam);
       Integer.parseInt(articleId);
     }
-    catch(NumberFormatException e)
-    {
-      throw new ServletModuleExc("smod content :: attach :: invalid articleid/mid");
+    catch (NumberFormatException e) {
+      throw new ServletModuleExc("smod content :: attach :: invalid articleid/mid", e);
     }
     
-    if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId))
+    if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) {
       throw new ServletModuleExc("Article has been locked");
+    }
 
     try {
       EntityContent entContent = (EntityContent) mainModule.getById(articleId);
@@ -241,13 +251,15 @@ public class ServletModuleContent extends ServletModule {
     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
 
     String idParam = requestParser.getParameter("id");
-    if (idParam == null)
+    if (idParam == null) {
       throw new ServletModuleExc("Wrong call: (id) is missing");
+    }
 
     EntityUsers user = ServletHelper.getUser(aRequest);
 
-    if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam))
+    if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) {
       throw new ServletModuleExc("Unable to lock");
+    }
 
     contentModule.lockArticle(idParam, user.getId(), false);
 
@@ -262,13 +274,15 @@ public class ServletModuleContent extends ServletModule {
     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
 
     String idParam = requestParser.getParameter("id");
-    if (idParam == null)
+    if (idParam == null) {
       throw new ServletModuleExc("Wrong call: (id) is missing");
+    }
 
     EntityUsers user = ServletHelper.getUser(aRequest);
 
-    if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam))
+    if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) {
       throw new ServletModuleExc("Unable to unlock");
+    }
 
     contentModule.unlockArticle(idParam, user.getId(), false);
 
@@ -303,23 +317,28 @@ public class ServletModuleContent extends ServletModule {
       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
 
       String idParam = requestParser.getParameter("id");
-      if (idParam == null)
+      if (idParam == null) {
         throw new ServletModuleExc("Wrong call: (id) is missing");
+      }
 
-      if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam))
+      if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) {
         throw new ServletModuleExc("Article has been locked");
+      }
 
       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
 
       withValues.put("is_produced", "0");
-      if (!withValues.containsKey("is_published"))
+      if (!withValues.containsKey("is_published")) {
         withValues.put("is_published","0");
-      if (!withValues.containsKey("is_html"))
+      }
+      if (!withValues.containsKey("is_html")) {
         withValues.put("is_html","0");
+      }
 
       String webdbCreate = (String) withValues.get("webdb_create");
-      if (webdbCreate==null || webdbCreate.trim().length()==0)
+      if (webdbCreate==null || webdbCreate.trim().length()==0) {
         withValues.remove("webdb_create");
+      }
 
       String id = mainModule.set(withValues);
 
@@ -328,7 +347,7 @@ public class ServletModuleContent extends ServletModule {
       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
 
       if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) &&
-         (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) {
+          requestParser.getParameterWithDefault("unlock", "0").equals("1")) {
         contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false);
       }
 
@@ -343,11 +362,11 @@ public class ServletModuleContent extends ServletModule {
   /**
    * Returns the basic article editing form.
    *
-   * @param id identifier of the article. <code>null</code>, means show an
+   * @param anId identifier of the article. <code>null</code>, means show an
    *     empty form to add a new article.
    */
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)
-      throws ServletModuleExc {
+  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse,
+                         String anId) throws ServletModuleExc {
     try {
       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
@@ -357,19 +376,20 @@ public class ServletModuleContent extends ServletModule {
 
       urlBuilder.setValue("module", "Content");
       urlBuilder.setValue("do", "edit");
-      urlBuilder.setValue("id", id);
+      urlBuilder.setValue("id", anId);
       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
 
-      if (id!=null) {
+      if (anId !=null) {
         responseData.put("new", Boolean.FALSE);
-        article = model.makeEntityAdapter("content", mainModule.getById(id));
+        article = model.makeEntityAdapter("content", mainModule.getById(anId));
 
         EntityUsers user = ServletHelper.getUser(aRequest);
 
-        responseData.put("mayEdit", new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, id)));
-        responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, id)));
-        responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, id)));
-        responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, id)));
+        responseData.put("mayEdit",
+            new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, anId)));
+        responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, anId)));
+        responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, anId)));
+        responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, anId)));
       }
       else {
         List fields = DatabaseContent.getInstance().getFieldNames();
@@ -395,7 +415,7 @@ public class ServletModuleContent extends ServletModule {
 
       List topicsList = new ArrayList();
 
-      String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");
+      String[] topicCategories = getConfiguration().getStringArray("Mir.Localizer.Admin.TopicLists");
 
       if (topicCategories.length==0 ) {
         Map categoryMap = new HashMap();
@@ -407,37 +427,37 @@ public class ServletModuleContent extends ServletModule {
       }
       else {
         for (int i = 0; i < topicCategories.length; i++) {
-          try {
-            Map categoryMap = new HashMap();
-            List parts = StringRoutines.splitString(topicCategories[i], ":");
-
-            String key = null;
-            String listtype = "0";
-            String listparameter = "5";
-            String where = "";
-            String order = "";
-
-            if (parts.size() > 0)
-              key = (String) parts.get(0);
-            if (parts.size() > 1)
-              listtype = (String) parts.get(1);
-            if (parts.size() > 2)
-              listparameter = (String) parts.get(2);
-            if (parts.size() > 3)
-              where = (String) parts.get(3);
-            if (parts.size() > 4)
-              order = (String) parts.get(4);
-
-            if (key != null) {
-              categoryMap.put("key", key);
-              categoryMap.put("listtype", listtype);
-              categoryMap.put("listparameter", listparameter);
-              categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
-              topicsList.add(categoryMap);
-            }
+          Map categoryMap = new HashMap();
+          List parts = StringRoutines.splitString(topicCategories[i], ":");
+
+          String key = null;
+
+          if (parts.size() > 0) {
+            key = (String) parts.get(0);
+          }
+          String listtype = "0";
+          if (parts.size() > 1) {
+            listtype = (String) parts.get(1);
+          }
+          String listparameter = "5";
+          if (parts.size() > 2) {
+            listparameter = (String) parts.get(2);
           }
-          catch (Throwable t) {
-            logger.error("error while preparing topics: " + t.toString());
+          String where = "";
+          if (parts.size() > 3) {
+            where = (String) parts.get(3);
+          }
+          String order = "";
+          if (parts.size() > 4) {
+            order = (String) parts.get(4);
+          }
+
+          if (key != null) {
+            categoryMap.put("key", key);
+            categoryMap.put("listtype", listtype);
+            categoryMap.put("listparameter", listparameter);
+            categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
+            topicsList.add(categoryMap);
           }
         }
       }
@@ -473,13 +493,14 @@ public class ServletModuleContent extends ServletModule {
   }
 
   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      String articleId = requestParser.getParameter("article_id");
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    String articleId = requestParser.getParameter("article_id");
 
-      if (articleId == null)
-        throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+    if (articleId == null) {
+      throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+    }
 
+    try {
       returnList(aRequest, aResponse, "to_content = " + articleId, "webdb_create desc", 0);
     }
     catch (Throwable e) {
@@ -504,7 +525,8 @@ public class ServletModuleContent extends ServletModule {
       logAdminUsage(aRequest, articleId, "parent set to " + parentId);
     }
     catch(Throwable e) {
-      logger.error("ServletModuleContent.setparent: " + e.getMessage());
+      getLogger().error("ServletModuleContent.setparent: " + e.getMessage());
+
       throw new ServletModuleFailure(e);
     }
 
@@ -524,8 +546,7 @@ public class ServletModuleContent extends ServletModule {
       logAdminUsage(aRequest, articleId, "parent cleared");
     }
     catch(Throwable e) {
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      logger.error("ServletModuleContent.clearparent: " + e.getMessage());
+      getLogger().error("ServletModuleContent.clearparent: " + e.getMessage(), e);
 
       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
     }
@@ -537,14 +558,14 @@ public class ServletModuleContent extends ServletModule {
     try {
       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
       String articleId = requestParser.getParameter("id");
-      EntityAdapter article = model.makeEntityAdapter("content", mainModule.getById(articleId));
+      EntityAdapter article = getModel().makeEntityAdapter("content", mainModule.getById(articleId));
       String preview = requestParser.getParameterWithDefault("preview", "default");
 
       Map generationValues = new HashMap();
       Generator generator =
           MirGlobal.localizer().adminInterface().prepareArticlePreview(preview, article, generationValues);
 
-      generator.generate(aResponse.getWriter(), generationValues, logger);
+      generator.generate(aResponse.getWriter(), generationValues, getLogger());
     }
     catch (Exception e) {
       throw new ServletModuleFailure(e);
index b74a600..52bf4be 100755 (executable)
@@ -46,8 +46,7 @@ import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.util.FileRoutines;
@@ -61,59 +60,22 @@ import mir.util.URLBuilder;
  *  in the config file.
  *
  * @author $Author: zapata $
- * @version $Revision: 1.13.2.10 $ $Date: 2005/08/21 17:09:24 $
+ * @version $Revision: 1.13.2.11 $ $Date: 2005/10/01 18:40:41 $
  *
  */
 
-public class ServletModuleFileEdit extends ServletModule
-{
-  private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
-  public static ServletModule getInstance() { return instance; }
-
+public class ServletModuleFileEdit extends AdminServletModule {
   private Map directories;
   private List directoryNames;
 
   private FilenameFilter dirFilter;
 
-  private class FileEditDirectory {
-    private String name;
-    private FileRoutines.RegExpFileFilter filter;
-    private File rootDirectory;
-    private boolean recursive;
-
-    public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
-      name = aName;
-      rootDirectory = new File(aRootDirectory);
-      filter = new FileRoutines.RegExpFileFilter(aFilter);
-      recursive = aRecursive;
-    }
-
-    public String getName() {
-      return name;
-    }
-
-    public FileRoutines.RegExpFileFilter getFilter() {
-      return filter;
-    }
-
-    public File getRootDirectory() {
-      return rootDirectory;
-    }
-
-    public boolean getRecursive() {
-      return recursive;
-    }
-  }
-
-  private ServletModuleFileEdit() {
-    super();
-
-    logger = new LoggerWrapper("ServletModule.FileEdit");
-
+  public ServletModuleFileEdit() {
     directories = new HashMap();
     directoryNames = new ArrayList();
 
-    String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
+    String settings[] =
+        getConfiguration().getStringArray("ServletModule.FileEdit.Configuration");
 
     if (settings!=null) {
       for (int i = 0; i < settings.length; i++) {
@@ -122,7 +84,7 @@ public class ServletModuleFileEdit extends ServletModule
         if (setting.length() > 0) {
           List parts = StringRoutines.splitStringWithEscape(setting, ':', '\\');
           if (parts.size() != 4) {
-            logger.error("config error: " + settings[i] + ", 4 parts expected");
+            getLogger().error("config error: " + settings[i] + ", 4 parts expected");
           }
           else {
             String name = (String) parts.get(0);
@@ -131,7 +93,7 @@ public class ServletModuleFileEdit extends ServletModule
             String recursive = (String) parts.get(3);
 
             directories.put(name, new FileEditDirectory(name, directory, filter,
-                recursive.equals("1") || recursive.toLowerCase().equals("y")));
+                "1".equals(recursive) || "y".equals(recursive.toLowerCase())));
             directoryNames.add(name);
           }
         }
@@ -212,7 +174,7 @@ public class ServletModuleFileEdit extends ServletModule
     try {
       File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
 
-      if (validateDirectory(directory, f)) {
+      if (isDirectoryValid(directory, f)) {
         FileWriter out = new FileWriter(f);
         try {
           out.write(text.toCharArray());
@@ -239,7 +201,7 @@ public class ServletModuleFileEdit extends ServletModule
       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
 
-      if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
+      if (!isDirectoryValid(aDirectory, dir) || !dir.isDirectory()) {
         dir = aDirectory.getRootDirectory();
         aSubDirectory = "";
       }
@@ -274,7 +236,7 @@ public class ServletModuleFileEdit extends ServletModule
     try {
       File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
 
-      if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
+      if (!isDirectoryValid(aDirectory, f) || f.isDirectory() || !isFileValid(aDirectory, f)) {
         listSubDirectory(aDirectory, "", aRequest, aResponse);
       }
       else {
@@ -314,16 +276,16 @@ public class ServletModuleFileEdit extends ServletModule
     }
   }
 
-  protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
+  private boolean isDirectoryValid(FileEditDirectory aDirectory, File aFile) {
     try {
-      return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
+      return aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath());
     }
     catch (Throwable t) {
       return false;
     }
   }
 
-  protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
+  private boolean isFileValid(FileEditDirectory aDirectory, File aFile) {
     try {
       return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
     }
@@ -331,4 +293,35 @@ public class ServletModuleFileEdit extends ServletModule
       return false;
     }
   }
+
+  private class FileEditDirectory {
+    private String name;
+    private FileRoutines.RegExpFileFilter filter;
+    private File rootDirectory;
+    private boolean recursive;
+
+    public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
+      name = aName;
+      rootDirectory = new File(aRootDirectory);
+      filter = new FileRoutines.RegExpFileFilter(aFilter);
+      recursive = aRecursive;
+    }
+
+    public String getName() {
+      return name;
+    }
+
+    public FileRoutines.RegExpFileFilter getFilter() {
+      return filter;
+    }
+
+    public File getRootDirectory() {
+      return rootDirectory;
+    }
+
+    public boolean getRecursive() {
+      return recursive;
+    }
+  }
+
 }
index f493911..bd93638 100755 (executable)
 package mircoders.servlet;
 
 import mir.entity.adapter.EntityAdapterEngine;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
-import mir.storage.DatabaseFailure;
 import mir.util.HTTPRequestParser;
 import mir.util.JDBCStringRoutines;
 import mircoders.module.ModuleContent;
@@ -51,46 +49,36 @@ import java.util.Map;
  *  @version $Id
  */
 
-public class ServletModuleHidden extends ServletModule {
-  private static ServletModuleHidden instance = new ServletModuleHidden();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleHidden() {
-    super();
-
-    logger = new LoggerWrapper("ServletModule.Hidden");
-
-    try {
-      definition = "content";
-      mainModule = new ModuleContent();
-    }
-    catch (DatabaseFailure e) {
-      logger.error("initialization of servletmoduleHidden failed: " + e.getMessage());
-    }
+public class ServletModuleHidden extends AdminServletModule {
+  public ServletModuleHidden() {
+    definition = "content";
+    mainModule = new ModuleContent();
   }
 
 
-  public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(req);
-    Map responseData = ServletHelper.makeGenerationData(req, res, new Locale[] { getLocale(req), getFallbackLocale(req)});
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
 
-    String query_year = requestParser.getParameter("year");
-    String query_month = requestParser.getParameter("month");
+    String queryYear = requestParser.getParameter("year");
+    String queryMonth = requestParser.getParameter("month");
 
     try {
-      if ((query_year!=null && !query_year.equals("")) && (query_month!=null && !query_month.equals(""))) {
+      if ((queryYear !=null && !queryYear.equals("")) &&
+          (queryMonth !=null && !queryMonth.equals(""))) {
         String whereClause = "is_published=false AND webdb_create LIKE "+
-            "'"+JDBCStringRoutines.escapeStringLiteral(query_year)+"-"+JDBCStringRoutines.escapeStringLiteral(query_month)+"%'";
+            "'"+JDBCStringRoutines.escapeStringLiteral(queryYear)+"-"+
+               JDBCStringRoutines.escapeStringLiteral(queryMonth)+"%'";
 
 
-        List articleList = EntityAdapterEngine.retrieveAdapterList(model, definition, whereClause, "webdb_create", -1, 0);
+        List articleList = EntityAdapterEngine.retrieveAdapterList(getModel(), definition, whereClause, "webdb_create", -1, 0);
 
-        responseData.put("year", query_year);
-        responseData.put("month", query_month);
+        responseData.put("year", queryYear);
+        responseData.put("month", queryMonth);
         responseData.put("articles", articleList);
       }
 
-      ServletHelper.generateResponse(res.getWriter(), responseData, listGenerator);
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
index 1bfe0d8..20bfaad 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
 import mircoders.module.ModuleImages;
 
 /*
  *  ServletModuleImages -
  *
- * @version $Id: ServletModuleImages.java,v 1.26.2.5 2005/04/10 10:52:00 zapata Exp $
+ * @version $Id: ServletModuleImages.java,v 1.26.2.6 2005/10/01 18:40:41 zapata Exp $
  * @author RK, the mir-coders group
  */
 
-public class ServletModuleImages extends ServletModuleUploadedMedia
-{
-  private static ServletModuleImages instance = new ServletModuleImages();
-  public static ServletModule getInstance() { return instance; }
-
-
-  private ServletModuleImages() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Images");
-    moduleName = "Images";
-
-    try {
-      definition = "image";
-      mainModule = new ModuleImages();
-    }
-    catch (Throwable e) {
-      logger.error("Initialization of ServletModuleImages failed!: " + e.getMessage());
-    }
+public class ServletModuleImages extends ServletModuleUploadedMedia {
+  public ServletModuleImages() {
+    super("Images");
+    
+    definition = "image";
+    mainModule = new ModuleImages();
   }
-
 }
 
index 616f3b6..0a6e2d4 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleLanguage;
 
-/*
- *  ServletModuleLanguage -
- *  Servlet-Interface to Language
- *
- *
- * @author idefix
+/**
+ * ServletModule for managing languages
  */
 
-public class ServletModuleLanguage extends ServletModule
-{
-  private static ServletModuleLanguage instance = new ServletModuleLanguage();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleLanguage() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Language");
-
-    try {
-      definition = "language";
-      mainModule = new ModuleLanguage();
-    }
-    catch (Throwable e) {
-      logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage());
-    }
+public class ServletModuleLanguage extends AdminServletModule {
+  public ServletModuleLanguage() {
+    definition = "language";
+    mainModule = new ModuleLanguage();
   }
 }
\ No newline at end of file
index e5b92b8..3862daf 100755 (executable)
  */
 package mircoders.servlet;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.util.StringRoutines;
 import mircoders.entity.EntityComment;
@@ -47,24 +38,22 @@ import mircoders.global.MirGlobal;
 import mircoders.module.ModuleComment;
 import mircoders.module.ModuleContent;
 
-public class ServletModuleLocalizer extends ServletModule {
-  private static ServletModuleLocalizer instance = new ServletModuleLocalizer();
-  public static ServletModule getInstance() { return instance; }
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 
-  private ModuleContent contentModule;
-  private ModuleComment commentModule;
-  private List administerOperations;
+public class ServletModuleLocalizer extends AdminServletModule {
+  private final ModuleContent contentModule = new ModuleContent();
+  private final ModuleComment commentModule = new ModuleComment();
+  private final List administerOperations = new ArrayList();
 
-  private ServletModuleLocalizer() {
+  public ServletModuleLocalizer() {
     try {
-      logger = new LoggerWrapper("ServletModule.Localizer");
-
-      contentModule = new ModuleContent();
-      commentModule = new ModuleComment();
-
-      administerOperations = new ArrayList();
-
-      String settings[] = configuration.getStringArray("Mir.Localizer.Admin.AdministerOperations");
+      String settings[] = 
+          getConfiguration().getStringArray("Mir.Localizer.Admin.AdministerOperations");
 
       if (settings!=null) {
         for (int i = 0; i < settings.length; i++) {
@@ -73,7 +62,7 @@ public class ServletModuleLocalizer extends ServletModule {
           if (setting.length() > 0) {
             List parts = StringRoutines.splitString(setting, ":");
             if (parts.size() != 2) {
-              logger.error("config error: " + settings[i] + ", 2 parts expected");
+              getLogger().error("config error: " + settings[i] + ", 2 parts expected");
             }
             else {
               Map entry = new HashMap();
@@ -86,7 +75,7 @@ public class ServletModuleLocalizer extends ServletModule {
       }
     }
     catch (Exception e) {
-      logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage());
+      getLogger().error("ServletModuleLocalizer could not be initialized" + e.getMessage(), e);
     }
   }
 
@@ -101,22 +90,20 @@ public class ServletModuleLocalizer extends ServletModule {
    * @param anOperation    The identifier of the operation to perform
    */
   public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) {
-    EntityComment entity;
-
     try {
-      entity = (EntityComment) commentModule.getById(anId);
+      EntityComment entity = (EntityComment) commentModule.getById(anId);
 
       if (entity != null) {
         MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation);
-        logger.info("Operation " + anOperation + " successfully performed on comment " + anId);
+        getLogger().debug("Operation " + anOperation + " successfully performed on comment " + anId);
         logAdminUsage(aRequest, "comment."+anId, "operation " + anOperation + " performed");
       }
       else {
-        logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");
+        getLogger().error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");
       }
     }
     catch (Throwable e) {
-      logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage());
+      getLogger().error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage(), e);
     }
   }
 
@@ -141,7 +128,7 @@ public class ServletModuleLocalizer extends ServletModule {
           List parts = StringRoutines.splitString(operations[i], ";");
 
           if (parts.size() != 2) {
-            logger.error("commentoperationbatch: operation string invalid: " +
+            getLogger().error("commentoperationbatch: operation string invalid: " +
                          operations[i]);
           }
           else {
@@ -165,15 +152,15 @@ public class ServletModuleLocalizer extends ServletModule {
 
       if (entity != null) {
         MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation);
-        logger.info("Operation " + anOperation + " successfully performed on article " + anId);
+        getLogger().info("Operation " + anOperation + " successfully performed on article " + anId);
         logAdminUsage(aRequest, "article." + anId, "operation " + anOperation + " performed");
       }
       else {
-        logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null");
+        getLogger().error("Error while performing " + anOperation + " on article " + anId + ": article is null");
       }
     }
     catch (Throwable e) {
-      logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
+      getLogger().error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
     }
   }
 
@@ -198,7 +185,7 @@ public class ServletModuleLocalizer extends ServletModule {
           List parts = StringRoutines.splitString(operations[i], ";");
 
           if (parts.size() != 2) {
-            logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
+            getLogger().error("articleoperationbatch: operation string invalid: " + operations[i]);
           }
           else {
             String articleIdString = (String) parts.get(0);
index 62ac870..3d3bb6e 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleMediaType;
 
-public class ServletModuleMediaType extends ServletModule
-{
-  private static ServletModuleMediaType instance = new ServletModuleMediaType();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleMediaType() {
-    logger = new LoggerWrapper("ServletModule.MediaType");
-
-    try {
-      definition = "mediaType";
-      mainModule = new ModuleMediaType();
-    }
-    catch (Exception e) {
-      logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
-    }
+public class ServletModuleMediaType extends AdminServletModule {
+  public ServletModuleMediaType() {
+    definition = "mediaType";
+    mainModule = new ModuleMediaType();
   }
 }
index 0054cd9..2ee7615 100755 (executable)
@@ -35,30 +35,14 @@ import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import mir.log.LoggerWrapper;
 import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleMediafolder;
 
-/**
- *
- */
-public class ServletModuleMediafolder extends ServletModule
-{
-  public static ServletModule getInstance() { return instance; }
-  private static ServletModuleMediafolder instance = new ServletModuleMediafolder();
-
-  private ServletModuleMediafolder() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Mediafolder");
-
-    try {
-      definition = "mediaFolder";
-      mainModule = new ModuleMediafolder();
-    }
-    catch (Throwable t) {
-      logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString());
-    }
+public class ServletModuleMediafolder extends AdminServletModule {
+  public ServletModuleMediafolder() {
+    definition = "mediaFolder";
+    mainModule = new ModuleMediafolder();
   }
 
   protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
index 6b76231..8be9d69 100755 (executable)
  */
 package mircoders.servlet;
 
-import java.util.Map;
+import mir.servlet.AdminServletModule;
+import mircoders.module.ModuleMessage;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.util.Map;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mircoders.module.ModuleMessage;
-
-/**
- * Title:       ServletModuleMessage
- * Description:
- * Copyright:   Copyright (c) 2001-2002
- * Company:     mir-coders
- * @author
- * @version 1.0
- */
-
-
-public class ServletModuleMessage extends ServletModule
-{
-  private static ServletModuleMessage instance = new ServletModuleMessage();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleMessage() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Messages");
-
-    try {
-      definition = "internalMessage";
-      mainModule = new ModuleMessage();
-    }
-    catch (Throwable e) {
-      logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());
-
-      throw new ServletModuleFailure(e);
-    }
+public class ServletModuleMessage extends AdminServletModule {
+  public ServletModuleMessage() {
+    definition = "internalMessage";
+    mainModule = new ModuleMessage();
   }
 
   protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
index ea91bf0..e5b1960 100755 (executable)
@@ -33,29 +33,38 @@ package mircoders.servlet;
 import gnu.regexp.RE;
 import gnu.regexp.REMatch;
 import mir.bundle.Bundle;
-import mir.entity.Entity;
 import mir.generator.Generator;
-import mir.log.LoggerWrapper;
 import mir.misc.StringUtil;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.servlet.ServletModuleUserExc;
-import mir.session.*;
-import mir.storage.DatabaseFailure;
-import mir.util.*;
-import mircoders.entity.EntityComment;
+import mir.session.HTTPAdapters;
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionHandler;
+import mir.session.SimpleResponse;
+import mir.util.FileRoutines;
+import mir.util.HTTPParsedRequest;
+import mir.util.HTTPRequestParser;
+import mir.util.StringRoutines;
+import mir.module.ModuleExc;
 import mircoders.entity.EntityContent;
 import mircoders.global.CacheKey;
 import mircoders.global.MirGlobal;
-import mircoders.media.MediaUploadProcessor;
-import mircoders.media.UnsupportedMediaTypeExc;
-import mircoders.module.ModuleComment;
 import mircoders.module.ModuleContent;
 import mircoders.pdf.PDFGenerator;
-import mircoders.search.*;
-import mircoders.storage.*;
-import org.apache.commons.fileupload.FileItem;
+import mircoders.search.AudioSearchTerm;
+import mircoders.search.ContentSearchTerm;
+import mircoders.search.ImagesSearchTerm;
+import mircoders.search.KeywordSearchTerm;
+import mircoders.search.TextSearchTerm;
+import mircoders.search.TopicMatrixSearchTerm;
+import mircoders.search.TopicSearchTerm;
+import mircoders.search.UnIndexedSearchTerm;
+import mircoders.search.VideoSearchTerm;
+import mircoders.storage.DatabaseTopics;
+import mircoders.localizer.MirLocalizerExc;
 import org.apache.commons.net.smtp.SMTPClient;
 import org.apache.commons.net.smtp.SMTPReply;
 import org.apache.lucene.analysis.standard.StandardAnalyzer;
@@ -70,62 +79,39 @@ import org.apache.lucene.store.FSDirectory;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
-import java.io.*;
-import java.util.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
 
 /*
- *  ServletModuleOpenIndy -
- *   is the open-access-servlet, which is responsible for
- *    adding comments to articles &
- *    open-postings to the newswire
- *
- * @author mir-coders group
- * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.18 2005/08/21 17:09:24 zapata Exp $
- *
  */
 
-public class ServletModuleOpenIndy extends ServletModule
-{
-
-  private String        commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
-  private String        postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
+public class ServletModuleOpenIndy extends ServletModule {
   private String        searchResultsTemplate;
   private String        prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
   private ModuleContent contentModule;
-  private ModuleComment commentModule;
-  private String        directOp ="yes";
-  private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
 
-  public  static ServletModule getInstance() {
-    return instance;
-  }
+  public ServletModuleOpenIndy() {
+    searchResultsTemplate = getConfiguration().getString("ServletModule.OpenIndy.SearchResultsTemplate");
+    prepareMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.PrepareMailTemplate");
+    emailAnArticleTemplate = getConfiguration().getString("ServletModule.OpenIndy.MailableArticleTemplate");
+    sentMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.SentMailTemplate");
 
-  private ServletModuleOpenIndy() {
-    super();
-    try {
-      logger = new LoggerWrapper("ServletModule.OpenIndy");
-
-      commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
-      commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
-      commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
-
-      postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
-      postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
-      postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
-
-      searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
-      prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
-      emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
-      sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
-      directOp = configuration.getString("DirectOpenposting").toLowerCase();
-      commentModule = new ModuleComment();
-      mainModule = commentModule;
-      contentModule = new ModuleContent();
-      defaultAction = "defaultAction";
-    }
-    catch (DatabaseFailure e) {
-      logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
-    }
+    contentModule = new ModuleContent();
   }
 
   /**
@@ -145,334 +131,7 @@ public class ServletModuleOpenIndy extends ServletModule
    * @throws ServletModuleFailure
    */
   public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
-  }
-
-  /**
-   *  Method for making a comment
-   */
-  public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(req, res);
-
-      return;
-    }
-
-    String aid = req.getParameter("aid"); // the article id the comment will belong to
-
-    if (aid != null && !aid.equals("")) {
-      try {
-        Map mergeData = new HashMap();
-
-        // onetimepasswd
-        if (MirGlobal.abuse().getOpenPostingPassword()) {
-          String passwd = generateOnetimePassword();
-          HttpSession session = req.getSession(false);
-          session.setAttribute("passwd", passwd);
-          mergeData.put("passwd", passwd);
-        }
-        else {
-          mergeData.put("passwd", null);
-        }
-        mergeData.put("aid", aid);
-
-        Map extraInfo = new HashMap();
-        extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-
-        deliver(req, res, mergeData, extraInfo, commentFormTemplate);
-      }
-      catch (Throwable t) {
-        throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
-      }
-    }
-    else
-      throw new ServletModuleExc("aid not set!");
-  }
-
-  /**
-   *  Method for inserting a comment into the Database and delivering
-   *  the commentDone Page
-   */
-
-  public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(req, res);
-
-      return;
-    }
-
-    String aid = req.getParameter("to_media"); // the article id the comment will belong to
-    if (aid != null && !aid.equals("")) {
-      // ok, collecting data from form
-      try {
-        Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
-
-        //no html in comments(for now)
-        for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
-          String k = (String) i.next();
-          String v = (String) withValues.get(k);
-
-          withValues.put(k, StringUtil.removeHTMLTags(v));
-        }
-        withValues.put("is_published", "1");
-        withValues.put("to_comment_status", "1");
-        withValues.put("is_html", "0");
-
-        //checking the onetimepasswd
-        HttpSession session = req.getSession(false);
-        String sessionPasswd = (String) session.getAttribute("passwd");
-        if (sessionPasswd != null) {
-          String passwd = req.getParameter("passwd");
-          if (passwd == null || passwd.length() == 0) {
-            throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
-          }
-          if (!sessionPasswd.equals(passwd)) {
-            throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
-          }
-          session.invalidate();
-        }
-
-        String id = mainModule.add(withValues);
-
-        SimpleResponse response = new SimpleResponse();
-        response.setResponseGenerator(commentFormDoneTemplate);
-
-        if (id == null) {
-          deliver(req, res, null, null, commentFormDupeTemplate);
-        }
-        else {
-          DatabaseContent.getInstance().setUnproduced("id=" + aid);
-
-          try {
-            EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
-            MirGlobal.localizer().openPostings().afterCommentPosting(comment);
-            MirGlobal.abuse().checkComment(
-                comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
-          }
-          catch (Throwable t) {
-            throw new ServletModuleExc(t.getMessage());
-          }
-        }
-
-        // redirecting to url
-        // should implement back to article
-        deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
-      }
-      catch (Throwable e) {
-        throw new ServletModuleFailure(e);
-      }
-    }
-    else
-      throw new ServletModuleExc("aid not set!");
-
-  }
-
-  /**
-   *  Method for delivering the form-Page for open posting
-   */
-
-  public void addposting(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    try {
-      if (MirGlobal.abuse().getOpenPostingDisabled()) {
-        openPostingDisabled(req, res);
-
-        return;
-      }
-
-      Map mergeData = new HashMap();
-
-      // onetimepasswd
-      if (MirGlobal.abuse().getOpenPostingPassword()) {
-        String passwd = generateOnetimePassword();
-        HttpSession session = req.getSession(false);
-        session.setAttribute("passwd", passwd);
-        mergeData.put("passwd", passwd);
-      }
-      else {
-        mergeData.put("passwd", null);
-      }
-
-      String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
-      String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
-      String numOfMedia = req.getParameter("medianum");
-
-      if (numOfMedia == null || numOfMedia.equals("")) {
-        numOfMedia = defaultMedia;
-      }
-      else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
-        numOfMedia = maxMedia;
-      }
-
-      int mediaNum = Integer.parseInt(numOfMedia);
-      List mediaFields = new ArrayList();
-      for (int i = 0; i < mediaNum; i++) {
-        Integer mNum = new Integer(i + 1);
-        mediaFields.add(mNum.toString());
-      }
-      mergeData.put("medianum", numOfMedia);
-      mergeData.put("mediafields", mediaFields);
-      mergeData.put("to_topic", null);
-
-      Map extraInfo = new HashMap();
-      extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-      extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
-
-      deliver(req, res, mergeData, extraInfo, postingFormTemplate);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   *  Method for inserting an open posting into the Database and delivering
-   *  the postingDone Page
-   */
-
-  public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
-      ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(aRequest, aResponse);
-
-      return;
-    }
-
-    try {
-      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
-          aRequest,
-          configuration.getString("Mir.DefaultEncoding"),
-          configuration.getInt("MaxMediaUploadSize")*1024,
-          configuration.getString("TempDir"));
-
-      Map mergeData = new HashMap();
-
-      HttpSession session = aRequest.getSession(false);
-      String sessionPasswd = (String) session.getAttribute("passwd");
-      if (sessionPasswd != null) {
-        String passwd = parsedRequest.getParameter("passwd");
-
-        if (passwd == null || passwd.length() == 0) {
-          throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
-        }
-        if (!sessionPasswd.equals(passwd)) {
-          throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
-        }
-        session.invalidate();
-      }
-
-      if (((parsedRequest.getParameter("title")).length() == 0) ||
-          ((parsedRequest.getParameter("description")).length() == 0) ||
-          ((parsedRequest.getParameter("content_data")).length() == 0))
-        throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
-
-      List mediaList = new ArrayList();
-      Iterator i = parsedRequest.getFiles().iterator();
-
-      while (i.hasNext()) {
-        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
-        Map mediaValues = new HashMap();
-
-        String suffix = file.getFieldName().substring(5); // media${m}
-        logger.debug("media_title" + suffix);
-        String title = parsedRequest.getParameter("media_title" + suffix);
-
-        mediaValues.put("title", StringUtil.removeHTMLTags(title));
-        mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
-        mediaValues.put("to_publisher", "0");
-        mediaValues.put("is_published", "1");
-        mediaValues.put("to_media_folder", "7");
-
-        mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
-      }
-
-      Map withValues = new HashMap();
-      i = DatabaseContent.getInstance().getFieldNames().iterator();
-      while (i.hasNext()) {
-        String field = (String) i.next();
-        String value = parsedRequest.getParameter(field);
-        if (value!=null)
-          withValues.put(field, value);
-      }
-
-
-      for (i = withValues.keySet().iterator(); i.hasNext(); ) {
-        String k = (String) i.next();
-        String v = (String) withValues.get(k);
-
-        if (k.equals("content_data")) {
-          //this doesn't quite work yet, so for now, all html goes
-          //withValues.put(k,StringUtil.approveHTMLTags(v));
-          withValues.put(k, StringUtil.deleteForbiddenTags(v));
-        }
-        else if (k.equals("description")) {
-          String tmp = StringUtil.deleteForbiddenTags(v);
-          withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
-        }
-        else {
-          withValues.put(k, StringUtil.removeHTMLTags(v));
-        }
-      }
-
-      withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
-      withValues.put("publish_path",
-                     StringUtil.webdbDate2path( (String) withValues.get("date")));
-      withValues.put("is_produced", "0");
-      withValues.put("is_published", "1");
-      if (directOp.equals("yes"))
-        withValues.put("to_article_type", "1");
-
-      withValues.put("to_publisher", "1");
-
-      // inserting  content into database
-      String cid = contentModule.add(withValues);
-      logger.debug("id: " + cid);
-      //insert was not successfull
-      if (cid == null) {
-        deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
-        return;
-      }
-
-      List topics = parsedRequest.getParameterList("to_topic");
-      if (topics.size() > 0) {
-        try {
-          DatabaseContentToTopics.getInstance().setTopics(cid, topics);
-        }
-        catch (Throwable e) {
-          logger.error("setting content_x_topic failed");
-          contentModule.deleteById(cid);
-          throw new ServletModuleFailure(
-              "smod - openindy :: insposting: setting content_x_topic failed: " +
-              e.toString(), e);
-        }
-      }
-
-      i = mediaList.iterator();
-      while (i.hasNext()) {
-        Entity mediaEnt = (Entity) i.next();
-        DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
-      }
-
-      EntityContent article = (EntityContent) contentModule.getById(cid);
-      try {
-        MirGlobal.abuse().checkArticle(
-            article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
-        MirGlobal.localizer().openPostings().afterContentPosting(article);
-      }
-      catch (Throwable t) {
-        logger.error("Error while post-processing article: " + t.getMessage());
-      }
-      deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
-    }
-    catch (Throwable e) {
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      Throwable cause = ExceptionRoutines.traceCauseException(e);
-
-      if (cause instanceof UnsupportedMediaTypeExc) {
-        throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
-      }
-      throw new ServletModuleFailure(e);
-    }
+    deliver(aRequest, aResponse, null, null, getConfiguration().getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
   }
 
   /**
@@ -491,7 +150,7 @@ public class ServletModuleOpenIndy extends ServletModule
     String requestLanguage = aRequest.getParameter("language");
     String sessionLanguage = (String) aSession.getAttribute("language");
     String acceptLanguage = aRequest.getLocale().getLanguage();
-    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
+    String defaultLanguage = getConfiguration().getString("Mir.Login.DefaultLanguage", "en");
 
     String language = requestLanguage;
 
@@ -525,18 +184,23 @@ public class ServletModuleOpenIndy extends ServletModule
     try {
       Request request =
           new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
-              configuration.getString("Mir.DefaultEncoding"),
-              configuration.getInt("MaxMediaUploadSize")*1024,
-              configuration.getString("TempDir")));
+              getConfiguration().getString("Mir.DefaultEncoding"),
+              getConfiguration().getInt("MaxMediaUploadSize")*1024,
+              getConfiguration().getString("TempDir")));
 
       if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
-          !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
+          !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY))) {
         aRequest.getSession().invalidate();
+      }
 
       Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
 
       SimpleResponse response = new SimpleResponse(
-          ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
+          ServletHelper.makeGenerationData(aRequest, aResponse,
+              new Locale[] {
+                  getResponseLocale(aRequest.getSession(), aRequest),
+                  getFallbackLocale(aRequest)
+              },
              "etc/bundles/open"));
 
       response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
@@ -547,8 +211,7 @@ public class ServletModuleOpenIndy extends ServletModule
       ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
     }
     catch (Throwable t) {
-      logger.error(t.toString());
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      getLogger().error(t.toString(), t);
 
       throw new ServletModuleFailure(t);
     }
@@ -557,20 +220,20 @@ public class ServletModuleOpenIndy extends ServletModule
   /**
    * Method for preparing and sending a content as an email message
    */
-  public void mail(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    String aid = req.getParameter("mail_aid");
+  public void mail(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+    String aid = aRequest.getParameter("mail_aid");
     if (aid == null){
-      throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
+      throw new ServletModuleExc("An article id must be specified in requests " +
+          "to email an article.  Something therefore went badly wrong....");
     }
 
-    String to = req.getParameter("mail_to");
-    String from = req.getParameter("mail_from");
-    String from_name = req.getParameter("mail_from_name");
-    String from_ip = req.getRemoteAddr();
-    String comment = req.getParameter("mail_comment");
-    String mail_language = req.getParameter("mail_language");
+    String to = aRequest.getParameter("mail_to");
+    String from = aRequest.getParameter("mail_from");
+    String from_name = aRequest.getParameter("mail_from_name");
+    String from_ip = aRequest.getRemoteAddr();
+    String comment = aRequest.getParameter("mail_comment");
+    String mail_language = aRequest.getParameter("mail_language");
 
     Map mergeData = new HashMap();
     mergeData.put("mail_to",to);
@@ -582,7 +245,7 @@ public class ServletModuleOpenIndy extends ServletModule
 
 
     if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
-      deliver(req, res, mergeData, null, prepareMailTemplate);
+      deliver(aRequest, aResponse, mergeData, null, prepareMailTemplate);
     }
     else {
       //run checks on to and from and mail_language to make sure no monkey business occurring
@@ -601,31 +264,46 @@ public class ServletModuleOpenIndy extends ServletModule
       CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
       String theEmailText;
 
+      EntityContent article;
+      try {
+        article = (EntityContent) contentModule.getById(aid);
+      }
+      catch (ModuleExc e) {
+        throw new ServletModuleExc("Couldn't retrieve article " + aid);
+      }
+
+      if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+        throw new ServletModuleExc("Illegal article");
+      }
+
       if (MirGlobal.mruCache().hasObject(theCacheKey)){
-        logger.info("fetching email text for article "+aid+" from cache");
+        getLogger().info("fetching email text for article "+aid+" from cache");
         theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
       }
       else {
-        EntityContent contentEnt;
+        StringWriter theEMailTextWriter = new StringWriter();
+        PrintWriter dest = new PrintWriter(theEMailTextWriter);
         try {
-          contentEnt = (EntityContent) contentModule.getById(aid);
-          StringWriter theEMailTextWriter = new StringWriter();
-          PrintWriter dest = new PrintWriter(theEMailTextWriter);
           Map articleData = new HashMap();
-          articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
+          try {
+            articleData.put("article",
+                MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", article));
+          }
+          catch (MirLocalizerExc e) {
+            throw new ServletModuleExc("Can't retrieve article " + aid, e);
+          }
           articleData.put("languagecode", mail_language);
-          deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
-          theEmailText = theEMailTextWriter.toString();
-          MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
+          deliver(dest, aRequest, aResponse, articleData, null, emailAnArticleTemplate, mail_language);
         }
-        catch (Throwable e) {
-          throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
+        finally {
+          dest.close();
         }
+        theEmailText = theEMailTextWriter.toString();
+        MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
       }
 
       String content = theEmailText;
 
-
       // add some headers
       content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
       // put in the comment where it should go
@@ -650,7 +328,7 @@ public class ServletModuleOpenIndy extends ServletModule
       SMTPClient client=new SMTPClient();
       try {
         int reply;
-        client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
+        client.connect(getConfiguration().getString("ServletModule.OpenIndy.SMTPServer"));
 
         reply = client.getReplyCode();
 
@@ -659,11 +337,11 @@ public class ServletModuleOpenIndy extends ServletModule
           throw new ServletModuleExc("SMTP server refused connection.");
         }
 
-        client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
+        client.sendSimpleMessage(getConfiguration().getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
 
         client.disconnect();
         //mission accomplished
-        deliver(req, res, mergeData, null, sentMailTemplate);
+        deliver(aRequest, aResponse, mergeData, null, sentMailTemplate);
       }
       catch(IOException e) {
         if(client.isConnected()) {
@@ -731,7 +409,7 @@ public class ServletModuleOpenIndy extends ServletModule
         mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
       }
       catch (Throwable e) {
-        logger.debug("Can't get topics: " + e.toString());
+        getLogger().debug("Can't get topics: " + e.toString());
       }
 
       String searchBackValue = req.getParameter("search_back");
@@ -758,7 +436,7 @@ public class ServletModuleOpenIndy extends ServletModule
           session.setAttribute("positionInResults", new Integer(newPosition));
         }
         else {
-          File indexFile = FileRoutines.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
+          File indexFile = FileRoutines.getAbsoluteOrRelativeFile(getConfiguration().getHome(), getConfiguration().getString("IndexPath"));
 
           String creatorFragment = creatorTerm.makeTerm(req);
           if (creatorFragment != null) {
@@ -769,7 +447,7 @@ public class ServletModuleOpenIndy extends ServletModule
           // the contentTerm uses param "search_boolean" to combine its terms
           String contentFragment = contentTerm.makeTerm(req);
           if (contentFragment != null) {
-            logger.debug("contentFragment: " + contentFragment);
+            getLogger().debug("contentFragment: " + contentFragment);
             queryString = queryString + " +" + contentFragment;
           }
 
@@ -804,22 +482,22 @@ public class ServletModuleOpenIndy extends ServletModule
           else {
             try {
               Searcher searcher = null;
-             
+
               try {
                 searcher = new IndexSearcher(FSDirectory.getDirectory(indexFile,false));
               }
               catch (IOException e) {
-                logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
+                getLogger().debug("Can't open indexPath: " + indexFile.getAbsolutePath());
                 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
               }
 
-              Query query = null;
+              Query query;
               try {
                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
               }
               catch (Exception e) {
                 searcher.close();
-                logger.debug("Query don't parse: " + queryString);
+                getLogger().debug("Query don't parse: " + queryString);
                 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
               }
 
@@ -829,7 +507,7 @@ public class ServletModuleOpenIndy extends ServletModule
               }
               catch (IOException e) {
                 searcher.close();
-                logger.debug("Can't get hits: " + e.toString());
+                getLogger().debug("Can't get hits: " + e.toString());
                 throw new ServletModuleExc("Problem getting hits!");
               }
 
@@ -889,7 +567,7 @@ public class ServletModuleOpenIndy extends ServletModule
                 searcher.close();
               }
               catch (IOException e) {
-                logger.debug("Can't close searcher: " + e.toString());
+                getLogger().debug("Can't close searcher: " + e.toString());
                 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
               }
 
@@ -903,7 +581,7 @@ public class ServletModuleOpenIndy extends ServletModule
 
             }
             catch (IOException e) {
-              logger.debug("Can't close searcher: " + e.toString());
+              getLogger().debug("Can't close searcher: " + e.toString());
               throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
             }
           }
@@ -956,7 +634,7 @@ public class ServletModuleOpenIndy extends ServletModule
         }
       }
       catch (Throwable e) {
-        logger.error("Can't iterate over hits: " + e.toString());
+        getLogger().error("Can't iterate over hits: " + e.toString());
 
         throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
       }
@@ -976,17 +654,17 @@ public class ServletModuleOpenIndy extends ServletModule
 
   public void getpdf(HttpServletRequest req, HttpServletResponse res)
       throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+
     long starttime = System.currentTimeMillis();
+
     String ID_REQUEST_PARAM = "id";
     int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
     try {
       String idParam = req.getParameter(ID_REQUEST_PARAM);
       if (idParam != null) {
-
         RE re = new RE("[0-9]+");
 
         REMatch[] idMatches = re.getAllMatches(idParam);
-
         String cacheSelector = "";
 
         for (int i = 0; i < idMatches.length; i++) {
@@ -1000,11 +678,11 @@ public class ServletModuleOpenIndy extends ServletModule
         byte[] thePDF;
 
         if (MirGlobal.mruCache().hasObject(theCacheKey)) {
-          logger.info("fetching pdf from cache");
+          getLogger().debug("fetching pdf from cache");
           thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
         }
         else {
-          logger.info("generating pdf and caching it");
+          getLogger().debug("generating pdf and caching it");
           ByteArrayOutputStream out = new ByteArrayOutputStream();
           PDFGenerator pdfMaker = new PDFGenerator(out);
 
@@ -1014,6 +692,8 @@ public class ServletModuleOpenIndy extends ServletModule
               REMatch aMatch = idMatches[i];
               String id = aMatch.toString();
               EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+
+
               pdfMaker.addIndexItem(contentEnt);
             }
           }
@@ -1021,9 +701,13 @@ public class ServletModuleOpenIndy extends ServletModule
           for (int i = 0; i < idMatches.length; i++) {
             REMatch aMatch = idMatches[i];
             String id = aMatch.toString();
-            EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+            EntityContent article = (EntityContent) contentModule.getById(id);
+
+            if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+              throw new ServletModuleExc("Illegal article");
+            }
 
-            pdfMaker.add(contentEnt);
+            pdfMaker.add(article);
           }
 
           pdfMaker.stop();
@@ -1038,7 +722,7 @@ public class ServletModuleOpenIndy extends ServletModule
         res.getOutputStream().write(thePDF);
         res.getOutputStream().flush();
         String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
-        logger.info("pdf retireval took " + elapsedtime + " milliseconds");
+        getLogger().info("pdf retireval took " + elapsedtime + " milliseconds");
 
       }
       else {
@@ -1046,7 +730,8 @@ public class ServletModuleOpenIndy extends ServletModule
       }
     }
     catch (Throwable t) {
-      logger.error(t.toString());
+      getLogger().error(t.toString());
+
       throw new ServletModuleFailure(t);
     }
   }
@@ -1085,12 +770,12 @@ public class ServletModuleOpenIndy extends ServletModule
 
 
       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
-      generator.generate(anOutputWriter, responseData, logger);
+      generator.generate(anOutputWriter, responseData, getLogger());
 
       anOutputWriter.close();
     }
     catch (Throwable e) {
-      logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+      getLogger().error("Error while generating " + aGenerator + ": " + e.getMessage());
 
       throw new ServletModuleFailure(e);
     }
@@ -1105,12 +790,12 @@ public class ServletModuleOpenIndy extends ServletModule
 
 
       Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
-      generator.generate(anOutputWriter, responseData, logger);
+      generator.generate(anOutputWriter, responseData, getLogger());
 
       anOutputWriter.close();
     }
     catch (Throwable e) {
-      logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+      getLogger().error("Error while generating " + aGenerator + ": " + e.getMessage());
 
       throw new ServletModuleFailure(e);
     }
@@ -1119,13 +804,13 @@ public class ServletModuleOpenIndy extends ServletModule
 
   public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
     try {
-      logger.error("Error during open action", anException);
+      getLogger().error("Error during open action", anException);
       Map data = new HashMap();
 
       data.put("errorstring", anException.getMessage());
       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
 
-      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
+      deliver(out, aRequest, aResponse, data, null, getConfiguration().getString("ServletModule.OpenIndy.ErrorTemplate"));
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
@@ -1135,7 +820,7 @@ public class ServletModuleOpenIndy extends ServletModule
   public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
                                PrintWriter out, ServletModuleUserExc anException) {
     try {
-      logger.warn("user error: " + anException.getMessage());
+      getLogger().warn("user error: " + anException.getMessage());
       Map data = new HashMap();
 
       Bundle bundle =
@@ -1144,7 +829,7 @@ public class ServletModuleOpenIndy extends ServletModule
       data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
       data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
 
-      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
+      deliver(out, aRequest, aResponse, data, null, getConfiguration().getString("ServletModule.OpenIndy.UserErrorTemplate"));
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
index d447c09..6a65fca 100755 (executable)
 
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseOther;
 
 /**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author the mir coders
- * @version 1.0
+ * Admin ServletModule to manage "other" (i.e. non-audio, video or image) media uploads
  */
 
 public class ServletModuleOtherMedia extends ServletModuleUploadedMedia {
-  private static ServletModuleOtherMedia instance = new ServletModuleOtherMedia();
-
-  public static ServletModule getInstance() {
-    return instance;
-  }
-
-  private ServletModuleOtherMedia() {
-    super();
-    logger = new LoggerWrapper("ServletModule.OtherMedia");
-    moduleName = "OtherMedia";
+  public ServletModuleOtherMedia() {
+    super("OtherMedia");
 
-    try {
-      definition = "otherMedia";
-      mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance());
-    }
-    catch (Throwable e) {
-      logger.error("servletmodule otherMedia could not be initialized: " + e.getMessage());
-    }
+    definition = "otherMedia";
+    mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance());
   }
 }
 
index c5b02dc..3d76981 100755 (executable)
  */
 package mircoders.servlet;
 
+import mir.generator.Generator;
+import mir.producer.ProducerFactory;
+import mir.servlet.AdminServletModule;
+import mir.servlet.ServletModuleFailure;
+import mir.util.HTTPRequestParser;
+import mircoders.global.MirGlobal;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -38,30 +47,9 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.generator.Generator;
-import mir.log.LoggerWrapper;
-import mir.producer.ProducerFactory;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mir.util.HTTPRequestParser;
-import mircoders.global.MirGlobal;
-
-public class ServletModuleProducer extends ServletModule
-{
-  private static ServletModuleProducer instance = new ServletModuleProducer();
-  public static ServletModule getInstance() { return instance; }
-
-  Object comments;
-  int totalNrComments;
-
-
-  private ServletModuleProducer() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Producer");
-    defaultAction="showProducerQueueStatus";
+public class ServletModuleProducer extends AdminServletModule {
+  public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    showProducerQueueStatus(aRequest, aResponse);
   }
 
   /**
@@ -70,18 +58,14 @@ public class ServletModuleProducer extends ServletModule
    * @param aResponse
    */
   public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    Map generationData;
-    Generator generator;
-    List producersData;
-
     try {
       // TODO: use ServletHelper
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");
+      Generator generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");
 
-      generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      Map generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
       generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus");
 
-      producersData = new ArrayList();
+      List producersData = new ArrayList();
       Iterator i = MirGlobal.getProducerEngine().getFactories().iterator();
       while (i.hasNext()) {
         ProducerFactory factory = (ProducerFactory) i.next();
@@ -106,7 +90,7 @@ public class ServletModuleProducer extends ServletModule
       generationData.put("producers", producersData);
 
       generationData.put("queue", MirGlobal.getProducerEngine().getQueueStatus());
-      generator.generate(aResponse.getWriter(), generationData, logger);
+      generator.generate(aResponse.getWriter(), generationData, getLogger());
     }
     catch (Throwable t) {
       throw new ServletModuleFailure(t);
@@ -118,25 +102,28 @@ public class ServletModuleProducer extends ServletModule
    * The output therefore is very simple.
    */
   public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    PrintWriter out;
     try {
-      PrintWriter out = aResponse.getWriter();
-
-      if (aRequest.getParameter("producer")!=null) {
-        String producerParam = aRequest.getParameter("producer");
-        String verbParam = aRequest.getParameter("verb");
-
-        try {
-          MirGlobal.getProducerEngine().addJob(producerParam, verbParam);
-          out.println("job added");
-        }
-        catch (Throwable t) {
-          out.println("Can't add job: " + t.getMessage());
-        }
-      }
+      out = aResponse.getWriter();
     }
     catch (IOException e) {
       throw new ServletModuleFailure(e);
     }
+
+    if (aRequest.getParameter("producer")!=null) {
+      String producerParam = aRequest.getParameter("producer");
+      String verbParam = aRequest.getParameter("verb");
+
+      try {
+        MirGlobal.getProducerEngine().addJob(producerParam, verbParam);
+
+        out.println("job added");
+      }
+      catch (Throwable t) {
+
+        out.println("Can't add job: " + t.getMessage());
+      }
+    }
   }
 
   /**
index e7700d0..4b1fa1b 100755 (executable)
 
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mircoders.module.ModuleTopics;
 
 /**
- *
+ * Admin ServletModule for managing topics
  */
-
-public class ServletModuleTopics extends ServletModule
-{
-  private static ServletModuleTopics instance = new ServletModuleTopics();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleTopics() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Topics");
-
-    try {
-      definition = "topic";
-      mainModule = new ModuleTopics();
-    }
-    catch (Throwable e) {
-      logger.error("Initialization of ServletModuleTopics failed!: " + e.getMessage());
-    }
+public class ServletModuleTopics extends AdminServletModule {
+  public ServletModuleTopics() {
+    definition = "topic";
+    mainModule = new ModuleTopics();
   }
 }
\ No newline at end of file
index d40eb37..87c321c 100755 (executable)
@@ -34,14 +34,19 @@ import mir.config.MirPropertiesConfiguration;
 import mir.entity.Entity;
 import mir.entity.adapter.EntityAdapter;
 import mir.entity.adapter.EntityAdapterEngine;
-import mir.log.LoggerWrapper;
 import mir.media.MediaHandler;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.servlet.ServletModuleUserExc;
 import mir.session.UploadedFile;
-import mir.util.*;
+import mir.session.CommonsUploadedFileAdapter;
+import mir.util.ExceptionRoutines;
+import mir.util.HTTPParsedRequest;
+import mir.util.HTTPRequestParser;
+import mir.util.JDBCStringRoutines;
+import mir.util.SQLQueryBuilder;
+import mir.util.URLBuilder;
 import mircoders.entity.EntityComment;
 import mircoders.entity.EntityContent;
 import mircoders.entity.EntityUploadedMedia;
@@ -57,30 +62,19 @@ import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.InputStream;
-import java.util.*;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author the mir coders
- * @version 1.0
- */
-
-public abstract class ServletModuleUploadedMedia extends ServletModule {
-  protected String moduleName = "UploadedMedia";
-
-  public static ServletModule getInstance() {
-    return null;
-  }
-
-  public ServletModuleUploadedMedia() {
-    super();
-
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+public abstract class ServletModuleUploadedMedia extends AdminServletModule {
+  private String moduleName;
+
+  protected ServletModuleUploadedMedia(String aModuleName) {
+    moduleName = aModuleName;
     definition = "uploadedMedia";
-    logger = new LoggerWrapper("ServletModule.UploadedMedia");
   }
 
   public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
@@ -88,9 +82,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
 
     try {
       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
-          configuration.getString("Mir.DefaultEncoding"),
-          configuration.getInt("MaxMediaUploadSize")*1024,
-          configuration.getString("TempDir"));
+          getConfiguration().getString("Mir.DefaultEncoding"),
+          getConfiguration().getInt("MaxMediaUploadSize")*1024,
+          getConfiguration().getString("TempDir"));
 
       Map mediaValues = new HashMap();
 
@@ -108,7 +102,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
 
       i = parsedRequest.getFiles().iterator();
       while (i.hasNext()) {
-        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
+        UploadedFile file = new CommonsUploadedFileAdapter((FileItem) i.next());
 
         String suffix = file.getFieldName().substring(5);
         mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
@@ -120,19 +114,19 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
       String commentid = parsedRequest.getParameter("commentid");
 
       if (articleid!=null) {
-        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
+        EntityContent entContent = (EntityContent)
+            DatabaseContent.getInstance().selectById(articleid);
 
         i = mediaList.iterator();
 
         while (i.hasNext()) {
-          String id = ((EntityUploadedMedia) i.next()).getId();
+          String id = ((Entity) i.next()).getId();
 
           entContent.attach(id);
           logAdminUsage(aRequest, id, "object attached to article " + articleid);
         }
 
-        (ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid);
-
+        ServletHelper.redirect(aResponse, "module=content&do=edit&id=" + articleid);
 
         return;
       }
@@ -150,7 +144,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
           logAdminUsage(aRequest, id, "object attached to comment " + commentid);
         }
 
-        (ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid);
+        ServletHelper.redirect(aResponse, "module=comment&do=edit&id=" + commentid);
 
         return;
       }
@@ -173,26 +167,29 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
 
     try {
       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
-          configuration.getString("Mir.DefaultEncoding"),
-          configuration.getInt("MaxMediaUploadSize")*1024,
-          configuration.getString("TempDir"));
+          getConfiguration().getString("Mir.DefaultEncoding"),
+          getConfiguration().getInt("MaxMediaUploadSize")*1024,
+          getConfiguration().getString("TempDir"));
+
       Map mediaValues = new HashMap();
 
       Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
       while (i.hasNext()) {
         String field = (String) i.next();
         String value = parsedRequest.getParameter(field);
-        if (value!=null)
+        if (value!=null) {
           mediaValues.put(field, value);
+        }
       }
 
       mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
       mediaValues.put("is_produced", "0");
-      if (!mediaValues.containsKey("is_published"))
+      if (!mediaValues.containsKey("is_published")) {
         mediaValues.put("is_published", "0");
+      }
 
       String id = mainModule.set(mediaValues);
-      logger.debug("update: media ID = " + id);
+      getLogger().debug("update: media ID = " + id);
       logAdminUsage(aRequest, id, "object modified");
 
       editUploadedMediaObject(id, aRequest, aResponse);
@@ -248,7 +245,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
 
     try {
       List list =
-         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
+         EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
 
       urlBuilder.setValue("module", moduleName);
       urlBuilder.setValue("do", "list");
@@ -337,7 +334,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
 
       int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1);
-      int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);
+      int maxNrMedia = getConfiguration().getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);
 
       List fields = mainModule.getStorageObject().getFieldNames();
       Map media = new HashMap();
@@ -382,11 +379,11 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
   }
 
   private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
-    if (idParam != null && !idParam.equals("")) {
+    if (idParam != null && !"".equals(idParam)) {
       try {
         Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
         EntityAdapter object =
-            model.makeEntityAdapter(definition, mainModule.getById(idParam));
+            getModel().makeEntityAdapter(definition, mainModule.getById(idParam));
         HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
         responseData.put("uploadedmedia", object);
         responseData.put("new", Boolean.FALSE);
@@ -442,7 +439,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
         throw new ServletModuleFailure(e);
       }
     }
-    else logger.error("id not specified.");
+    else {
+      getLogger().error("id not specified.");
+    }
     // no exception allowed
   }
 
@@ -489,15 +488,18 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
         }
       }
       catch (Throwable e) {
-        logger.error("getIcon: " + e.toString());
+        getLogger().error("getIcon: " + e.toString());
       }
     }
-    else logger.error("getIcon: id not specified.");
+    else {
+      getLogger().error("getIcon: id not specified.");
+    }
   }
 
   protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure {
     try {
-      aTarget.put("mediafolders", EntityAdapterEngine.retrieveAdapterList(model, "mediaFolder", "", "", -1, 0));
+      aTarget.put("mediafolders",
+          EntityAdapterEngine.retrieveAdapterList(getModel(), "mediaFolder", "", "", -1, 0));
     }
     catch (Throwable t) {
       throw new ServletModuleFailure(t);
@@ -509,7 +511,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
     if (idParam!=null && !idParam.equals("")) {
       try {
         // TODO rewrite as relational sql
-        ServletModuleContent.getInstance().returnList(
+        ServletHelper.getServletModuleContent().returnList(
             aRequest,
             aResponse,
             "exists (select * from content_x_media where content_id=content.id and media_id='" +
@@ -519,7 +521,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
         throw new ServletModuleFailure(t);
       }
     }
-    else logger.error("showarticles: id not specified.");
+    else {
+      getLogger().error("showarticles: id not specified.");
+    }
   }
 
   public void showcomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
@@ -528,7 +532,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
     if (idParam!=null && !idParam.equals("")) {
       try {
         // TODO rewrite as relational sql
-        ServletModuleComment.getInstance().returnList(
+        ServletHelper.getServletModuleComment().returnList(
             aRequest,
             aResponse,
             "exists (select * from comment_x_media where comment_id=comment.id and media_id='" + JDBCStringRoutines.escapeStringLiteral( idParam ) + "')", "", 0);
@@ -537,6 +541,8 @@ public abstract class ServletModuleUploadedMedia extends ServletModule {
         throw new ServletModuleFailure(t);
       }
     }
-    else logger.error("showcomments: id not specified.");
+    else {
+      getLogger().error("showcomments: id not specified.");
+    }
   }
 }
\ No newline at end of file
index 4d29ed4..6191551 100755 (executable)
@@ -32,8 +32,7 @@ package mircoders.servlet;
 
 import mir.entity.adapter.EntityAdapterEngine;
 import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.servlet.ServletModuleUserExc;
@@ -46,38 +45,30 @@ import mircoders.storage.DatabaseUsers;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.util.*;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
 
 /**
  *
  *
  */
-public class ServletModuleUsers extends ServletModule
-{
-  private static ServletModuleUsers instance = new ServletModuleUsers();
-  public static ServletModule getInstance() { return instance; }
-  protected ModuleUsers usersModule;
+public class ServletModuleUsers extends AdminServletModule {
+  protected ModuleUsers usersModule = new ModuleUsers();
 
-  private ServletModuleUsers() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Users");
-
-    try {
-      definition = "user";
-      usersModule = new ModuleUsers();
-      mainModule = usersModule;
-    }
-    catch (Throwable e) {
-      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());
-    }
+  public ServletModuleUsers() {
+    definition = "user";
+    mainModule = usersModule;
   }
 
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
     String idParam = aRequest.getParameter("id");
 
-    if (idParam == null)
+    if (idParam == null) {
       throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
+    }
 
     try {
       EntityUsers user = (EntityUsers) mainModule.getById(idParam);
@@ -247,7 +238,8 @@ public class ServletModuleUsers extends ServletModule
       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
 
       List list =
-         EntityAdapterEngine.retrieveAdapterList(model, definition, "", "login", nrEntitiesPerListPage, anOffset);
+         EntityAdapterEngine.retrieveAdapterList(getModel(), definition,
+             "", "login", nrEntitiesPerListPage, anOffset);
 
       responseData.put("nexturl", null);
       responseData.put("prevurl", null);
@@ -256,11 +248,11 @@ public class ServletModuleUsers extends ServletModule
       urlBuilder.setValue("do", "list");
 
       urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("offset" , Integer.toString(anOffset));
       responseData.put("thisurl" , urlBuilder.getQuery());
 
       if (list.size()>=nrEntitiesPerListPage) {
-        urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
         responseData.put("nexturl" , urlBuilder.getQuery());
       }
 
index 5344273..bd95b01 100755 (executable)
 
 package mircoders.servlet;
 
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseVideo;
 
 /**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * Admin ServletModule for managing video uploads
  */
 
 public class ServletModuleVideo extends ServletModuleUploadedMedia {
-  private static ServletModuleVideo instance = new ServletModuleVideo();
-
-  public static ServletModule getInstance() {
-    return instance;
-  }
-
   private ServletModuleVideo() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Video");
-
-    moduleName = "Video";
+    super("Video");
 
-    try {
-      definition = "video";
-      mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance());
-    }
-    catch (Throwable e) {
-      logger.error("servletmodule video could not be initialized: " + e.getMessage());
-    }
+    definition = "video";
+    mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance());
   }
 }
\ No newline at end of file