some cosmetic change, organzied imports, and made some accesses in a static way
authorrk <rk>
Thu, 23 Oct 2003 14:55:25 +0000 (14:55 +0000)
committerrk <rk>
Thu, 23 Oct 2003 14:55:25 +0000 (14:55 +0000)
76 files changed:
source/Mir.java
source/OpenMir.java
source/mir/entity/Entity.java
source/mir/entity/adapter/EntityAdapterEngine.java
source/mir/generator/FreemarkerGenerator.java
source/mir/generator/Generator.java
source/mir/generator/GeneratorHelper.java
source/mir/misc/StringUtil.java
source/mir/producer/EntityDeletingProducerNode.java
source/mir/producer/EntityModifyingProducerNode.java
source/mir/producer/GeneratingProducerNode.java
source/mir/producer/ListEnumeratingProducerNode.java
source/mir/producer/RDFAggregatorProducerNode.java
source/mir/producer/RSSProducerNode.java
source/mir/producer/reader/ProducerConfigReader.java
source/mir/rss/RSS091Reader.java
source/mir/rss/RSSAggregator.java
source/mir/rss/RSSTest.java
source/mir/servlet/AbstractServlet.java
source/mir/servlet/ServletModule.java
source/mir/session/HTTPAdapters.java
source/mir/session/ValidationHelper.java
source/mir/storage/Database.java
source/mir/util/DateTimeFunctions.java
source/mir/util/FileFunctions.java
source/mir/util/GeneratorHTMLFunctions.java
source/mir/util/HTTPRequestParser.java
source/mir/util/JDBCStringRoutines.java
source/mir/util/ParameterExpander.java
source/mir/util/StringRoutines.java
source/mir/util/StructuredContentParser.java
source/mircoders/entity/EntityImages.java
source/mircoders/global/Abuse.java
source/mircoders/global/MirGlobal.java
source/mircoders/localizer/MirCachingLocalizerDecorator.java
source/mircoders/localizer/MirOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java
source/mircoders/localizer/basic/MirBasicAntiAbuseFilterTypes.java
source/mircoders/localizer/basic/MirBasicArticlePostingHandler.java
source/mircoders/localizer/basic/MirBasicEmailArticleHandler.java
source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java
source/mircoders/localizer/basic/MirBasicProducerLocalizer.java
source/mircoders/media/ImageProcessor.java
source/mircoders/media/MediaHandlerGeneric.java
source/mircoders/media/MediaHandlerImages.java
source/mircoders/media/MediaHandlerImagesExtern.java
source/mircoders/module/ModuleTopics.java
source/mircoders/pdf/PDFGenerator.java
source/mircoders/producer/IndexingProducerNode.java
source/mircoders/producer/PDFPreFormattingProducerNode.java
source/mircoders/servlet/ServletHelper.java
source/mircoders/servlet/ServletModuleAbuse.java
source/mircoders/servlet/ServletModuleAdmin.java
source/mircoders/servlet/ServletModuleAudio.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/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
source/mircoders/storage/DatabaseImages.java
source/mircoders/storage/DatabaseVideo.java
source/tool/BundleTool.java
source/tool/ConfigTool.java

index 3c42ca6..7043046 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-import java.io.IOException;\r
-import java.lang.reflect.Method;\r
-import java.util.*;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-import javax.servlet.*;\r
-import javax.servlet.ServletException;\r
-import javax.servlet.UnavailableException;\r
-import javax.servlet.http.*;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import org.apache.struts.util.MessageResources;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.servlet.AbstractServlet;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleDispatch;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.util.ExceptionFunctions;\r
-import mir.util.StringRoutines;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleMessage;\r
-import mircoders.module.ModuleUsers;\r
-import mircoders.servlet.ServletHelper;\r
-import mircoders.storage.DatabaseUsers;\r
-\r
-\r
-\r
-\r
-/**\r
- * Mir.java - main servlet, that dispatches to servletmodules\r
- *\r
- * @author $Author: zapata $\r
- * @version $Id: Mir.java,v 1.49.2.7 2003/09/04 03:11:42 zapata Exp $\r
- *\r
- */\r
-public class Mir extends AbstractServlet {\r
-  private static ModuleUsers usersModule = null;\r
-  private static ModuleMessage messageModule = null;\r
-  private final static Map servletModuleInstanceHash = new HashMap();\r
-  private static Locale fallbackLocale = null;\r
-\r
-  private static List loginLanguages = null;\r
-\r
-  protected List getLoginLanguages() throws ServletException {\r
-    synchronized (Mir.class) {\r
-      try {\r
-        if (loginLanguages == null) {\r
-          MessageResources messageResources =\r
-            MessageResources.getMessageResources("bundles.adminlocal");\r
-          MessageResources messageResources2 =\r
-            MessageResources.getMessageResources("bundles.admin");\r
-\r
-          List languages =\r
-            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");\r
-\r
-          loginLanguages = new Vector();\r
-\r
-          Iterator i = languages.iterator();\r
-\r
-          while (i.hasNext()) {\r
-            String code = (String) i.next();\r
-            Locale locale = new Locale(code, "");\r
-            String name = messageResources.getMessage(locale, "languagename");\r
-\r
-            if (name == null) {\r
-              name = messageResources2.getMessage(locale, "languagename");\r
-            }\r
-\r
-            if (name == null) {\r
-              name = code;\r
-            }\r
-\r
-            Map record = new HashMap();\r
-            record.put("name", name);\r
-            record.put("code", code);\r
-            loginLanguages.add(record);\r
-          }\r
-        }\r
-\r
-        return loginLanguages;\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletException(t.getMessage());\r
-      }\r
-    }\r
-  }\r
-\r
-  public void init(ServletConfig config) throws ServletException {\r
-    super.init(config);\r
-\r
-    usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
-  }\r
-\r
-  protected String getDefaultLanguage(HttpServletRequest aRequest) {\r
-    String defaultlanguage =\r
-      MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");\r
-\r
-    if (defaultlanguage.length() == 0) {\r
-      Locale locale = aRequest.getLocale();\r
-      defaultlanguage = locale.getLanguage();\r
-    }\r
-\r
-    return defaultlanguage;\r
-  }\r
-\r
-  protected synchronized Locale getFallbackLocale() throws ServletException {\r
-    try {\r
-      if (fallbackLocale == null) {\r
-        fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletException(t.getMessage());\r
-    }\r
-\r
-    return fallbackLocale;\r
-  }\r
-\r
-  public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {\r
-    try {\r
-      EntityUsers user = ServletHelper.getUser(aRequest);\r
-\r
-      String username = aRequest.getParameter("login");\r
-      String password = aRequest.getParameter("password");\r
-\r
-      if (username != null && password != null) {\r
-        user = usersModule.getUserForLogin(username, password);\r
-\r
-        if (user!=null) {\r
-          ServletHelper.setUser(aRequest, user);\r
-          aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username));\r
-        }\r
-      }\r
-\r
-      return user;\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace();\r
-\r
-      throw new ServletException(t.toString());\r
-    }\r
-  }\r
-\r
-  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {\r
-    try {\r
-      long startTime = System.currentTimeMillis();\r
-      long sessionConnectTime = 0;\r
-\r
-      HttpSession session = aRequest.getSession(true);\r
-      setNoCaching(aResponse);\r
-      Locale locale = new Locale(getDefaultLanguage(aRequest), "");\r
-      aResponse.setContentType("text/html; charset=" +\r
-                               configuration.\r
-                               getString("Mir.DefaultHTMLCharset", "UTF-8"));\r
-\r
-      EntityUsers userEntity = checkCredentials(aRequest);\r
-\r
-      if (userEntity == null) {\r
-        String queryString = aRequest.getQueryString();\r
-\r
-        if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&\r
-             (aRequest.getParameter("module")==null ||\r
-              (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {\r
-          session.setAttribute("login.target", queryString);\r
-        }\r
-\r
-        _sendLoginPage(aResponse, aRequest);\r
-      }\r
-      else {\r
-        String moduleName = aRequest.getParameter("module");\r
-        checkLanguage(session, aRequest);\r
-\r
-        if ( ( (moduleName == null) || moduleName.equals(""))) {\r
-          moduleName="Admin";\r
-        }\r
-\r
-\r
-        if (moduleName.equals("login")) {\r
-          String target = (String) session.getAttribute("login.target");\r
-\r
-          if (target != null) {\r
-            ServletHelper.redirect(aResponse, target);\r
-          }\r
-          else {\r
-            ServletHelper.redirect(aResponse, "");\r
-          }\r
-        }\r
-        else if (moduleName.equals("logout")) {\r
-          logger.info(userEntity.getValue("login") + " has logged out");\r
-          session.invalidate();\r
-          _sendLoginPage(aResponse, aRequest);\r
-          return;\r
-        }\r
-        else {\r
-          try {\r
-            ServletModule servletModule = getServletModuleForName(moduleName);\r
-            ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);\r
-\r
-            sessionConnectTime = System.currentTimeMillis() - startTime;\r
-            logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");\r
-          }\r
-          catch (Throwable e) {\r
-            Throwable cause = ExceptionFunctions.traceCauseException(e);\r
-\r
-            if (cause instanceof ServletModuleUserExc)\r
-              handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);\r
-            else\r
-              handleError(aRequest, aResponse, cause);\r
-          }\r
-\r
-          if (aRequest.getParameter("killsession")!=null)\r
-            aRequest.getSession().invalidate();\r
-        }\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace();\r
-\r
-      throw new ServletException(t.toString());\r
-    }\r
-  }\r
-\r
-  /**\r
-   * caching routine to get a module for a module name\r
-   *\r
-   * @param moduleName the module name\r
-   * @return the requested module\r
-   * @throws ServletModuleExc\r
-   */\r
-\r
-  private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {\r
-    // Instance in Map ?\r
-    if (!servletModuleInstanceHash.containsKey(moduleName)) {\r
-      // was not found in hash...\r
-      try {\r
-        Class theServletModuleClass = null;\r
-\r
-        try {\r
-          // first we try to get ServletModule from stern.che3.servlet\r
-          theServletModuleClass =\r
-            Class.forName("mircoders.servlet.ServletModule" + moduleName);\r
-        }\r
-        catch (ClassNotFoundException e) {\r
-          // on failure, we try to get it from lib-layer\r
-          theServletModuleClass =\r
-            Class.forName("mir.servlet.ServletModule" + moduleName);\r
-        }\r
-\r
-        Method m = theServletModuleClass.getMethod("getInstance", null);\r
-        ServletModule smod = (ServletModule) m.invoke(null, null);\r
-\r
-        // we put it into map for further reference\r
-        servletModuleInstanceHash.put(moduleName, smod);\r
-\r
-        return smod;\r
-      }\r
-      catch (Exception e) {\r
-        throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());\r
-      }\r
-    }\r
-    else {\r
-      return (ServletModule) servletModuleInstanceHash.get(moduleName);\r
-    }\r
-  }\r
-\r
-  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {\r
-    try {\r
-      logger.info("user error: " + anException.getMessage());\r
-\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
-\r
-      MessageResources messages = MessageResources.getMessageResources("bundles.admin");\r
-      responseData.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));\r
-      responseData.put("date", new GregorianCalendar().getTime());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Error handling user error" + e.toString());\r
-    }\r
-  }\r
-\r
-  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {\r
-    try {\r
-      logger.error("error: " + anException);\r
-\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
-\r
-      responseData.put("errorstring", anException.toString());\r
-      responseData.put("date", new GregorianCalendar().getTime());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Error handling error: " + e.toString());\r
-    }\r
-  }\r
-\r
-  // Redirect-methods\r
-  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {\r
-    String loginTemplate = configuration.getString("Mir.LoginTemplate");\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
-\r
-      responseData.put("defaultlanguage", getDefaultLanguage(aRequest));\r
-      responseData.put("languages", getLoginLanguages());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      handleError(aRequest, aResponse, e);\r
-    }\r
-  }\r
-\r
-  public String getServletInfo() {\r
-    return "Mir " + configuration.getString("Mir.Version");\r
-  }\r
-\r
-  private class SessionTracker implements HttpSessionBindingListener {\r
-    private String name;\r
-\r
-    public SessionTracker(String aUserName) {\r
-      name = aUserName;\r
-    }\r
-\r
-    public void valueBound(HttpSessionBindingEvent anEvent) {\r
-      MirGlobal.registerLogin(name);\r
-    }\r
-\r
-    public void valueUnbound(HttpSessionBindingEvent anEvent) {\r
-      MirGlobal.registerLogout(name);\r
-    }\r
-  }\r
-}\r
+/*
+ * 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.
+ */
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.UnavailableException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.servlet.AbstractServlet;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleDispatch;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.ExceptionFunctions;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleMessage;
+import mircoders.module.ModuleUsers;
+import mircoders.servlet.ServletHelper;
+import mircoders.storage.DatabaseUsers;
+
+import org.apache.struts.util.MessageResources;
+
+
+
+
+/**
+ * Mir.java - main servlet, that dispatches to servletmodules
+ *
+ * @author $Author: rk $
+ * @version $Id: Mir.java,v 1.49.2.8 2003/10/23 14:55:26 rk Exp $
+ *
+ */
+public class Mir extends AbstractServlet {
+  private static ModuleUsers usersModule = null;
+  private static ModuleMessage messageModule = null;
+  private final static Map servletModuleInstanceHash = new HashMap();
+  private static Locale fallbackLocale = null;
+
+  private static List loginLanguages = null;
+
+  protected List getLoginLanguages() throws ServletException {
+    synchronized (Mir.class) {
+      try {
+        if (loginLanguages == null) {
+          MessageResources messageResources =
+            MessageResources.getMessageResources("bundles.adminlocal");
+          MessageResources messageResources2 =
+            MessageResources.getMessageResources("bundles.admin");
+
+          List languages =
+            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
+
+          loginLanguages = new Vector();
+
+          Iterator i = languages.iterator();
+
+          while (i.hasNext()) {
+            String code = (String) i.next();
+            Locale locale = new Locale(code, "");
+            String name = messageResources.getMessage(locale, "languagename");
+
+            if (name == null) {
+              name = messageResources2.getMessage(locale, "languagename");
+            }
+
+            if (name == null) {
+              name = code;
+            }
+
+            Map record = new HashMap();
+            record.put("name", name);
+            record.put("code", code);
+            loginLanguages.add(record);
+          }
+        }
+
+        return loginLanguages;
+      }
+      catch (Throwable t) {
+        throw new ServletException(t.getMessage());
+      }
+    }
+  }
+
+  public void init(ServletConfig config) throws ServletException {
+    super.init(config);
+
+    usersModule = new ModuleUsers(DatabaseUsers.getInstance());
+  }
+
+  protected String getDefaultLanguage(HttpServletRequest aRequest) {
+    String defaultlanguage =
+      MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
+
+    if (defaultlanguage.length() == 0) {
+      Locale locale = aRequest.getLocale();
+      defaultlanguage = locale.getLanguage();
+    }
+
+    return defaultlanguage;
+  }
+
+  protected synchronized Locale getFallbackLocale() throws ServletException {
+    try {
+      if (fallbackLocale == null) {
+        fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletException(t.getMessage());
+    }
+
+    return fallbackLocale;
+  }
+
+  public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {
+    try {
+      EntityUsers user = ServletHelper.getUser(aRequest);
+
+      String username = aRequest.getParameter("login");
+      String password = aRequest.getParameter("password");
+
+      if (username != null && password != null) {
+        user = usersModule.getUserForLogin(username, password);
+
+        if (user!=null) {
+          ServletHelper.setUser(aRequest, user);
+          aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username));
+        }
+      }
+
+      return user;
+    }
+    catch (Throwable t) {
+      t.printStackTrace();
+
+      throw new ServletException(t.toString());
+    }
+  }
+
+  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {
+    try {
+      long startTime = System.currentTimeMillis();
+      long sessionConnectTime = 0;
+
+      HttpSession session = aRequest.getSession(true);
+      setNoCaching(aResponse);
+      Locale locale = new Locale(getDefaultLanguage(aRequest), "");
+      aResponse.setContentType("text/html; charset=" +
+                               configuration.
+                               getString("Mir.DefaultHTMLCharset", "UTF-8"));
+
+      EntityUsers userEntity = checkCredentials(aRequest);
+
+      if (userEntity == null) {
+        String queryString = aRequest.getQueryString();
+
+        if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&
+             (aRequest.getParameter("module")==null ||
+              (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {
+          session.setAttribute("login.target", queryString);
+        }
+
+        _sendLoginPage(aResponse, aRequest);
+      }
+      else {
+        String moduleName = aRequest.getParameter("module");
+        checkLanguage(session, aRequest);
+
+        if ( ( (moduleName == null) || moduleName.equals(""))) {
+          moduleName="Admin";
+        }
+
+
+        if (moduleName.equals("login")) {
+          String target = (String) session.getAttribute("login.target");
+
+          if (target != null) {
+            ServletHelper.redirect(aResponse, target);
+          }
+          else {
+            ServletHelper.redirect(aResponse, "");
+          }
+        }
+        else if (moduleName.equals("logout")) {
+          logger.info(userEntity.getValue("login") + " has logged out");
+          session.invalidate();
+          _sendLoginPage(aResponse, aRequest);
+          return;
+        }
+        else {
+          try {
+            ServletModule servletModule = getServletModuleForName(moduleName);
+            ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);
+
+            sessionConnectTime = System.currentTimeMillis() - startTime;
+            logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
+          }
+          catch (Throwable e) {
+            Throwable cause = ExceptionFunctions.traceCauseException(e);
+
+            if (cause instanceof ServletModuleUserExc)
+              handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
+            else
+              handleError(aRequest, aResponse, cause);
+          }
+
+          if (aRequest.getParameter("killsession")!=null)
+            aRequest.getSession().invalidate();
+        }
+      }
+    }
+    catch (Throwable t) {
+      t.printStackTrace();
+
+      throw new ServletException(t.toString());
+    }
+  }
+
+  /**
+   * caching routine to get a module for a module name
+   *
+   * @param moduleName 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());
+      }
+    }
+    else {
+      return (ServletModule) servletModuleInstanceHash.get(moduleName);
+    }
+  }
+
+  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
+    try {
+      logger.info("user error: " + anException.getMessage());
+
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      MessageResources messages = MessageResources.getMessageResources("bundles.admin");
+      responseData.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
+      responseData.put("date", new GregorianCalendar().getTime());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));
+    }
+    catch (Throwable e) {
+      logger.error("Error handling user error" + e.toString());
+    }
+  }
+
+  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {
+    try {
+      logger.error("error: " + anException);
+
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      responseData.put("errorstring", anException.toString());
+      responseData.put("date", new GregorianCalendar().getTime());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
+    }
+    catch (Throwable e) {
+      logger.error("Error handling error: " + e.toString());
+    }
+  }
+
+  // Redirect-methods
+  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {
+    String loginTemplate = configuration.getString("Mir.LoginTemplate");
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
+
+      responseData.put("defaultlanguage", getDefaultLanguage(aRequest));
+      responseData.put("languages", getLoginLanguages());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);
+    }
+    catch (Throwable e) {
+      handleError(aRequest, aResponse, e);
+    }
+  }
+
+  public String getServletInfo() {
+    return "Mir " + configuration.getString("Mir.Version");
+  }
+
+  private class SessionTracker implements HttpSessionBindingListener {
+    private String name;
+
+    public SessionTracker(String aUserName) {
+      name = aUserName;
+    }
+
+    public void valueBound(HttpSessionBindingEvent anEvent) {
+      MirGlobal.registerLogin(name);
+    }
+
+    public void valueUnbound(HttpSessionBindingEvent anEvent) {
+      MirGlobal.registerLogout(name);
+    }
+  }
+}
index cc9e260..1daa016 100755 (executable)
@@ -40,14 +40,13 @@ import mir.servlet.AbstractServlet;
 import mir.servlet.ServletModuleDispatch;
 import mir.servlet.ServletModuleUserExc;
 import mir.util.ExceptionFunctions;
-import mircoders.global.MirGlobal;
 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.1 2003/06/13 03:54:08 zapata Exp $
+ *  @version $Id: OpenMir.java,v 1.35.2.2 2003/10/23 14:55:26 rk Exp $
  *
  */
 
index 306c6fb..d675ad6 100755 (executable)
 package  mir.entity;
 
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
-import java.util.*;
+import java.util.Map;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
 import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
 import mir.storage.StorageObject;
 import mir.storage.StorageObjectExc;
 import mir.storage.StorageObjectFailure;
@@ -45,7 +45,7 @@ import mir.storage.StorageObjectFailure;
  * Base class the entities are derived from. Provides base functionality of
  * an entity. Entities are used to represent rows of a database table.<p>
  *
- * @version $Id: Entity.java,v 1.21.2.4 2003/09/03 17:49:38 zapata Exp $
+ * @version $Id: Entity.java,v 1.21.2.5 2003/10/23 14:55:28 rk Exp $
  * @author rk
  *
  */
@@ -188,7 +188,7 @@ public class Entity
     }
     catch (Throwable t) {
       logger.error("Entity.setValueForProperty: " + t.toString());
-      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
 
       throw new StorageObjectFailure(t);
     }
index 4237c27..2ef7c69 100755 (executable)
@@ -1,71 +1,71 @@
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mir.entity.adapter;\r
-\r
-import java.util.List;\r
-\r
-import mir.entity.EntityBrowser;\r
-import mir.storage.*;\r
-\r
-/**\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public class EntityAdapterEngine {\r
-  private EntityAdapterEngine() {\r
-  }\r
-\r
-  /**\r
-   *\r
-   * @param aStorage\r
-   * @param aDefinition\r
-   * @param aQualifier\r
-   * @param anOrder\r
-   * @param aLimit\r
-   * @param anOffset\r
-   * @return\r
-   */\r
-  static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) {\r
-    try {\r
-      EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset);\r
-\r
-      return new EntityListAdapter(aModel, aDefinition, browser, aLimit);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new StorageObjectFailure(t);\r
-    }\r
-  }\r
+/*
+ * 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.entity.adapter;
+
+import java.util.List;
+
+import mir.entity.EntityBrowser;
+import mir.storage.StorageObjectFailure;
+
+/**
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public class EntityAdapterEngine {
+  private EntityAdapterEngine() {
+  }
+
+  /**
+   *
+   * @param aStorage
+   * @param aDefinition
+   * @param aQualifier
+   * @param anOrder
+   * @param aLimit
+   * @param anOffset
+   * @return
+   */
+  static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) {
+    try {
+      EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset);
+
+      return new EntityListAdapter(aModel, aDefinition, browser, aLimit);
+    }
+    catch (Throwable t) {
+      throw new StorageObjectFailure(t);
+    }
+  }
 }
\ No newline at end of file
index 8b5ec61..8ca243b 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.generator;\r
-\r
-import java.io.PrintWriter;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import org.apache.commons.beanutils.MethodUtils;\r
-import org.apache.commons.beanutils.PropertyUtils;\r
-import freemarker.template.FileTemplateCache;\r
-import freemarker.template.SimpleScalar;\r
-import freemarker.template.Template;\r
-import freemarker.template.TemplateHashModel;\r
-import freemarker.template.TemplateListModel;\r
-import freemarker.template.TemplateMethodModel;\r
-import freemarker.template.TemplateModel;\r
-import freemarker.template.TemplateModelException;\r
-import freemarker.template.TemplateModelRoot;\r
-import freemarker.template.TemplateScalarModel;\r
-import mir.log.LoggerWrapper;\r
-import mir.util.GeneratorFormatAdapters;\r
-import mir.util.RewindableIterator;\r
-\r
-\r
-public class FreemarkerGenerator implements Generator {\r
-  private Template template;\r
-\r
-  public FreemarkerGenerator(Template aTemplate) {\r
-    template = aTemplate;\r
-  }\r
-\r
-  public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {\r
-    if (!(anOutputWriter instanceof PrintWriter))\r
-      throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");\r
-\r
-    try {\r
-      template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace();\r
-      aLogger.error("Exception occurred: "+t.getMessage());\r
-      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      throw new GeneratorFailure( t );\r
-    }\r
-  }\r
-\r
-  private static TemplateScalarModel makeStringAdapter(String aString) {\r
-    return new SimpleScalar(aString);\r
-  }\r
-\r
-  private static TemplateHashModel makeMapAdapter(Map aMap)  {\r
-    return new MapAdapter(aMap);\r
-  }\r
-\r
-  private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {\r
-    return new IteratorAdapter(anIterator);\r
-  }\r
-\r
-  private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) {\r
-    return new FunctionAdapter(aFunction);\r
-  }\r
-\r
-  private static TemplateHashModel makeBeanAdapter(Object anObject)  {\r
-    return new BeanAdapter(anObject);\r
-  }\r
-\r
-  public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {\r
-    if (anObject == null)\r
-      return null;\r
-\r
-    if (anObject instanceof TemplateModel)\r
-      return (TemplateModel) anObject;\r
-    else if (anObject instanceof Generator.GeneratorFunction)\r
-      return makeFunctionAdapter((Generator.GeneratorFunction) anObject);\r
-    else if (anObject instanceof Integer)\r
-      return makeStringAdapter(((Integer) anObject).toString());\r
-    else if (anObject instanceof Boolean) {\r
-      if (((Boolean) anObject).booleanValue())\r
-        return makeStringAdapter("1");\r
-      else\r
-        return makeStringAdapter("0");\r
-    }\r
-    else if (anObject instanceof String)\r
-      return makeStringAdapter((String) anObject);\r
-    else if (anObject instanceof Map)\r
-      return makeMapAdapter((Map) anObject);\r
-    else if (anObject instanceof Iterator)\r
-      return makeIteratorAdapter((Iterator) anObject);\r
-    else if (anObject instanceof List)\r
-      return makeIteratorAdapter(((List) anObject).iterator());\r
-    else if (anObject instanceof Number)\r
-      return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject));\r
-    else if (anObject instanceof Date)\r
-      return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) anObject));\r
-    else\r
-      return makeBeanAdapter(anObject);\r
-  }\r
-\r
-  private static class MapAdapter implements TemplateModelRoot {\r
-    private Map map;\r
-    private Map valuesCache;\r
-\r
-    private MapAdapter(Map aMap) {\r
-      map = aMap;\r
-      valuesCache = new HashMap();\r
-    }\r
-\r
-    public void put(String aKey, TemplateModel aModel) {\r
-      valuesCache.put(aKey, aModel);\r
-    }\r
-\r
-    public void remove(String aKey) {\r
-    }\r
-\r
-    public boolean isEmpty() {\r
-      return map.isEmpty();\r
-    }\r
-\r
-    public TemplateModel get(String aKey) throws TemplateModelException {\r
-      try {\r
-        if (!valuesCache.containsKey(aKey)) {\r
-          Object value = map.get(aKey);\r
-\r
-          if (value == null && !map.containsKey(aKey)) {\r
-            throw new TemplateModelException("MapAdapter: no key "+aKey+" available");\r
-          }\r
-\r
-          valuesCache.put(aKey, makeAdapter(value));\r
-        }\r
-\r
-        return (TemplateModel) valuesCache.get(aKey);\r
-      }\r
-      catch (TemplateModelException e) {\r
-        throw e;\r
-      }\r
-      catch (Throwable t) {\r
-        throw new TemplateModelException(t.getMessage());\r
-      }\r
-    }\r
-  }\r
-\r
-  private static class IteratorAdapter implements TemplateListModel {\r
-    private Iterator iterator;\r
-    private List valuesCache;\r
-    private int position;\r
-\r
-    private IteratorAdapter(Iterator anIterator) {\r
-      iterator = anIterator;\r
-\r
-      valuesCache = new Vector();\r
-      position=0;\r
-\r
-\r
-      if (iterator instanceof RewindableIterator) {\r
-        ((RewindableIterator) iterator).rewind();\r
-      }\r
-    }\r
-\r
-    public boolean isEmpty() {\r
-      return valuesCache.isEmpty() && !iterator.hasNext();\r
-    }\r
-\r
-    private void getUntil(int anIndex) throws TemplateModelException {\r
-      while (valuesCache.size()<=anIndex && iterator.hasNext())\r
-      {\r
-        valuesCache.add(makeAdapter(iterator.next()));\r
-      }\r
-    };\r
-\r
-    public TemplateModel get(int anIndex) throws TemplateModelException {\r
-      TemplateModel result;\r
-\r
-      getUntil(anIndex);\r
-\r
-      if (anIndex<valuesCache.size())\r
-      {\r
-        result = (TemplateModel) valuesCache.get(anIndex);\r
-\r
-        return result;\r
-      }\r
-      else\r
-        throw new TemplateModelException( "Iterator out of bounds" );\r
-    }\r
-\r
-    public boolean hasNext() {\r
-      return position<valuesCache.size() || iterator.hasNext();\r
-    }\r
-\r
-    public boolean isRewound() {\r
-      return position==0;\r
-    }\r
-\r
-    public TemplateModel next() throws TemplateModelException {\r
-      TemplateModel result;\r
-\r
-      if (hasNext()) {\r
-        result = get(position);\r
-        position++;\r
-      }\r
-      else\r
-        throw new TemplateModelException( "Iterator out of bounds" );\r
-\r
-      return result;\r
-    }\r
-\r
-    public void rewind() {\r
-      position=0;\r
-    }\r
-  }\r
-\r
-  private static class ListAdapter implements TemplateListModel {\r
-    List list;\r
-    List valuesCache;\r
-    int position;\r
-\r
-    private ListAdapter(List aList) {\r
-      list = aList;\r
-      valuesCache = new Vector();\r
-      position=0;\r
-    }\r
-\r
-    public boolean isEmpty() {\r
-      return list.isEmpty();\r
-    }\r
-\r
-    public TemplateModel get(int i) throws TemplateModelException {\r
-\r
-      if (i>=valuesCache.size() && i<list.size()) {\r
-        for(int j=valuesCache.size(); j<=i; j++) {\r
-          valuesCache.add(makeAdapter(list.get(j)));\r
-        }\r
-      }\r
-\r
-      if (i<valuesCache.size())\r
-        return (TemplateModel) valuesCache.get(i);\r
-      else\r
-        throw new TemplateModelException( "Iterator out of bounds" );\r
-    }\r
-\r
-    public boolean hasNext() {\r
-      return position<list.size();\r
-    }\r
-\r
-    public boolean isRewound() {\r
-      return position==0;\r
-    }\r
-\r
-    public TemplateModel next() throws TemplateModelException {\r
-      TemplateModel result;\r
-\r
-      if (hasNext()) {\r
-        result = get(position);\r
-        position++;\r
-      }\r
-      else {\r
-        throw new TemplateModelException( "Iterator out of bounds" );\r
-      }\r
-\r
-      return result;\r
-    }\r
-\r
-    public void rewind() {\r
-      position = 0;\r
-    }\r
-  }\r
-\r
-  private static class FunctionAdapter implements TemplateMethodModel {\r
-    private Generator.GeneratorFunction function;\r
-\r
-    public FunctionAdapter(Generator.GeneratorFunction aFunction) {\r
-      function = aFunction;\r
-    }\r
-\r
-    public TemplateModel exec(List anArguments) throws TemplateModelException {\r
-      try {\r
-        return makeAdapter(function.perform(anArguments));\r
-      }\r
-      catch (Throwable t) {\r
-        throw new TemplateModelException(t.getMessage());\r
-      }\r
-    }\r
-\r
-    public boolean isEmpty() {\r
-      return false;\r
-    }\r
-\r
-  }\r
-\r
-  private static class BeanAdapter implements TemplateHashModel {\r
-    private Object object;\r
-\r
-    public BeanAdapter(Object anObject) {\r
-      object = anObject;\r
-    }\r
-\r
-    public void put(String aKey, TemplateModel aModel)  throws TemplateModelException  {\r
-      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.put not supported");\r
-    }\r
-\r
-    public void remove(String aKey) throws TemplateModelException  {\r
-      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.remove not supported");\r
-    }\r
-\r
-    public boolean isEmpty() {\r
-      return false;\r
-    }\r
-\r
-    public TemplateModel get(String aKey) throws TemplateModelException {\r
-      try {\r
-        if (PropertyUtils.isReadable(object, aKey))\r
-          return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));\r
-        else\r
-          return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));\r
-      }\r
-      catch (Throwable t) {\r
-        throw new TemplateModelException(t.getMessage());\r
-      }\r
-    }\r
-  }\r
-\r
-  public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {\r
-    private FileTemplateCache templateCache;\r
-\r
-    public FreemarkerGeneratorLibrary(String aTemplateRoot) {\r
-      templateCache = new FileTemplateCache( aTemplateRoot+"/" );\r
-      templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);\r
-    }\r
-\r
-    public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {\r
-      Template template = (Template) templateCache.getItem(anIdentifier, "template");\r
-\r
-      if (template==null) {\r
-        throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);\r
-      }\r
-\r
-      return new FreemarkerGenerator(template);\r
-    }\r
-  }\r
-\r
-  public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {\r
-    private String basePath;\r
-\r
-    public FreemarkerGeneratorLibraryFactory(String aBasePath) {\r
-      basePath = aBasePath;\r
-    }\r
-\r
-    public GeneratorLibrary makeLibrary(String anInitializationString) {\r
-      return new FreemarkerGeneratorLibrary(basePath+anInitializationString);\r
-    };\r
-  }\r
-}\r
+/*
+ * 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.generator;
+
+import java.io.PrintWriter;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.log.LoggerWrapper;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.RewindableIterator;
+
+import org.apache.commons.beanutils.MethodUtils;
+import org.apache.commons.beanutils.PropertyUtils;
+
+import freemarker.template.FileTemplateCache;
+import freemarker.template.SimpleScalar;
+import freemarker.template.Template;
+import freemarker.template.TemplateHashModel;
+import freemarker.template.TemplateListModel;
+import freemarker.template.TemplateMethodModel;
+import freemarker.template.TemplateModel;
+import freemarker.template.TemplateModelException;
+import freemarker.template.TemplateModelRoot;
+import freemarker.template.TemplateScalarModel;
+
+
+public class FreemarkerGenerator implements Generator {
+  private Template template;
+
+  public FreemarkerGenerator(Template aTemplate) {
+    template = aTemplate;
+  }
+
+  public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {
+    if (!(anOutputWriter instanceof PrintWriter))
+      throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");
+
+    try {
+      template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);
+    }
+    catch (Throwable t) {
+      t.printStackTrace();
+      aLogger.error("Exception occurred: "+t.getMessage());
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      throw new GeneratorFailure( t );
+    }
+  }
+
+  private static TemplateScalarModel makeStringAdapter(String aString) {
+    return new SimpleScalar(aString);
+  }
+
+  private static TemplateHashModel makeMapAdapter(Map aMap)  {
+    return new MapAdapter(aMap);
+  }
+
+  private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {
+    return new IteratorAdapter(anIterator);
+  }
+
+  private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) {
+    return new FunctionAdapter(aFunction);
+  }
+
+  private static TemplateHashModel makeBeanAdapter(Object anObject)  {
+    return new BeanAdapter(anObject);
+  }
+
+  public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {
+    if (anObject == null)
+      return null;
+
+    if (anObject instanceof TemplateModel)
+      return (TemplateModel) anObject;
+    else if (anObject instanceof Generator.GeneratorFunction)
+      return makeFunctionAdapter((Generator.GeneratorFunction) anObject);
+    else if (anObject instanceof Integer)
+      return makeStringAdapter(((Integer) anObject).toString());
+    else if (anObject instanceof Boolean) {
+      if (((Boolean) anObject).booleanValue())
+        return makeStringAdapter("1");
+      else
+        return makeStringAdapter("0");
+    }
+    else if (anObject instanceof String)
+      return makeStringAdapter((String) anObject);
+    else if (anObject instanceof Map)
+      return makeMapAdapter((Map) anObject);
+    else if (anObject instanceof Iterator)
+      return makeIteratorAdapter((Iterator) anObject);
+    else if (anObject instanceof List)
+      return makeIteratorAdapter(((List) anObject).iterator());
+    else if (anObject instanceof Number)
+      return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject));
+    else if (anObject instanceof Date)
+      return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) anObject));
+    else
+      return makeBeanAdapter(anObject);
+  }
+
+  private static class MapAdapter implements TemplateModelRoot {
+    private Map map;
+    private Map valuesCache;
+
+    private MapAdapter(Map aMap) {
+      map = aMap;
+      valuesCache = new HashMap();
+    }
+
+    public void put(String aKey, TemplateModel aModel) {
+      valuesCache.put(aKey, aModel);
+    }
+
+    public void remove(String aKey) {
+    }
+
+    public boolean isEmpty() {
+      return map.isEmpty();
+    }
+
+    public TemplateModel get(String aKey) throws TemplateModelException {
+      try {
+        if (!valuesCache.containsKey(aKey)) {
+          Object value = map.get(aKey);
+
+          if (value == null && !map.containsKey(aKey)) {
+            throw new TemplateModelException("MapAdapter: no key "+aKey+" available");
+          }
+
+          valuesCache.put(aKey, makeAdapter(value));
+        }
+
+        return (TemplateModel) valuesCache.get(aKey);
+      }
+      catch (TemplateModelException e) {
+        throw e;
+      }
+      catch (Throwable t) {
+        throw new TemplateModelException(t.getMessage());
+      }
+    }
+  }
+
+  private static class IteratorAdapter implements TemplateListModel {
+    private Iterator iterator;
+    private List valuesCache;
+    private int position;
+
+    private IteratorAdapter(Iterator anIterator) {
+      iterator = anIterator;
+
+      valuesCache = new Vector();
+      position=0;
+
+
+      if (iterator instanceof RewindableIterator) {
+        ((RewindableIterator) iterator).rewind();
+      }
+    }
+
+    public boolean isEmpty() {
+      return valuesCache.isEmpty() && !iterator.hasNext();
+    }
+
+    private void getUntil(int anIndex) throws TemplateModelException {
+      while (valuesCache.size()<=anIndex && iterator.hasNext())
+      {
+        valuesCache.add(makeAdapter(iterator.next()));
+      }
+    };
+
+    public TemplateModel get(int anIndex) throws TemplateModelException {
+      TemplateModel result;
+
+      getUntil(anIndex);
+
+      if (anIndex<valuesCache.size())
+      {
+        result = (TemplateModel) valuesCache.get(anIndex);
+
+        return result;
+      }
+      else
+        throw new TemplateModelException( "Iterator out of bounds" );
+    }
+
+    public boolean hasNext() {
+      return position<valuesCache.size() || iterator.hasNext();
+    }
+
+    public boolean isRewound() {
+      return position==0;
+    }
+
+    public TemplateModel next() throws TemplateModelException {
+      TemplateModel result;
+
+      if (hasNext()) {
+        result = get(position);
+        position++;
+      }
+      else
+        throw new TemplateModelException( "Iterator out of bounds" );
+
+      return result;
+    }
+
+    public void rewind() {
+      position=0;
+    }
+  }
+
+  private static class ListAdapter implements TemplateListModel {
+    List list;
+    List valuesCache;
+    int position;
+
+    private ListAdapter(List aList) {
+      list = aList;
+      valuesCache = new Vector();
+      position=0;
+    }
+
+    public boolean isEmpty() {
+      return list.isEmpty();
+    }
+
+    public TemplateModel get(int i) throws TemplateModelException {
+
+      if (i>=valuesCache.size() && i<list.size()) {
+        for(int j=valuesCache.size(); j<=i; j++) {
+          valuesCache.add(makeAdapter(list.get(j)));
+        }
+      }
+
+      if (i<valuesCache.size())
+        return (TemplateModel) valuesCache.get(i);
+      else
+        throw new TemplateModelException( "Iterator out of bounds" );
+    }
+
+    public boolean hasNext() {
+      return position<list.size();
+    }
+
+    public boolean isRewound() {
+      return position==0;
+    }
+
+    public TemplateModel next() throws TemplateModelException {
+      TemplateModel result;
+
+      if (hasNext()) {
+        result = get(position);
+        position++;
+      }
+      else {
+        throw new TemplateModelException( "Iterator out of bounds" );
+      }
+
+      return result;
+    }
+
+    public void rewind() {
+      position = 0;
+    }
+  }
+
+  private static class FunctionAdapter implements TemplateMethodModel {
+    private Generator.GeneratorFunction function;
+
+    public FunctionAdapter(Generator.GeneratorFunction aFunction) {
+      function = aFunction;
+    }
+
+    public TemplateModel exec(List anArguments) throws TemplateModelException {
+      try {
+        return makeAdapter(function.perform(anArguments));
+      }
+      catch (Throwable t) {
+        throw new TemplateModelException(t.getMessage());
+      }
+    }
+
+    public boolean isEmpty() {
+      return false;
+    }
+
+  }
+
+  private static class BeanAdapter implements TemplateHashModel {
+    private Object object;
+
+    public BeanAdapter(Object anObject) {
+      object = anObject;
+    }
+
+    public void put(String aKey, TemplateModel aModel)  throws TemplateModelException  {
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.put not supported");
+    }
+
+    public void remove(String aKey) throws TemplateModelException  {
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.remove not supported");
+    }
+
+    public boolean isEmpty() {
+      return false;
+    }
+
+    public TemplateModel get(String aKey) throws TemplateModelException {
+      try {
+        if (PropertyUtils.isReadable(object, aKey))
+          return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));
+        else
+          return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));
+      }
+      catch (Throwable t) {
+        throw new TemplateModelException(t.getMessage());
+      }
+    }
+  }
+
+  public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {
+    private FileTemplateCache templateCache;
+
+    public FreemarkerGeneratorLibrary(String aTemplateRoot) {
+      templateCache = new FileTemplateCache( aTemplateRoot+"/" );
+      templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);
+    }
+
+    public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
+      Template template = (Template) templateCache.getItem(anIdentifier, "template");
+
+      if (template==null) {
+        throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);
+      }
+
+      return new FreemarkerGenerator(template);
+    }
+  }
+
+  public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {
+    private String basePath;
+
+    public FreemarkerGeneratorLibraryFactory(String aBasePath) {
+      basePath = aBasePath;
+    }
+
+    public GeneratorLibrary makeLibrary(String anInitializationString) {
+      return new FreemarkerGeneratorLibrary(basePath+anInitializationString);
+    };
+  }
+}
index 3f10ca7..2a3428d 100755 (executable)
@@ -30,7 +30,8 @@
 
 package mir.generator;
 
-import java.io.*;
+import java.io.PrintWriter;
+import java.io.Reader;
 import java.util.List;
 import java.util.Map;
 
index 54bb03c..cfd49e0 100755 (executable)
@@ -34,16 +34,13 @@ import java.util.HashMap;
 import java.util.Locale;
 import java.util.Map;
 
-import org.apache.struts.util.MessageResources;
-
-
-import mir.entity.adapter.*;
-import mir.generator.GeneratorExc;
+import mir.entity.adapter.EntityIteratorAdapter;
 import mir.util.CachingRewindableIterator;
 import mir.util.ResourceBundleGeneratorFunction;
-
 import mircoders.global.MirGlobal;
 
+import org.apache.struts.util.MessageResources;
+
 
 
 public class GeneratorHelper {
index bcbc06a..f9c996a 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.misc;\r
-\r
-import java.text.NumberFormat;\r
-import java.util.Calendar;\r
-import java.util.Date;\r
-import java.util.GregorianCalendar;\r
-import java.util.TimeZone;\r
-\r
-import gnu.regexp.RE;\r
-import gnu.regexp.REException;\r
-\r
-/**\r
- * Statische Hilfsmethoden zur Stringbehandlung\r
- *\r
- * @version $Id: StringUtil.java,v 1.33.2.4 2003/08/10 00:16:53 zapata Exp $\r
- * @author mir-coders group\r
- *\r
- */\r
-public final class StringUtil {\r
-\r
-  private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags,\r
-                      re_tables, re_forbiddenTags;\r
-\r
-  private StringUtil() { }  // this avoids contruction\r
-\r
-  static {\r
-    try {\r
-      //precompile regex\r
-      re_newline2br = new RE("(\r?\n){1}");\r
-      re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");\r
-      re_mail       = new RE("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b");\r
-      re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");\r
-      re_tags       = new RE("<[^>]*>",RE.REG_ICASE);\r
-      re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE);\r
-      re_forbiddenTags = new RE("<[ \t\r\n/]*(html|meta|body|head|script)[ \t\r\n]*>",RE.REG_ICASE);\r
-    }\r
-    catch (REException e){\r
-      System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Formats a number with the specified minimum and maximum number of digits.\r
-   **/\r
-  public static synchronized String zeroPaddingNumber(long value, int minDigits,\r
-      int maxDigits)\r
-  {\r
-    NumberFormat numberFormat = NumberFormat.getInstance();\r
-    numberFormat.setMinimumIntegerDigits(minDigits);\r
-    numberFormat.setMaximumIntegerDigits(maxDigits);\r
-    return numberFormat.format(value);\r
-  }\r
-\r
-  /**\r
-   * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)\r
-   * @param theDate\r
-   * @return 8-ziffriger String (yyyymmdd)\r
-   */\r
-\r
-  public static final String date2webdbDate (GregorianCalendar theDate) {\r
-    StringBuffer webdbDate = new StringBuffer();\r
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
-    return  webdbDate.toString();\r
-  }\r
-\r
-  /**\r
-   * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)\r
-   * @param theDate\r
-   * @return 12-ziffriger String (yyyymmdd)\r
-   */\r
-\r
-  public static final String date2webdbDateTime (GregorianCalendar theDate) {\r
-    StringBuffer webdbDate = new StringBuffer();\r
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
-    webdbDate.append(pad2(theDate.get(Calendar.HOUR)));\r
-    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));\r
-    return  webdbDate.toString();\r
-  }\r
-\r
-  /**\r
-   * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)\r
-   * @param theDate\r
-   * @return w3approved datetime\r
-   */\r
-\r
-  public static final String date2w3DateTime (GregorianCalendar theDate) {\r
-    StringBuffer webdbDate = new StringBuffer();\r
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
-    webdbDate.append("-");\r
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
-    webdbDate.append("-");\r
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
-    webdbDate.append("T");\r
-    webdbDate.append(pad2(theDate.get(Calendar.HOUR_OF_DAY)));\r
-    webdbDate.append(":");\r
-    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));\r
-    webdbDate.append(":");\r
-    webdbDate.append(pad2(theDate.get(Calendar.SECOND)));\r
-    //assumes you are an hour-multiple away from UTC....\r
-    int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));\r
-    if (offset < 0){\r
-      webdbDate.append("-");\r
-    }\r
-    else{\r
-      webdbDate.append("+");\r
-    }\r
-    webdbDate.append(pad2(Math.abs(offset)));\r
-    webdbDate.append(":00");\r
-    return  webdbDate.toString();\r
-  }\r
-\r
-  /**\r
-   * wandelt Calendar in dd.mm.yyyy / hh.mm um\r
-   * @param theDate\r
-   * @return String mit (dd.mm.yyyy / hh.mm um)\r
-   */\r
-  public static String date2readableDateTime (GregorianCalendar theDate) {\r
-    String readable = "";\r
-    int hour;\r
-    readable += pad2(theDate.get(Calendar.DATE));\r
-    readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);\r
-    readable += "." + String.valueOf(theDate.get(Calendar.YEAR));\r
-    hour = theDate.get(Calendar.HOUR);\r
-    if (theDate.get(Calendar.AM_PM) == Calendar.PM)\r
-      hour += 12;\r
-    readable += " / " + pad2(hour);\r
-    readable += ":" + pad2(theDate.get(Calendar.MINUTE));\r
-    return  readable;\r
-  }\r
-\r
-  /**\r
-  *  deleteForbiddenTags\r
-  *  this method deletes all <script>, <body> and <head>-tags\r
-  */\r
-  public static final String deleteForbiddenTags(String haystack) {\r
-    return re_forbiddenTags.substituteAll(haystack,"");\r
-  }\r
-\r
-  /**\r
-   *  deleteHTMLTableTags\r
-   *  this method deletes all <table>, <tr> and <td>-tags\r
-   */\r
-  public static final String deleteHTMLTableTags(String haystack) {\r
-    return re_tables.substituteAll(haystack,"");\r
-  }\r
-\r
-  /**\r
-   * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>\r
-   * getrennt ist.\r
-   *\r
-   * @param webdbDate\r
-   * @return String mit <code>/yyyy/mm/dd</code>\r
-   */\r
-  public static final String webdbDate2path (String webdbDate) {\r
-    StringBuffer path = new StringBuffer();\r
-    path.append("/").append(webdbDate.substring(0, 4));\r
-    path.append("/").append(webdbDate.substring(4, 6));\r
-    path.append("/");\r
-    //who did this?\r
-    //path.append("/").append(webdbDate.substring(6, 8));\r
-    return  path.toString();\r
-  }\r
-\r
-  /**\r
-   * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>\r
-   * @param s\r
-   * @param pattern\r
-   * @param substitute\r
-   * @return String mit den Ersetzungen\r
-   */\r
-  public static String regexpReplace(String haystack, String pattern, String substitute) {\r
-    try {\r
-      RE regex = new RE(pattern);\r
-      return regex.substituteAll(haystack,substitute);\r
-    } catch(REException ex){\r
-      return null;\r
-    }\r
-  }\r
-\r
-  /**\r
-   * L?scht <code>/</code> am Ende des Strings, falls vorhanden\r
-   * @param path\r
-   * @return String ohne <code>/</code> am Ende\r
-   */\r
-  public static final String removeSlash (String path) {\r
-    return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()\r
-        - 1) : path;\r
-  }\r
-\r
-  /**\r
-   * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)\r
-   * @return zwistellige Zahl\r
-   */\r
-  public static String pad2 (int number) {\r
-    return  number < 10 ? "0" + number : String.valueOf(number);\r
-  }\r
-\r
-  /**\r
-   * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)\r
-   *\r
-   * @return 3-stellige Zahl\r
-   */\r
-  public static String pad3 (int number) {\r
-    return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);\r
-  }\r
-\r
-  /**\r
-   * Liefert Default-Wert def zur?ck, wenn String <code>s</code>\r
-   * kein Integer ist.\r
-   *\r
-   * @param s\r
-   * @param def\r
-   * @return geparster int aus s oder def\r
-   */\r
-  public static int parseInt(String s, int def) {\r
-    if (s == null) return def;\r
-    try {\r
-      return Integer.parseInt(s);\r
-    } catch (NumberFormatException e) {\r
-      return def;\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)\r
-   *  in den html-tag <p>\r
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
-   */\r
-  public static String convertNewline2P(String haystack) {\r
-    return re_brbr2p.substituteAll(haystack,"\n</p><p>");\r
-  }\r
-\r
-  /**\r
-   *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)\r
-   *  in den html-tag <br>\r
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
-   */\r
-  public static String convertNewline2Break(String haystack) {\r
-    return re_newline2br.substituteAll(haystack,"$0<br />");\r
-  }\r
-\r
-  /**\r
-   *  createMailLinks wandelt text im email-adressenformat\r
-   *  in einen klickbaren link um\r
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
-   */\r
-  public static String createMailLinks(String haystack) {\r
-    return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");\r
-  }\r
-\r
-\r
-  /**\r
-   *  createMailLinks wandelt text im email-adressenformat\r
-   *  in einen klickbaren link um\r
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
-   */\r
-  public static String createMailLinks(String haystack, String imageRoot, String mailImage) {\r
-    return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");\r
-  }\r
-\r
-\r
-  /**\r
-   *  createURLLinks wandelt text im url-format\r
-   *  in einen klickbaren link um\r
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
-   */\r
-  public static String createURLLinks(String haystack) {\r
-    return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");\r
-  }\r
-\r
-  /**\r
-   * this routine takes text in url format and makes\r
-   * a clickaeble "<href>" link removing any "illegal" html tags\r
-   * @param haystack, the url\r
-   * @param title, the href link text\r
-   * @param imagRoot, the place to find icons\r
-   * @param extImage, the url of the icon to show next to the link\r
-   * @return a String containing the url\r
-   */\r
-  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {\r
-    if (title == null) {\r
-      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");\r
-    } else {\r
-      title = removeHTMLTags(title);\r
-      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");\r
-    }\r
-  }\r
-\r
-  /**\r
-   * this routine takes text in url format and makes\r
-   * a clickaeble "<href>" link removing any "illegal" html tags\r
-   * @param haystack, the url\r
-   * @param imageRoot, the place to find icons\r
-   * @param extImage, the url of the icon to show next to the link\r
-   * @param intImage, unused\r
-   * @return a String containing the url\r
-   */\r
-  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {\r
-    return createURLLinks(haystack, title, imageRoot, extImage);\r
-  }\r
-\r
-  /**\r
-   * this method deletes all html tags\r
-   */\r
-  public static final String removeHTMLTags(String haystack){\r
-    return re_tags.substituteAll(haystack,"");\r
-  }\r
-\r
-  /**\r
-   * this method deletes all but the approved tags html tags\r
-   * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all\r
-   */\r
-  public static String approveHTMLTags(String haystack){\r
-    try {\r
-      String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";\r
-      String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";\r
-      String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";\r
-\r
-      // kill all the bad tags that have attributes\r
-      String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";\r
-      RE regex = new RE(s,RE.REG_ICASE);\r
-      haystack = regex.substituteAll(haystack,"");\r
-\r
-      // kill all the bad tags that are attributeless\r
-      regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);\r
-      haystack = regex.substituteAll(haystack,"");\r
-\r
-      // kill all the tags which have a javascript attribute like onLoad\r
-      regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);\r
-      haystack = regex.substituteAll(haystack,"");\r
-\r
-      // kill all the tags which include a url to an unacceptable protocol\r
-      regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);\r
-      haystack = regex.substituteAll(haystack,"");\r
-\r
-      return haystack;\r
-    } catch(REException ex){\r
-      ex.printStackTrace();\r
-      return null;\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht\r
-   *  htmlcodierten string auf und returnt einen htmlcodierten String\r
-   */\r
-  public static String createHTML(String content){\r
-    content=convertNewline2Break(content);\r
-    content=convertNewline2P(content);\r
-    content=createMailLinks(content);\r
-    content=createURLLinks(content);\r
-    return content;\r
-  }\r
-\r
-\r
-  /**\r
-   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht\r
-   *  htmlcodierten string auf und returnt einen htmlcodierten String\r
-   */\r
-  public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){\r
-    content=convertNewline2Break(content);\r
-    content=convertNewline2P(content);\r
-    content=createMailLinks(content,producerDocRoot,mailImage);\r
-    content=createURLLinks(content,null,producerDocRoot,extImage,intImage);\r
-    return content;\r
-  }\r
-\r
-  /**\r
-   * Converts mir's horrible internal date format (yyyy-MM-dd HH:mm:ss+zz) into a java Date\r
-   *\r
-   * @param anInternalDate\r
-   * @return\r
-   */\r
-  public static Date convertMirInternalDateToDate(String anInternalDate) {\r
-    Calendar calendar = new GregorianCalendar();\r
-\r
-    int year;\r
-    int month;\r
-    int day;\r
-    int hours;\r
-    int minutes;\r
-    int seconds;\r
-    int timezoneOffset;\r
-\r
-    year = Integer.parseInt(anInternalDate.substring(0,4));\r
-    month = Integer.parseInt(anInternalDate.substring(5,7));\r
-    day = Integer.parseInt(anInternalDate.substring(8,10));\r
-    hours = Integer.parseInt(anInternalDate.substring(11,13));\r
-    minutes = Integer.parseInt(anInternalDate.substring(14,16));\r
-    seconds = Integer.parseInt(anInternalDate.substring(17,19));\r
-\r
-    timezoneOffset = Integer.parseInt(anInternalDate.substring(20,22));\r
-    if (anInternalDate.charAt(19) == '-')\r
-      timezoneOffset = -timezoneOffset;\r
-\r
-    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));\r
-    calendar.set(year, month-1, day, hours, minutes, seconds);\r
-    calendar.add(Calendar.HOUR, -timezoneOffset);\r
-\r
-    return calendar.getTime();\r
-  }\r
-\r
-}\r
-\r
+/*
+ * 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.misc;
+
+import gnu.regexp.RE;
+import gnu.regexp.REException;
+
+import java.text.NumberFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+/**
+ * Statische Hilfsmethoden zur Stringbehandlung
+ *
+ * @version $Id: StringUtil.java,v 1.33.2.5 2003/10/23 14:55:28 rk Exp $
+ * @author mir-coders group
+ *
+ */
+public final class StringUtil {
+
+  private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags,
+                      re_tables, re_forbiddenTags;
+
+  private StringUtil() { }  // this avoids contruction
+
+  static {
+    try {
+      //precompile regex
+      re_newline2br = new RE("(\r?\n){1}");
+      re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");
+      re_mail       = new RE("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b");
+      re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
+      re_tags       = new RE("<[^>]*>",RE.REG_ICASE);
+      re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE);
+      re_forbiddenTags = new RE("<[ \t\r\n/]*(html|meta|body|head|script)[ \t\r\n]*>",RE.REG_ICASE);
+    }
+    catch (REException e){
+      System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
+    }
+  }
+
+  /**
+   * Formats a number with the specified minimum and maximum number of digits.
+   **/
+  public static synchronized String zeroPaddingNumber(long value, int minDigits,
+      int maxDigits)
+  {
+    NumberFormat numberFormat = NumberFormat.getInstance();
+    numberFormat.setMinimumIntegerDigits(minDigits);
+    numberFormat.setMaximumIntegerDigits(maxDigits);
+    return numberFormat.format(value);
+  }
+
+  /**
+   * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
+   * @param theDate
+   * @return 8-ziffriger String (yyyymmdd)
+   */
+
+  public static final String date2webdbDate (GregorianCalendar theDate) {
+    StringBuffer webdbDate = new StringBuffer();
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
+    return  webdbDate.toString();
+  }
+
+  /**
+   * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
+   * @param theDate
+   * @return 12-ziffriger String (yyyymmdd)
+   */
+
+  public static final String date2webdbDateTime (GregorianCalendar theDate) {
+    StringBuffer webdbDate = new StringBuffer();
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
+    webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
+    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
+    return  webdbDate.toString();
+  }
+
+  /**
+   * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
+   * @param theDate
+   * @return w3approved datetime
+   */
+
+  public static final String date2w3DateTime (GregorianCalendar theDate) {
+    StringBuffer webdbDate = new StringBuffer();
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
+    webdbDate.append("-");
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
+    webdbDate.append("-");
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
+    webdbDate.append("T");
+    webdbDate.append(pad2(theDate.get(Calendar.HOUR_OF_DAY)));
+    webdbDate.append(":");
+    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
+    webdbDate.append(":");
+    webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
+    //assumes you are an hour-multiple away from UTC....
+    int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
+    if (offset < 0){
+      webdbDate.append("-");
+    }
+    else{
+      webdbDate.append("+");
+    }
+    webdbDate.append(pad2(Math.abs(offset)));
+    webdbDate.append(":00");
+    return  webdbDate.toString();
+  }
+
+  /**
+   * wandelt Calendar in dd.mm.yyyy / hh.mm um
+   * @param theDate
+   * @return String mit (dd.mm.yyyy / hh.mm um)
+   */
+  public static String date2readableDateTime (GregorianCalendar theDate) {
+    String readable = "";
+    int hour;
+    readable += pad2(theDate.get(Calendar.DATE));
+    readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
+    readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
+    hour = theDate.get(Calendar.HOUR);
+    if (theDate.get(Calendar.AM_PM) == Calendar.PM)
+      hour += 12;
+    readable += " / " + pad2(hour);
+    readable += ":" + pad2(theDate.get(Calendar.MINUTE));
+    return  readable;
+  }
+
+  /**
+  *  deleteForbiddenTags
+  *  this method deletes all <script>, <body> and <head>-tags
+  */
+  public static final String deleteForbiddenTags(String haystack) {
+    return re_forbiddenTags.substituteAll(haystack,"");
+  }
+
+  /**
+   *  deleteHTMLTableTags
+   *  this method deletes all <table>, <tr> and <td>-tags
+   */
+  public static final String deleteHTMLTableTags(String haystack) {
+    return re_tables.substituteAll(haystack,"");
+  }
+
+  /**
+   * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
+   * getrennt ist.
+   *
+   * @param webdbDate
+   * @return String mit <code>/yyyy/mm/dd</code>
+   */
+  public static final String webdbDate2path (String webdbDate) {
+    StringBuffer path = new StringBuffer();
+    path.append("/").append(webdbDate.substring(0, 4));
+    path.append("/").append(webdbDate.substring(4, 6));
+    path.append("/");
+    //who did this?
+    //path.append("/").append(webdbDate.substring(6, 8));
+    return  path.toString();
+  }
+
+  /**
+   * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
+   * @param s
+   * @param pattern
+   * @param substitute
+   * @return String mit den Ersetzungen
+   */
+  public static String regexpReplace(String haystack, String pattern, String substitute) {
+    try {
+      RE regex = new RE(pattern);
+      return regex.substituteAll(haystack,substitute);
+    } catch(REException ex){
+      return null;
+    }
+  }
+
+  /**
+   * L?scht <code>/</code> am Ende des Strings, falls vorhanden
+   * @param path
+   * @return String ohne <code>/</code> am Ende
+   */
+  public static final String removeSlash (String path) {
+    return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
+        - 1) : path;
+  }
+
+  /**
+   * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
+   * @return zwistellige Zahl
+   */
+  public static String pad2 (int number) {
+    return  number < 10 ? "0" + number : String.valueOf(number);
+  }
+
+  /**
+   * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
+   *
+   * @return 3-stellige Zahl
+   */
+  public static String pad3 (int number) {
+    return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
+  }
+
+  /**
+   * Liefert Default-Wert def zur?ck, wenn String <code>s</code>
+   * kein Integer ist.
+   *
+   * @param s
+   * @param def
+   * @return geparster int aus s oder def
+   */
+  public static int parseInt(String s, int def) {
+    if (s == null) return def;
+    try {
+      return Integer.parseInt(s);
+    } catch (NumberFormatException e) {
+      return def;
+    }
+  }
+
+
+  /**
+   *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
+   *  in den html-tag <p>
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben
+   */
+  public static String convertNewline2P(String haystack) {
+    return re_brbr2p.substituteAll(haystack,"\n</p><p>");
+  }
+
+  /**
+   *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
+   *  in den html-tag <br>
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben
+   */
+  public static String convertNewline2Break(String haystack) {
+    return re_newline2br.substituteAll(haystack,"$0<br />");
+  }
+
+  /**
+   *  createMailLinks wandelt text im email-adressenformat
+   *  in einen klickbaren link um
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben
+   */
+  public static String createMailLinks(String haystack) {
+    return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
+  }
+
+
+  /**
+   *  createMailLinks wandelt text im email-adressenformat
+   *  in einen klickbaren link um
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben
+   */
+  public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
+    return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");
+  }
+
+
+  /**
+   *  createURLLinks wandelt text im url-format
+   *  in einen klickbaren link um
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben
+   */
+  public static String createURLLinks(String haystack) {
+    return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
+  }
+
+  /**
+   * this routine takes text in url format and makes
+   * a clickaeble "<href>" link removing any "illegal" html tags
+   * @param haystack, the url
+   * @param title, the href link text
+   * @param imagRoot, the place to find icons
+   * @param extImage, the url of the icon to show next to the link
+   * @return a String containing the url
+   */
+  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
+    if (title == null) {
+      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");
+    } else {
+      title = removeHTMLTags(title);
+      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");
+    }
+  }
+
+  /**
+   * this routine takes text in url format and makes
+   * a clickaeble "<href>" link removing any "illegal" html tags
+   * @param haystack, the url
+   * @param imageRoot, the place to find icons
+   * @param extImage, the url of the icon to show next to the link
+   * @param intImage, unused
+   * @return a String containing the url
+   */
+  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
+    return createURLLinks(haystack, title, imageRoot, extImage);
+  }
+
+  /**
+   * this method deletes all html tags
+   */
+  public static final String removeHTMLTags(String haystack){
+    return re_tags.substituteAll(haystack,"");
+  }
+
+  /**
+   * this method deletes all but the approved tags html tags
+   * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
+   */
+  public static String approveHTMLTags(String haystack){
+    try {
+      String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
+      String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
+      String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
+
+      // kill all the bad tags that have attributes
+      String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
+      RE regex = new RE(s,RE.REG_ICASE);
+      haystack = regex.substituteAll(haystack,"");
+
+      // kill all the bad tags that are attributeless
+      regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
+      haystack = regex.substituteAll(haystack,"");
+
+      // kill all the tags which have a javascript attribute like onLoad
+      regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
+      haystack = regex.substituteAll(haystack,"");
+
+      // kill all the tags which include a url to an unacceptable protocol
+      regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
+      haystack = regex.substituteAll(haystack,"");
+
+      return haystack;
+    } catch(REException ex){
+      ex.printStackTrace();
+      return null;
+    }
+  }
+
+
+  /**
+   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
+   *  htmlcodierten string auf und returnt einen htmlcodierten String
+   */
+  public static String createHTML(String content){
+    content=convertNewline2Break(content);
+    content=convertNewline2P(content);
+    content=createMailLinks(content);
+    content=createURLLinks(content);
+    return content;
+  }
+
+
+  /**
+   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
+   *  htmlcodierten string auf und returnt einen htmlcodierten String
+   */
+  public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
+    content=convertNewline2Break(content);
+    content=convertNewline2P(content);
+    content=createMailLinks(content,producerDocRoot,mailImage);
+    content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
+    return content;
+  }
+
+  /**
+   * Converts mir's horrible internal date format (yyyy-MM-dd HH:mm:ss+zz) into a java Date
+   *
+   * @param anInternalDate
+   * @return
+   */
+  public static Date convertMirInternalDateToDate(String anInternalDate) {
+    Calendar calendar = new GregorianCalendar();
+
+    int year;
+    int month;
+    int day;
+    int hours;
+    int minutes;
+    int seconds;
+    int timezoneOffset;
+
+    year = Integer.parseInt(anInternalDate.substring(0,4));
+    month = Integer.parseInt(anInternalDate.substring(5,7));
+    day = Integer.parseInt(anInternalDate.substring(8,10));
+    hours = Integer.parseInt(anInternalDate.substring(11,13));
+    minutes = Integer.parseInt(anInternalDate.substring(14,16));
+    seconds = Integer.parseInt(anInternalDate.substring(17,19));
+
+    timezoneOffset = Integer.parseInt(anInternalDate.substring(20,22));
+    if (anInternalDate.charAt(19) == '-')
+      timezoneOffset = -timezoneOffset;
+
+    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+    calendar.set(year, month-1, day, hours, minutes, seconds);
+    calendar.add(Calendar.HOUR, -timezoneOffset);
+
+    return calendar.getTime();
+  }
+
+}
+
index 055e182..0a09c02 100755 (executable)
 package mir.producer;
 
 import java.util.Map;
-import java.util.Vector;
 
 import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
 import mir.log.LoggerWrapper;
-import mir.util.CachingRewindableIterator;
 import mir.util.ParameterExpander;
 
 public class EntityDeletingProducerNode implements ProducerNode {
index 295a63a..d0c9c4d 100755 (executable)
 
 package mir.producer;
 
+import java.util.Date;
 import java.util.HashMap;
 import java.util.Iterator;
-import java.util.*;
+import java.util.Map;
 
 import mir.entity.Entity;
 import mir.entity.adapter.EntityAdapter;
 import mir.entity.adapter.EntityAdapterModel;
 import mir.log.LoggerWrapper;
+import mir.util.JDBCStringRoutines;
 import mir.util.ParameterExpander;
-import mir.util.*;
 
 
 public class EntityModifyingProducerNode implements ProducerNode {
@@ -105,7 +106,7 @@ public class EntityModifyingProducerNode implements ProducerNode {
     }
     catch (Throwable t) {
       aLogger.error("Error while performing entity modification operation: " + t.getMessage());
-      t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE));
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
 
       throw new ProducerFailure(t.getMessage(), t);
     }
index 8cb0360..35d5ee9 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.producer;\r
-\r
-import java.util.*;\r
-\r
-import mir.generator.Generator;\r
-import mir.generator.WriterEngine;\r
-import mir.log.LoggerWrapper;\r
-import mir.util.ParameterExpander;\r
-\r
-public class GeneratingProducerNode implements ProducerNode {\r
-  private String generatorExpression;\r
-  private String destinationExpression;\r
-  private String parametersExpression;\r
-  private Generator.GeneratorLibrary generatorLibrary;\r
-  private WriterEngine writerEngine;\r
-\r
-  public GeneratingProducerNode(Generator.GeneratorLibrary aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination, String aParameters) {\r
-    generatorExpression=aGenerator;\r
-    destinationExpression=aDestination;\r
-    parametersExpression=aParameters;\r
-    generatorLibrary = aGeneratorLibrary;\r
-    writerEngine = aWriterEngine;\r
-  }\r
-\r
-  public GeneratingProducerNode(Generator.GeneratorLibrary aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination) {\r
-    this(aGeneratorLibrary, aWriterEngine, aGenerator, aDestination, "");\r
-  }\r
-\r
-  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {\r
-    Generator generator;\r
-    Object writer;\r
-    String generatorIdentifier;\r
-    String destinationIdentifier;\r
-    String parameters;\r
-\r
-    long startTime;\r
-    long endTime;\r
-\r
-    startTime = System.currentTimeMillis();\r
-    try {\r
-      Map mirMap = (Map) aValueMap.get("Mir");\r
-      if (mirMap==null) {\r
-        mirMap = new HashMap();\r
-        aValueMap.put("Mir", mirMap);\r
-      }\r
-\r
-      Object oldGenerator = mirMap.get("generator");\r
-      Object oldDestination = mirMap.get("destination");\r
-      Object oldParameters = mirMap.get("parameters");\r
-      try {\r
-        destinationIdentifier = ParameterExpander.expandExpression(aValueMap, destinationExpression);\r
-        generatorIdentifier = ParameterExpander.expandExpression(aValueMap, generatorExpression);\r
-        parameters = ParameterExpander.expandExpression(aValueMap, parametersExpression);\r
-\r
-        mirMap.put("generator", generatorIdentifier);\r
-        mirMap.put("destination", destinationIdentifier);\r
-        mirMap.put("parameters", parameters);\r
-\r
-        writer = writerEngine.openWriter(destinationIdentifier, parameters);\r
-        generator = generatorLibrary.makeGenerator(generatorIdentifier);\r
-        generator.generate(writer, aValueMap, aLogger);\r
-        writerEngine.closeWriter(writer);\r
-\r
-        endTime = System.currentTimeMillis();\r
-        aLogger.info("Generated " + generatorIdentifier + " into " + destinationIdentifier + " [" + parameters + "] in " + (endTime - startTime) + " ms");\r
-      }\r
-      finally {\r
-        mirMap.put("generator", oldGenerator);\r
-        mirMap.put("destination", oldDestination);\r
-        mirMap.put("parameters", oldParameters);\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      aLogger.error("  error while generating: " + t.getClass().getName() + ": " + t.getMessage());\r
-    }\r
-  }\r
+/*
+ * 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.producer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import mir.generator.Generator;
+import mir.generator.WriterEngine;
+import mir.log.LoggerWrapper;
+import mir.util.ParameterExpander;
+
+public class GeneratingProducerNode implements ProducerNode {
+  private String generatorExpression;
+  private String destinationExpression;
+  private String parametersExpression;
+  private Generator.GeneratorLibrary generatorLibrary;
+  private WriterEngine writerEngine;
+
+  public GeneratingProducerNode(Generator.GeneratorLibrary aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination, String aParameters) {
+    generatorExpression=aGenerator;
+    destinationExpression=aDestination;
+    parametersExpression=aParameters;
+    generatorLibrary = aGeneratorLibrary;
+    writerEngine = aWriterEngine;
+  }
+
+  public GeneratingProducerNode(Generator.GeneratorLibrary aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination) {
+    this(aGeneratorLibrary, aWriterEngine, aGenerator, aDestination, "");
+  }
+
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+    Generator generator;
+    Object writer;
+    String generatorIdentifier;
+    String destinationIdentifier;
+    String parameters;
+
+    long startTime;
+    long endTime;
+
+    startTime = System.currentTimeMillis();
+    try {
+      Map mirMap = (Map) aValueMap.get("Mir");
+      if (mirMap==null) {
+        mirMap = new HashMap();
+        aValueMap.put("Mir", mirMap);
+      }
+
+      Object oldGenerator = mirMap.get("generator");
+      Object oldDestination = mirMap.get("destination");
+      Object oldParameters = mirMap.get("parameters");
+      try {
+        destinationIdentifier = ParameterExpander.expandExpression(aValueMap, destinationExpression);
+        generatorIdentifier = ParameterExpander.expandExpression(aValueMap, generatorExpression);
+        parameters = ParameterExpander.expandExpression(aValueMap, parametersExpression);
+
+        mirMap.put("generator", generatorIdentifier);
+        mirMap.put("destination", destinationIdentifier);
+        mirMap.put("parameters", parameters);
+
+        writer = writerEngine.openWriter(destinationIdentifier, parameters);
+        generator = generatorLibrary.makeGenerator(generatorIdentifier);
+        generator.generate(writer, aValueMap, aLogger);
+        writerEngine.closeWriter(writer);
+
+        endTime = System.currentTimeMillis();
+        aLogger.info("Generated " + generatorIdentifier + " into " + destinationIdentifier + " [" + parameters + "] in " + (endTime - startTime) + " ms");
+      }
+      finally {
+        mirMap.put("generator", oldGenerator);
+        mirMap.put("destination", oldDestination);
+        mirMap.put("parameters", oldParameters);
+      }
+    }
+    catch (Throwable t) {
+      aLogger.error("  error while generating: " + t.getClass().getName() + ": " + t.getMessage());
+    }
+  }
 }
\ No newline at end of file
index 6dc6d01..e9a68fc 100755 (executable)
  */
 package mir.producer;
 
-import java.util.*;
+import java.util.Collection;
+import java.util.Iterator;
 import java.util.Map;
 
-import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
 import mir.log.LoggerWrapper;
-import mir.util.*;
+import mir.util.ParameterExpander;
+import mir.util.RewindableIterator;
 
 public class ListEnumeratingProducerNode extends ProducerNodeDecorator {
   private String key;
index 7d002cf..fe99ff6 100755 (executable)
  */
 package mir.producer;
 
-import java.util.*;
+import java.util.List;
+import java.util.Map;
 
 import mir.log.LoggerWrapper;
-import mir.rss.RSSData;
-import mir.rss.*;
+import mir.rss.RSSAggregator;
 import mir.util.ExceptionFunctions;
 import mir.util.ParameterExpander;
 
index 6dae7c6..d61c96e 100755 (executable)
@@ -32,8 +32,9 @@ package mir.producer;
 import java.util.Map;
 
 import mir.log.LoggerWrapper;
+import mir.rss.RSS091Reader;
 import mir.rss.RSSData;
-import mir.rss.*;
+import mir.rss.RSSReader;
 import mir.util.ExceptionFunctions;
 import mir.util.ParameterExpander;
 
index dd91805..448f0c3 100755 (executable)
@@ -42,8 +42,9 @@ import mir.producer.CompositeProducerNode;
 import mir.producer.ProducerFactory;
 import mir.producer.ProducerNode;
 import mir.producer.SimpleProducerVerb;
+import mir.util.ExceptionFunctions;
 import mir.util.XMLReader;
-import mir.util.*;
+import mir.util.XMLReaderTool;
 
 public class ProducerConfigReader {
   private ProducerNodeBuilderLibrary builderLibrary;
index 85fd95c..7e85c69 100755 (executable)
@@ -31,13 +31,13 @@ package mir.rss;
 
 import java.io.InputStream;
 import java.net.URL;
+import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
-import java.util.*;
+import java.util.Map;
 import java.util.Vector;
-import java.text.*;
 
 import mir.util.XMLReader;
-import mir.util.*;
 
 /**
  *
index bdc6ae0..a7b48d2 100755 (executable)
@@ -30,7 +30,9 @@
 
 package mir.rss;
 
-import java.util.*;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
 
 public class RSSAggregator {
   private String orderBy;
index 92f102c..fdd074c 100755 (executable)
@@ -30,9 +30,6 @@
 
 package mir.rss;
 
-import java.util.*;
-import mir.util.*;
-import gnu.regexp.RE;
 
 
 public class RSSTest {
index 441ee33..ff059d5 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 java.io.IOException;\r
-import java.lang.reflect.InvocationTargetException;\r
-import java.lang.reflect.Method;\r
-import java.sql.Connection;\r
-import java.util.Locale;\r
-\r
-import javax.servlet.ServletConfig;\r
-import javax.servlet.ServletException;\r
-import javax.servlet.http.HttpServlet;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import com.codestudio.util.JDBCPool;\r
-import com.codestudio.util.JDBCPoolMetaData;\r
-import com.codestudio.util.SQLManager;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.log.LoggerWrapper;\r
-\r
-import mircoders.global.MirGlobal;\r
-\r
-/**\r
- * Title:        Mir\r
- * Description:  Abstract servlet-class\r
- * Copyright:    Copyright (c) 2001, 2002\r
- * Company:      Mir-coders group\r
- * @author       idfx, the Mir-coders group\r
- * @version      $Id: AbstractServlet.java,v 1.30.2.4 2003/09/03 17:49:38 zapata Exp $\r
- */\r
-\r
-public abstract class AbstractServlet extends HttpServlet {\r
-  protected static String lang;\r
-  protected LoggerWrapper logger;\r
-  protected MirPropertiesConfiguration configuration;\r
-\r
-  /**\r
-   * Constructor for AbstractServlet.\r
-   */\r
-  public AbstractServlet() {\r
-    super();\r
-  }\r
-\r
-  protected void setNoCaching(HttpServletResponse aResponse) {\r
-    //nothing in Mir can or should be cached as it's all dynamic...\r
-    //\r
-    //this needs to be done here and not per page (via meta tags) as some\r
-    //browsers have problems w/ it per-page -mh\r
-    aResponse.setHeader("Pragma", "no-cache");\r
-    aResponse.setDateHeader("Expires", 0);\r
-    aResponse.setHeader("Cache-Control", "no-cache");\r
-  }\r
-\r
-  /**\r
-   * Bind the language to the session\r
-   */\r
-  protected void setLanguage(HttpSession session, String language) {\r
-    logger.debug("setting language to " + language);\r
-\r
-    session.setAttribute("language", language);\r
-    session.setAttribute("locale", new Locale(language, ""));\r
-  }\r
-\r
-  /**\r
-   * Get the session-bound language\r
-   */\r
-  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {\r
-    String lang = (String) session.getAttribute("language");\r
-\r
-    if (lang == null || lang.length()==0) {\r
-      lang = getAcceptLanguage(aRequest);\r
-    }\r
-\r
-    return lang;\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
-  public Locale getLocale(HttpServletRequest aRequest) {\r
-    Locale loc = null;\r
-    HttpSession session = aRequest.getSession(false);\r
-    if (session != null) {\r
-      // session can be null in case of logout\r
-      loc = (Locale) session.getAttribute("locale");\r
-    }\r
-    // if there is nothing in the session get it fron the accept-language\r
-    if (loc == null) {\r
-      loc = aRequest.getLocale();\r
-    }\r
-\r
-    logger.debug("getting locale: " + loc.getLanguage());\r
-\r
-    return loc;\r
-  }\r
-\r
-  /**\r
-   * Checks the Accept-Language of the client browser.\r
-   * If this language is available it returns its country-code,\r
-   * else it returns the standard-language\r
-   */\r
-  protected String getAcceptLanguage(HttpServletRequest aRequest) {\r
-    Locale loc = aRequest.getLocale();\r
-    lang = loc.getLanguage();\r
-    return lang;\r
-  }\r
-\r
-  /**\r
-   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)\r
-   */\r
-  public void init(ServletConfig config) throws ServletException {\r
-    super.init(config);\r
-\r
-    MirPropertiesConfiguration.setContext(config.getServletContext());\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletException("can't read configuration: " + t.toString());\r
-    }\r
-\r
-    logger = new LoggerWrapper("Servlet");\r
-\r
-    try {\r
-      MirGlobal.localizer();\r
-    }\r
-    catch (Throwable t) {\r
-      logger.fatal("can't get localizer: " + t.toString());\r
-      throw new ServletException("can't get localizer: " + t.toString());\r
-    }\r
-\r
-    String dbUser = configuration.getString("Database.Username");\r
-    String dbPassword = configuration.getString("Database.Password");\r
-    String dbHost = configuration.getString("Database.Host");\r
-    String dbPort = configuration.getString("Database.Port");\r
-    String dbAdapName = configuration.getString("Database.Adaptor");\r
-    String dbName = configuration.getString("Database.Name");\r
-    String dbDriver = configuration.getString("Database.Driver");\r
-    String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;\r
-    int dbMin = configuration.getInteger("Database.poolMin", 1);\r
-    int dbMax = configuration.getInteger("Database.poolMax", 10);\r
-\r
-    JDBCPoolMetaData meta = new JDBCPoolMetaData();\r
-    meta.setDbname(dbName);\r
-    meta.setDriver(dbDriver);\r
-    meta.setURL(dbUrl);\r
-    meta.setUserName(dbUser);\r
-    meta.setPassword(dbPassword);\r
-    meta.setJNDIName("mir");\r
-    meta.setMaximumSize(dbMax);\r
-    meta.setMinimumSize(dbMin);\r
-    meta.setPoolPreparedStatements(false);\r
-    meta.setCacheEnabled(false);\r
-    meta.setCacheSize(15);\r
-    meta.setDebugging(false);\r
-\r
-    SQLManager manager = SQLManager.getInstance();\r
-\r
-    JDBCPool pool = null;\r
-    if (manager != null) {\r
-      pool = manager.createPool(meta);\r
-    }\r
-\r
-    Connection connection;\r
-    try {\r
-      connection = pool.requestConnection();\r
-      pool.closeConnection(connection);\r
-    }\r
-    catch (Throwable t) {\r
-      logger.fatal("Can't connect to database: " + t.toString());\r
-      throw new ServletException("Can't connect to database: " + t.toString());\r
-    }\r
-  }\r
-\r
-  private void setEncoding(HttpServletRequest request){\r
-    try {\r
-      logger.info("Request has encoding: " + request.getCharacterEncoding());\r
-      logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));\r
-      Class reqClass = request.getClass();\r
-      Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});\r
-      String encoding = configuration.getString("Mir.DefaultHTMLCharset");\r
-      method.invoke(request, new Object[]{encoding});\r
-      logger.info("Request now has encoding: " + request.getCharacterEncoding());\r
-    }\r
-    catch (NoSuchMethodException e) {\r
-      // TODO set the encoding in a zapata-way\r
-//      logger.warn("set encoding not yet implemented: " + e.getMessage());\r
-    }\r
-    catch (SecurityException e) {\r
-      logger.error(e.getMessage());\r
-      e.printStackTrace();\r
-    }\r
-    catch (IllegalArgumentException e) {\r
-      logger.error(e.getMessage());\r
-      e.printStackTrace();\r
-    }\r
-    catch (IllegalAccessException e) {\r
-      logger.error(e.getMessage());\r
-      e.printStackTrace();\r
-    }\r
-    catch (InvocationTargetException e) {\r
-      logger.error(e.getMessage());\r
-      e.printStackTrace();\r
-    }\r
-  }\r
-\r
-  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
-    doPost(request, response);\r
-  }\r
-\r
-  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
-    if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {\r
-      configuration.setProperty("RootUri", request.getContextPath());\r
-    }\r
-    setEncoding(request);\r
-    process(request, response);\r
-  }\r
-\r
-  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;\r
-\r
-  /**\r
-   * Selects the language for the response.\r
-   *\r
-   * @param session\r
-   * @param aRequest\r
-   */\r
-  protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {\r
-    String requestLanguage = aRequest.getParameter("language");\r
-    String sessionLanguage = (String) aSession.getAttribute("language");\r
-    String acceptLanguage = aRequest.getLocale().getLanguage();\r
-    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");\r
-\r
-    String language = requestLanguage;\r
-\r
-    if (language==null)\r
-      language = sessionLanguage;\r
-\r
-    if (language==null)\r
-      language = acceptLanguage;\r
-\r
-    if (language==null)\r
-      language = defaultLanguage;\r
-\r
-    setLanguage(aSession, language);\r
-  }\r
-}\r
+/*
+ * 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.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.util.Locale;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
+import mircoders.global.MirGlobal;
+
+import com.codestudio.util.JDBCPool;
+import com.codestudio.util.JDBCPoolMetaData;
+import com.codestudio.util.SQLManager;
+
+/**
+ * Title:        Mir
+ * Description:  Abstract servlet-class
+ * Copyright:    Copyright (c) 2001, 2002
+ * Company:      Mir-coders group
+ * @author       idfx, the Mir-coders group
+ * @version      $Id: AbstractServlet.java,v 1.30.2.5 2003/10/23 14:55:26 rk Exp $
+ */
+
+public abstract class AbstractServlet extends HttpServlet {
+  protected static String lang;
+  protected LoggerWrapper logger;
+  protected MirPropertiesConfiguration configuration;
+
+  /**
+   * Constructor for AbstractServlet.
+   */
+  public AbstractServlet() {
+    super();
+  }
+
+  protected void setNoCaching(HttpServletResponse aResponse) {
+    //nothing in Mir can or should be cached as it's all dynamic...
+    //
+    //this needs to be done here and not per page (via meta tags) as some
+    //browsers have problems w/ it per-page -mh
+    aResponse.setHeader("Pragma", "no-cache");
+    aResponse.setDateHeader("Expires", 0);
+    aResponse.setHeader("Cache-Control", "no-cache");
+  }
+
+  /**
+   * Bind the language to the session
+   */
+  protected void setLanguage(HttpSession session, String language) {
+    logger.debug("setting language to " + language);
+
+    session.setAttribute("language", language);
+    session.setAttribute("locale", new Locale(language, ""));
+  }
+
+  /**
+   * Get the session-bound language
+   */
+  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
+    String lang = (String) session.getAttribute("language");
+
+    if (lang == null || lang.length()==0) {
+      lang = getAcceptLanguage(aRequest);
+    }
+
+    return lang;
+  }
+
+  /**
+   * get the locale either from the session or the accept-language header ot the request
+   * this supersedes getLanguage for the new i18n
+   */
+  public Locale getLocale(HttpServletRequest aRequest) {
+    Locale loc = null;
+    HttpSession session = aRequest.getSession(false);
+    if (session != null) {
+      // session can be null in case of logout
+      loc = (Locale) session.getAttribute("locale");
+    }
+    // if there is nothing in the session get it fron the accept-language
+    if (loc == null) {
+      loc = aRequest.getLocale();
+    }
+
+    logger.debug("getting locale: " + loc.getLanguage());
+
+    return loc;
+  }
+
+  /**
+   * Checks the Accept-Language of the client browser.
+   * If this language is available it returns its country-code,
+   * else it returns the standard-language
+   */
+  protected String getAcceptLanguage(HttpServletRequest aRequest) {
+    Locale loc = aRequest.getLocale();
+    lang = loc.getLanguage();
+    return lang;
+  }
+
+  /**
+   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
+   */
+  public void init(ServletConfig config) throws ServletException {
+    super.init(config);
+
+    MirPropertiesConfiguration.setContext(config.getServletContext());
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (Throwable t) {
+      throw new ServletException("can't read configuration: " + t.toString());
+    }
+
+    logger = new LoggerWrapper("Servlet");
+
+    try {
+      MirGlobal.localizer();
+    }
+    catch (Throwable t) {
+      logger.fatal("can't get localizer: " + t.toString());
+      throw new ServletException("can't get localizer: " + t.toString());
+    }
+
+    String dbUser = configuration.getString("Database.Username");
+    String dbPassword = configuration.getString("Database.Password");
+    String dbHost = configuration.getString("Database.Host");
+    String dbPort = configuration.getString("Database.Port");
+    String dbAdapName = configuration.getString("Database.Adaptor");
+    String dbName = configuration.getString("Database.Name");
+    String dbDriver = configuration.getString("Database.Driver");
+    String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;
+    int dbMin = configuration.getInteger("Database.poolMin", 1);
+    int dbMax = configuration.getInteger("Database.poolMax", 10);
+
+    JDBCPoolMetaData meta = new JDBCPoolMetaData();
+    meta.setDbname(dbName);
+    meta.setDriver(dbDriver);
+    meta.setURL(dbUrl);
+    meta.setUserName(dbUser);
+    meta.setPassword(dbPassword);
+    meta.setJNDIName("mir");
+    meta.setMaximumSize(dbMax);
+    meta.setMinimumSize(dbMin);
+    meta.setPoolPreparedStatements(false);
+    meta.setCacheEnabled(false);
+    meta.setCacheSize(15);
+    meta.setDebugging(false);
+
+    SQLManager manager = SQLManager.getInstance();
+
+    JDBCPool pool = null;
+    if (manager != null) {
+      pool = manager.createPool(meta);
+    }
+
+    Connection connection;
+    try {
+      connection = pool.requestConnection();
+         JDBCPool.closeConnection(connection);
+    }
+    catch (Throwable t) {
+      logger.fatal("Can't connect to database: " + t.toString());
+      throw new ServletException("Can't connect to database: " + t.toString());
+    }
+  }
+
+  private void setEncoding(HttpServletRequest request){
+    try {
+      logger.info("Request has encoding: " + request.getCharacterEncoding());
+      logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));
+      Class reqClass = request.getClass();
+      Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
+      String encoding = configuration.getString("Mir.DefaultHTMLCharset");
+      method.invoke(request, new Object[]{encoding});
+      logger.info("Request now has encoding: " + request.getCharacterEncoding());
+    }
+    catch (NoSuchMethodException e) {
+      // TODO set the encoding in a zapata-way
+//      logger.warn("set encoding not yet implemented: " + e.getMessage());
+    }
+    catch (SecurityException e) {
+      logger.error(e.getMessage());
+      e.printStackTrace();
+    }
+    catch (IllegalArgumentException e) {
+      logger.error(e.getMessage());
+      e.printStackTrace();
+    }
+    catch (IllegalAccessException e) {
+      logger.error(e.getMessage());
+      e.printStackTrace();
+    }
+    catch (InvocationTargetException e) {
+      logger.error(e.getMessage());
+      e.printStackTrace();
+    }
+  }
+
+  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+    doPost(request, response);
+  }
+
+  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());
+    }
+    setEncoding(request);
+    process(request, response);
+  }
+
+  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
+
+  /**
+   * Selects the language for the response.
+   *
+   * @param session
+   * @param aRequest
+   */
+  protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {
+    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 language = requestLanguage;
+
+    if (language==null)
+      language = sessionLanguage;
+
+    if (language==null)
+      language = acceptLanguage;
+
+    if (language==null)
+      language = defaultLanguage;
+
+    setLanguage(aSession, language);
+  }
+}
index dda8e7d..7232928 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
-import mir.entity.adapter.EntityAdapterDefinition;\r
-import mir.entity.adapter.EntityAdapterEngine;\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.log.LoggerWrapper;\r
-import mir.module.AbstractModule;\r
-import mir.storage.StorageObject;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.URLBuilder;\r
-import mircoders.servlet.ServletHelper;\r
-import mircoders.global.*;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public abstract class ServletModule {\r
-  public String defaultAction;\r
-  protected LoggerWrapper logger;\r
-  protected MirPropertiesConfiguration configuration;\r
-  protected Locale fallbackLocale;\r
-\r
-  protected AbstractModule mainModule;\r
-  protected String definition;\r
-  protected EntityAdapterModel model;\r
-\r
-  protected String listGenerator;\r
-  protected String editGenerator;\r
-  protected String deleteConfirmationGenerator;\r
-  protected int nrEntitiesPerListPage;\r
-\r
-\r
-  public ServletModule(){\r
-    definition = null;\r
-    model = null;\r
-\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (PropertiesConfigExc e) {\r
-      throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
-    }\r
-\r
-    listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate");\r
-    editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate");\r
-    deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate");\r
-    nrEntitiesPerListPage =\r
-        configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize",\r
-        configuration.getInt("ServletModule.Default.ListSize", 20));\r
-\r
-    fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");\r
-  }\r
-\r
-\r
-  public void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {\r
-    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + anObject, aDescription);\r
-  }\r
-\r
-  /**\r
-   * Singleton instance retrievel method. MUST be overridden in subclasses.\r
-   *\r
-   * @return ServletModule the single instance of the servletmodule class\r
-   */\r
-  public static ServletModule getInstance() {\r
-    return null;\r
-  }\r
-\r
-  /**\r
-   * Get the module name\r
-   *\r
-   * @return\r
-   */\r
-  protected String getOperationModuleName() {\r
-    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());\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
-  public Locale getLocale(HttpServletRequest aRequest) {\r
-    Locale loc = null;\r
-    HttpSession session = aRequest.getSession(false);\r
-    if (session != null) {\r
-      // session can be null in case of logout\r
-      loc = (Locale) session.getAttribute("locale");\r
-    }\r
-    // if there is nothing in the session get it fron the accept-language\r
-    if (loc == null) {\r
-      loc = aRequest.getLocale();\r
-    }\r
-    return loc;\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
-  public Locale getFallbackLocale(HttpServletRequest aRequest) {\r
-    return fallbackLocale;\r
-  }\r
-\r
-  /**\r
-   * Function to specify the default ordering for lists. May be overridden.\r
-   *\r
-   *\r
-   * @return\r
-   */\r
-  public String getDefaultListOrdering() {\r
-\r
-    if (mainModule!=null && mainModule.getStorageObject()!=null){\r
-      if (mainModule.getStorageObject().getFields().contains("webdb_create"))\r
-        return "webdb_create desc";\r
-    }\r
-\r
-    return "id asc";\r
-  }\r
-\r
-  /**\r
-   *\r
-   * @param aResponse\r
-   * @param aQuery\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Generic list method\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String where = requestParser.getParameter("where");\r
-    String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());\r
-    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
-\r
-    returnList(aRequest, aResponse, where, order, offset);\r
-  }\r
-\r
-\r
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
-\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      List list =\r
-         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);\r
-\r
-      responseData.put("nexturl", null);\r
-      responseData.put("prevurl", null);\r
-      responseData.put("module", getOperationModuleName());\r
-\r
-      count=mainModule.getSize(aWhereClause);\r
-\r
-      urlBuilder.setValue("module", getOperationModuleName());\r
-      urlBuilder.setValue("do", "list");\r
-      urlBuilder.setValue("where", aWhereClause);\r
-      urlBuilder.setValue("order", anOrderByClause);\r
-\r
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
-      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
-      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));\r
-      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
-\r
-      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
-      responseData.put("searchtext", requestParser.getParameter("searchtext"));\r
-      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
-      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));\r
-      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
-\r
-      urlBuilder.setValue("offset", anOffset);\r
-      responseData.put("offset" , new Integer(anOffset).toString());\r
-      responseData.put("thisurl" , urlBuilder.getQuery());\r
-\r
-      if (count>anOffset+nrEntitiesPerListPage) {\r
-        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
-        responseData.put("nexturl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      if (anOffset>0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
-        responseData.put("prevurl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      responseData.put("entities", list);\r
-      responseData.put("from" , Integer.toString(anOffset+1));\r
-      responseData.put("count", Integer.toString(count));\r
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {\r
-    try {\r
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    EntityAdapterModel model;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      responseData.put("module", getOperationModuleName());\r
-      responseData.put("entity", anObject);\r
-      responseData.put("new", new Boolean(anIsNew));\r
-\r
-\r
-      urlBuilder.setValue("module", getOperationModuleName());\r
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
-      if (anIsNew)\r
-        urlBuilder.setValue("do", "add");\r
-      else {\r
-        urlBuilder.setValue("id", anId);\r
-        urlBuilder.setValue("do", "edit");\r
-      }\r
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   * Generic add method\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-\r
-    Map object = new HashMap();\r
-\r
-    Iterator i = mainModule.getStorageObject().getFields().iterator();\r
-\r
-    while (i.hasNext())\r
-      object.put(i.next(), "");\r
-\r
-    initializeNewObject(object, aRequest, aResponse);\r
-\r
-    editObject(aRequest, aResponse, object, true, null);\r
-  }\r
-\r
-  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-  }\r
-\r
-  /**\r
-   * Method called when the user edits an object.\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    edit(aRequest, aResponse, aRequest.getParameter("id"));\r
-  }\r
-\r
-  /**\r
-   * Generic edit method\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @param anIdentifier\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Generic update method\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-      String id = aRequest.getParameter("id");\r
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-      mainModule.set(withValues);\r
-\r
-      logAdminUsage(aRequest, id, "object modified");\r
-\r
-      String returnUrl = requestParser.getParameter("returnurl");\r
-\r
-      if (returnUrl!=null) {\r
-        redirect(aResponse, returnUrl);\r
-      }\r
-      else {\r
-        edit(aRequest, aResponse, id);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Generic insert method\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-      Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-\r
-      String id = processInstertedObject(object, aRequest, aResponse);\r
-\r
-      logAdminUsage(aRequest, id, "object inserted");\r
-\r
-      String returnUrl = requestParser.getParameter("returnurl");\r
-\r
-      if (returnUrl!=null) {\r
-        redirect(aResponse, returnUrl);\r
-      }\r
-      else {\r
-        edit(aRequest, aResponse, id);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      return mainModule.add(anObject);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  };\r
-\r
-  /**\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   */\r
-  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      String idParam = aRequest.getParameter("id");\r
-      String confirmParam = aRequest.getParameter("confirm");\r
-      String cancelParam = aRequest.getParameter("cancel");\r
-\r
-      if (confirmParam != null && !confirmParam.equals("")) {\r
-        mainModule.deleteById(idParam);\r
-        logAdminUsage(aRequest, idParam, "object deleted");\r
-        redirect(aResponse, aRequest.getParameter("okurl"));\r
-      }\r
-      else\r
-        redirect(aResponse, aRequest.getParameter("cancelurl"));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   * @throws ServletModuleUserExc\r
-   * @throws ServletModuleFailure\r
-   */\r
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      String idParam = aRequest.getParameter("id");\r
-\r
-      if (idParam == null)\r
-        throw new ServletModuleExc("Invalid call to delete: no id supplied");\r
-\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      responseData.put("module", getOperationModuleName());\r
-      responseData.put("id", idParam);\r
-      responseData.put("cancelurl", aRequest.getParameter("cancelurl"));\r
-      responseData.put("okurl", aRequest.getParameter("okurl"));\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem\r
-   *  Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des\r
-   *  doParameters ausgefuehrt.\r
-   *\r
-   * @return Name der Default-Action\r
-   */\r
-  public String defaultAction() {\r
-    return defaultAction;\r
-  }\r
-\r
-  /**\r
-   * Gets the fields from a httprequest and matches them with the metadata from\r
-   * the storage object. Returns the keys that match, with their values.\r
-   *\r
-   * @return Map with the values\r
-   */\r
-  public Map getIntersectingValues(HttpServletRequest aRequest, StorageObject theStorage)\r
-      throws ServletModuleExc, ServletModuleFailure {\r
-\r
-    try {\r
-      HTTPRequestParser parser;\r
-      List theFieldList;\r
-\r
-      parser = new HTTPRequestParser(aRequest);\r
-\r
-      theFieldList = theStorage.getFields();\r
-\r
-      Map withValues = new HashMap();\r
-      String aField, aValue;\r
-\r
-      for (int i = 0; i < theFieldList.size(); i++) {\r
-        aField = (String) theFieldList.get(i);\r
-\r
-        aValue = parser.getParameter(aField);\r
-        if (aValue != null)\r
-          withValues.put(aField, aValue);\r
-      }\r
-      return withValues;\r
-    }\r
-    catch (Throwable e) {\r
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-\r
-      throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e);\r
-    }\r
-  }\r
+/*
+ * 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.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.config.MirPropertiesConfiguration.PropertiesConfigExc;
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.log.LoggerWrapper;
+import mir.module.AbstractModule;
+import mir.storage.StorageObject;
+import mir.util.HTTPRequestParser;
+import mir.util.URLBuilder;
+import mircoders.global.MirGlobal;
+import mircoders.servlet.ServletHelper;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public abstract class ServletModule {
+  public String defaultAction;
+  protected LoggerWrapper logger;
+  protected MirPropertiesConfiguration configuration;
+  protected Locale fallbackLocale;
+
+  protected AbstractModule mainModule;
+  protected String definition;
+  protected EntityAdapterModel model;
+
+  protected String listGenerator;
+  protected String editGenerator;
+  protected String deleteConfirmationGenerator;
+  protected int nrEntitiesPerListPage;
+
+
+  public ServletModule(){
+    definition = null;
+    model = null;
+
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (PropertiesConfigExc e) {
+      throw new RuntimeException("Can't get configuration: " + e.getMessage());
+    }
+
+    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));
+
+    fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");
+  }
+
+
+  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;
+  }
+
+  /**
+   * Get the module name
+   *
+   * @return
+   */
+  protected String getOperationModuleName() {
+    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
+  }
+
+  /**
+   * get the locale either from the session or the accept-language header ot the request
+   * this supersedes getLanguage for the new i18n
+   */
+  public Locale getLocale(HttpServletRequest aRequest) {
+    Locale loc = null;
+    HttpSession session = aRequest.getSession(false);
+    if (session != null) {
+      // session can be null in case of logout
+      loc = (Locale) session.getAttribute("locale");
+    }
+    // if there is nothing in the session get it fron the accept-language
+    if (loc == null) {
+      loc = aRequest.getLocale();
+    }
+    return loc;
+  }
+
+  /**
+   * 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().getFields().contains("webdb_create"))
+        return "webdb_create desc";
+    }
+
+    return "id asc";
+  }
+
+  /**
+   *
+   * @param aResponse
+   * @param aQuery
+   * @throws ServletModuleExc
+   * @throws ServletModuleFailure
+   */
+  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {
+    try {
+      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery));
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);
+    }
+  }
+
+  /**
+   * Generic list method
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+
+  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 {
+
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+
+      List list =
+         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
+
+      responseData.put("nexturl", null);
+      responseData.put("prevurl", null);
+      responseData.put("module", getOperationModuleName());
+
+      count=mainModule.getSize(aWhereClause);
+
+      urlBuilder.setValue("module", getOperationModuleName());
+      urlBuilder.setValue("do", "list");
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
+      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
+
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));
+      responseData.put("searchtext", requestParser.getParameter("searchtext"));
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
+      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));
+
+      urlBuilder.setValue("offset", anOffset);
+      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      if (count>anOffset+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", Integer.toString(count));
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+
+      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();
+    EntityAdapterModel model;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(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 method
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+
+    Map object = new HashMap();
+
+    Iterator i = mainModule.getStorageObject().getFields().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) {
+  }
+
+  /**
+   * Method called when the user edits an object.
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    edit(aRequest, aResponse, aRequest.getParameter("id"));
+  }
+
+  /**
+   * Generic edit method
+   *
+   * @param aRequest
+   * @param aResponse
+   * @param anIdentifier
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  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 method
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  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) {
+        redirect(aResponse, returnUrl);
+      }
+      else {
+        edit(aRequest, aResponse, id);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * Generic insert method
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  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) {
+        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 (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  };
+
+  /**
+   *
+   * @param aRequest
+   * @param aResponse
+   */
+  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      String idParam = aRequest.getParameter("id");
+      String confirmParam = aRequest.getParameter("confirm");
+      String cancelParam = aRequest.getParameter("cancel");
+
+      if (confirmParam != null && !confirmParam.equals("")) {
+        mainModule.deleteById(idParam);
+        logAdminUsage(aRequest, idParam, "object deleted");
+        redirect(aResponse, aRequest.getParameter("okurl"));
+      }
+      else
+        redirect(aResponse, aRequest.getParameter("cancelurl"));
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  /**
+   *
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
+   */
+  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, new Locale[] { getLocale(aRequest), getFallbackLocale(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);
+    }
+  }
+
+  /**
+   *  Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem
+   *  Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des
+   *  doParameters ausgefuehrt.
+   *
+   * @return Name der Default-Action
+   */
+  public String defaultAction() {
+    return defaultAction;
+  }
+
+  /**
+   * Gets the fields from a httprequest and matches them with the metadata from
+   * the storage object. Returns the keys that match, with their values.
+   *
+   * @return Map with the values
+   */
+  public Map getIntersectingValues(HttpServletRequest aRequest, StorageObject theStorage)
+      throws ServletModuleExc, ServletModuleFailure {
+
+    try {
+      HTTPRequestParser parser;
+      List theFieldList;
+
+      parser = new HTTPRequestParser(aRequest);
+
+      theFieldList = theStorage.getFields();
+
+      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;
+    }
+    catch (Throwable e) {
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+
+      throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e);
+    }
+  }
 }
\ No newline at end of file
index 319a8c8..5dcc510 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.session;\r
-\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Vector;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import org.apache.commons.fileupload.FileItem;\r
-\r
-import mir.util.HTTPParsedRequest;\r
-\r
-public class HTTPAdapters {\r
-  public static class HTTPRequestAdapter implements Request {\r
-    private HttpServletRequest request;\r
-\r
-    public HTTPRequestAdapter(HttpServletRequest aRequest) {\r
-      request = aRequest;\r
-    }\r
-\r
-    public String getHeader(String aHeaderName) {\r
-      if (aHeaderName.equals("ip"))\r
-        return request.getRemoteAddr();\r
-\r
-      return request.getHeader(aHeaderName);\r
-    };\r
-\r
-    public String getParameter(String aName) {\r
-      return request.getParameter(aName);\r
-    };\r
-\r
-    public List getUploadedFiles() {\r
-      return new Vector();\r
-    };\r
-\r
-    public List getParameters(String aName) {\r
-      return Arrays.asList(request.getParameterValues(aName));\r
-    };\r
-\r
-    public HttpServletRequest getRequest() {\r
-      return request;\r
-    }\r
-  }\r
-\r
-  public static class HTTPParsedRequestAdapter implements Request {\r
-    private HTTPParsedRequest request;\r
-\r
-    public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {\r
-      request = aRequest;\r
-    }\r
-\r
-    public String getHeader(String aHeaderName) {\r
-      if (aHeaderName.equals("ip"))\r
-        return request.getRequest().getRemoteAddr();\r
-\r
-      return request.getHeader(aHeaderName);\r
-    };\r
-\r
-    public String getParameter(String aName) {\r
-      return request.getParameter(aName);\r
-    };\r
-\r
-    public List getParameters(String aName) {\r
-      return request.getParameterList(aName);\r
-    };\r
-\r
-    public List getUploadedFiles() {\r
-      List result = new Vector();\r
-      List files = request.getFiles();\r
-\r
-      for (int i=0; i<files.size(); i++) {\r
-        result.add(new CommonsUploadedFileAdapter((FileItem) files.get(i)));\r
-      }\r
-\r
-      return result;\r
-    };\r
-\r
-    public HttpServletRequest getRequest() {\r
-      return request.getRequest();\r
-    }\r
-  }\r
-\r
-  public static class HTTPSessionAdapter implements Session {\r
-    private HttpSession session;\r
-\r
-    public HTTPSessionAdapter(HttpSession aSession) {\r
-      session = aSession;\r
-    }\r
-    public Object getAttribute(String aName) {\r
-      return session.getAttribute(aName);\r
-    }\r
-\r
-    public void deleteAttribute(String aName) {\r
-      session.removeAttribute(aName);\r
-    }\r
-\r
-    public void setAttribute(String aName, Object aNewValue) {\r
-      if (aName.equals("$httpsessiontimeout")) {\r
-        if (aNewValue instanceof Number) {\r
-          try {\r
-            session.setMaxInactiveInterval( ( (Number) aNewValue).intValue());\r
-          }\r
-          catch (Throwable t) {\r
-          }\r
-        }\r
-      }\r
-      else {\r
-        if (aNewValue == null)\r
-          deleteAttribute(aName);\r
-        else\r
-          session.setAttribute(aName, aNewValue);\r
-      }\r
-    }\r
-\r
-    public void terminate() {\r
-      session.invalidate();\r
-    }\r
-  }\r
+/*
+ * 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.session;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import mir.util.HTTPParsedRequest;
+
+import org.apache.commons.fileupload.FileItem;
+
+public class HTTPAdapters {
+  public static class HTTPRequestAdapter implements Request {
+    private HttpServletRequest request;
+
+    public HTTPRequestAdapter(HttpServletRequest aRequest) {
+      request = aRequest;
+    }
+
+    public String getHeader(String aHeaderName) {
+      if (aHeaderName.equals("ip"))
+        return request.getRemoteAddr();
+
+      return request.getHeader(aHeaderName);
+    };
+
+    public String getParameter(String aName) {
+      return request.getParameter(aName);
+    };
+
+    public List getUploadedFiles() {
+      return new Vector();
+    };
+
+    public List getParameters(String aName) {
+      return Arrays.asList(request.getParameterValues(aName));
+    };
+
+    public HttpServletRequest getRequest() {
+      return request;
+    }
+  }
+
+  public static class HTTPParsedRequestAdapter implements Request {
+    private HTTPParsedRequest request;
+
+    public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {
+      request = aRequest;
+    }
+
+    public String getHeader(String aHeaderName) {
+      if (aHeaderName.equals("ip"))
+        return request.getRequest().getRemoteAddr();
+
+      return request.getHeader(aHeaderName);
+    };
+
+    public String getParameter(String aName) {
+      return request.getParameter(aName);
+    };
+
+    public List getParameters(String aName) {
+      return request.getParameterList(aName);
+    };
+
+    public List getUploadedFiles() {
+      List result = new Vector();
+      List files = request.getFiles();
+
+      for (int i=0; i<files.size(); i++) {
+        result.add(new CommonsUploadedFileAdapter((FileItem) files.get(i)));
+      }
+
+      return result;
+    };
+
+    public HttpServletRequest getRequest() {
+      return request.getRequest();
+    }
+  }
+
+  public static class HTTPSessionAdapter implements Session {
+    private HttpSession session;
+
+    public HTTPSessionAdapter(HttpSession aSession) {
+      session = aSession;
+    }
+    public Object getAttribute(String aName) {
+      return session.getAttribute(aName);
+    }
+
+    public void deleteAttribute(String aName) {
+      session.removeAttribute(aName);
+    }
+
+    public void setAttribute(String aName, Object aNewValue) {
+      if (aName.equals("$httpsessiontimeout")) {
+        if (aNewValue instanceof Number) {
+          try {
+            session.setMaxInactiveInterval( ( (Number) aNewValue).intValue());
+          }
+          catch (Throwable t) {
+          }
+        }
+      }
+      else {
+        if (aNewValue == null)
+          deleteAttribute(aName);
+        else
+          session.setAttribute(aName, aNewValue);
+      }
+    }
+
+    public void terminate() {
+      session.invalidate();
+    }
+  }
 }
\ No newline at end of file
index 015b9ab..9ac7e08 100755 (executable)
@@ -32,9 +32,6 @@ package mir.session;
 
 import java.util.List;
 
-import mir.session.Request;
-import mir.session.ValidationError;
-
 
 public class ValidationHelper {
   /**
index e2a678e..a4b3e37 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.storage;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStreamReader;\r
-import java.sql.Connection;\r
-import java.sql.PreparedStatement;\r
-import java.sql.ResultSet;\r
-import java.sql.ResultSetMetaData;\r
-import java.sql.SQLException;\r
-import java.sql.Statement;\r
-import java.sql.Timestamp;\r
-import java.text.ParseException;\r
-import java.text.SimpleDateFormat;\r
-import java.util.ArrayList;\r
-import java.util.Calendar;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.TimeZone;\r
-import java.util.Vector;\r
-\r
-import com.codestudio.util.SQLManager;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
-import mir.entity.Entity;\r
-import mir.entity.EntityList;\r
-import mir.entity.StorableObjectEntity;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.storage.store.ObjectStore;\r
-import mir.storage.store.StorableObject;\r
-import mir.storage.store.StoreContainerType;\r
-import mir.storage.store.StoreIdentifier;\r
-import mir.storage.store.StoreUtil;\r
-import mir.util.JDBCStringRoutines;\r
-\r
-\r
-/**\r
- * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.\r
- * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.\r
- * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.\r
- * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten\r
- * Treiber, Host, User und Passwort, ueber den der Zugriff auf die\r
- * Datenbank erfolgt.\r
- *\r
- * @version $Id: Database.java,v 1.44.2.6 2003/09/03 17:49:39 zapata Exp $\r
- * @author rk\r
- *\r
- */\r
-public class Database implements StorageObject {\r
-  private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
-  private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
-\r
-\r
-  private static Map POPUP_EMPTYLINE = new HashMap();\r
-  protected static final ObjectStore o_store = ObjectStore.getInstance();\r
-  private static final int _millisPerHour = 60 * 60 * 1000;\r
-  private static final int _millisPerMinute = 60 * 1000;\r
-\r
-  static {\r
-    // always same object saves a little space\r
-    POPUP_EMPTYLINE.put("key", "");\r
-    POPUP_EMPTYLINE.put("value", "--");\r
-  }\r
-\r
-  protected LoggerWrapper logger;\r
-  protected MirPropertiesConfiguration configuration;\r
-  protected String theTable;\r
-  protected String theCoreTable = null;\r
-  protected String thePKeyName = "id";\r
-  protected int thePKeyType;\r
-  protected int thePKeyIndex;\r
-  protected boolean evaluatedMetaData = false;\r
-  protected ArrayList metadataFields;\r
-  protected ArrayList metadataLabels;\r
-  protected ArrayList metadataNotNullFields;\r
-  protected int[] metadataTypes;\r
-  protected Class theEntityClass;\r
-  protected List popupCache = null;\r
-  protected boolean hasPopupCache = false;\r
-  protected Map hashCache = null;\r
-  protected boolean hasTimestamp = true;\r
-  private String database_driver;\r
-  private String database_url;\r
-  private int defaultLimit;\r
-\r
-  TimeZone timezone;\r
-  SimpleDateFormat internalDateFormat;\r
-  SimpleDateFormat userInputDateFormat;\r
-/*\r
-  private SimpleDateFormat _dateFormatterOut;\r
-  private SimpleDateFormat _dateFormatterIn;\r
-  _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
-  _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");\r
-*/\r
-\r
-  /**\r
-   * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.\r
-   * Aus diesem file werden <code>Database.Logfile</code>,\r
-   * <code>Database.Username</code>,<code>Database.Password</code>,\r
-   * <code>Database.Host</code> und <code>Database.Adaptor</code>\r
-   * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank\r
-   * erzeugt.\r
-   *\r
-   * @param   String confFilename Dateiname der Konfigurationsdatei\r
-   */\r
-  public Database() throws StorageObjectFailure {\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (PropertiesConfigExc e) {\r
-      throw new StorageObjectFailure(e);\r
-    }\r
-    logger = new LoggerWrapper("Database");\r
-    timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));\r
-    internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
-    internalDateFormat.setTimeZone(timezone);\r
-\r
-    userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");\r
-    userInputDateFormat.setTimeZone(timezone);\r
-\r
-\r
-    String theAdaptorName = configuration.getString("Database.Adaptor");\r
-    defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));\r
-\r
-    try {\r
-      theEntityClass = GENERIC_ENTITY_CLASS;\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());\r
-      throw new StorageObjectFailure("Error in Database() constructor.", e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt\r
-   * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,\r
-   * wird eine mir.entity.GenericEntity erzeugt.\r
-   *\r
-   * @return Class-Objekt der Entity\r
-   */\r
-  public java.lang.Class getEntityClass() {\r
-    return theEntityClass;\r
-  }\r
-\r
-  /**\r
-   * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also\r
-   * wieviel Datens?tze per Default selektiert werden.\r
-   *\r
-   * @return Standard-Anzahl der Datens?tze\r
-   */\r
-  public int getLimit() {\r
-    return defaultLimit;\r
-  }\r
-\r
-  /**\r
-   * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von\r
-   * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>\r
-   * @return Name des Primary-Keys\r
-   */\r
-  public String getIdName() {\r
-    return thePKeyName;\r
-  }\r
-\r
-  /**\r
-   * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.\r
-   *\r
-   * @return Name der Tabelle\r
-   */\r
-  public String getTableName() {\r
-    return theTable;\r
-  }\r
-\r
-  /*\r
-  *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS\r
-  *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet\r
-  *   wird.\r
-  *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst\r
-  *    the Table\r
-   */\r
-  public String getCoreTable() {\r
-    if (theCoreTable != null) {\r
-      return theCoreTable;\r
-    }\r
-    else {\r
-      return theTable;\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)\r
-   * @return int-Array mit den Typen der Felder\r
-   * @exception StorageObjectException\r
-   */\r
-  public int[] getTypes() throws StorageObjectFailure {\r
-    if (metadataTypes == null) {\r
-      get_meta_data();\r
-    }\r
-\r
-    return metadataTypes;\r
-  }\r
-\r
-  /**\r
-   * Liefert eine Liste der Labels der Tabellenfelder\r
-   * @return ArrayListe mit Labeln\r
-   * @exception StorageObjectException\r
-   */\r
-  public List getLabels() throws StorageObjectFailure {\r
-    if (metadataLabels == null) {\r
-      get_meta_data();\r
-    }\r
-\r
-    return metadataLabels;\r
-  }\r
-\r
-  /**\r
-   * Liefert eine Liste der Felder der Tabelle\r
-   * @return ArrayList mit Feldern\r
-   * @exception StorageObjectException\r
-   */\r
-  public List getFields() throws StorageObjectFailure {\r
-    if (metadataFields == null) {\r
-      get_meta_data();\r
-    }\r
-\r
-    return metadataFields;\r
-  }\r
-\r
-  /*\r
-  *   Gets value out of ResultSet according to type and converts to String\r
-  *   @param inValue  Wert aus ResultSet.\r
-  *   @param aType  Datenbanktyp.\r
-  *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich\r
-  *           dann /unsupported value/\r
-   */\r
-  private String getValueAsString(ResultSet rs, int valueIndex, int aType)\r
-    throws StorageObjectFailure {\r
-    String outValue = null;\r
-\r
-    if (rs != null) {\r
-      try {\r
-        switch (aType) {\r
-          case java.sql.Types.BIT:\r
-            outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";\r
-\r
-            break;\r
-\r
-          case java.sql.Types.INTEGER:\r
-          case java.sql.Types.SMALLINT:\r
-          case java.sql.Types.TINYINT:\r
-          case java.sql.Types.BIGINT:\r
-\r
-            int out = rs.getInt(valueIndex);\r
-\r
-            if (!rs.wasNull()) {\r
-              outValue = new Integer(out).toString();\r
-            }\r
-\r
-            break;\r
-\r
-          case java.sql.Types.NUMERIC:\r
-\r
-            /** @todo Numeric can be float or double depending upon\r
-             *  metadata.getScale() / especially with oracle */\r
-            long outl = rs.getLong(valueIndex);\r
-\r
-            if (!rs.wasNull()) {\r
-              outValue = new Long(outl).toString();\r
-            }\r
-\r
-            break;\r
-\r
-          case java.sql.Types.REAL:\r
-\r
-            float tempf = rs.getFloat(valueIndex);\r
-\r
-            if (!rs.wasNull()) {\r
-              tempf *= 10;\r
-              tempf += 0.5;\r
-\r
-              int tempf_int = (int) tempf;\r
-              tempf = (float) tempf_int;\r
-              tempf /= 10;\r
-              outValue = "" + tempf;\r
-              outValue = outValue.replace('.', ',');\r
-            }\r
-\r
-            break;\r
-\r
-          case java.sql.Types.DOUBLE:\r
-\r
-            double tempd = rs.getDouble(valueIndex);\r
-\r
-            if (!rs.wasNull()) {\r
-              tempd *= 10;\r
-              tempd += 0.5;\r
-\r
-              int tempd_int = (int) tempd;\r
-              tempd = (double) tempd_int;\r
-              tempd /= 10;\r
-              outValue = "" + tempd;\r
-              outValue = outValue.replace('.', ',');\r
-            }\r
-\r
-            break;\r
-\r
-          case java.sql.Types.CHAR:\r
-          case java.sql.Types.VARCHAR:\r
-          case java.sql.Types.LONGVARCHAR:\r
-            outValue = rs.getString(valueIndex);\r
-\r
-            break;\r
-\r
-          case java.sql.Types.LONGVARBINARY:\r
-            outValue = rs.getString(valueIndex);\r
-\r
-            break;\r
-\r
-          case java.sql.Types.TIMESTAMP:\r
-\r
-            // it's important to use Timestamp here as getting it\r
-            // as a string is undefined and is only there for debugging\r
-            // according to the API. we can make it a string through formatting.\r
-            // -mh\r
-            Timestamp timestamp = (rs.getTimestamp(valueIndex));\r
-\r
-            if (!rs.wasNull()) {\r
-              java.util.Date date = new java.util.Date(timestamp.getTime());\r
-\r
-              Calendar calendar = new GregorianCalendar();\r
-              calendar.setTime(date);\r
-              calendar.setTimeZone(timezone);\r
-              outValue = internalDateFormat.format(date);\r
-\r
-              int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);\r
-              String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);\r
-\r
-              if (offset<0)\r
-                outValue = outValue + "-";\r
-              else\r
-                outValue = outValue + "+";\r
-              outValue = outValue + tzOffset;\r
-            }\r
-\r
-            break;\r
-\r
-          default:\r
-            outValue = "<unsupported value>";\r
-            logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");\r
-        }\r
-      } catch (SQLException e) {\r
-        throw new StorageObjectFailure("Could not get Value out of Resultset -- ",\r
-          e);\r
-      }\r
-    }\r
-\r
-    return outValue;\r
-  }\r
-\r
-  /*\r
-  *   select-Operator um einen Datensatz zu bekommen.\r
-  *   @param id Primaerschluessel des Datensatzes.\r
-  *   @return liefert EntityObject des gefundenen Datensatzes oder null.\r
-   */\r
-  public Entity selectById(String id) throws StorageObjectExc {\r
-    if ((id == null) || id.equals("")) {\r
-      throw new StorageObjectExc("Database.selectById: Missing id");\r
-    }\r
-\r
-    // ask object store for object\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      String uniqueId = id;\r
-\r
-      if (theEntityClass.equals(StorableObjectEntity.class)) {\r
-        uniqueId += ("@" + theTable);\r
-      }\r
-\r
-      StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);\r
-      logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());\r
-\r
-      Entity hit = (Entity) o_store.use(search_sid);\r
-\r
-      if (hit != null) {\r
-        return hit;\r
-      }\r
-    }\r
-\r
-    Statement stmt = null;\r
-    Connection con = getPooledCon();\r
-    Entity returnEntity = null;\r
-\r
-    try {\r
-      ResultSet rs;\r
-\r
-      /** @todo better prepared statement */\r
-      String selectSql =\r
-        "select * from " + theTable + " where " + thePKeyName + "=" + id;\r
-      stmt = con.createStatement();\r
-      rs = executeSql(stmt, selectSql);\r
-\r
-      if (rs != null) {\r
-        if (evaluatedMetaData == false) {\r
-          evalMetaData(rs.getMetaData());\r
-        }\r
-\r
-        if (rs.next()) {\r
-          returnEntity = makeEntityFromResultSet(rs);\r
-        }\r
-        else {\r
-          logger.debug("No data for id: " + id + " in table " + theTable);\r
-        }\r
-\r
-        rs.close();\r
-      }\r
-      else {\r
-        logger.debug("No Data for Id " + id + " in Table " + theTable);\r
-      }\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "selectById");\r
-      return null;\r
-    }\r
-    catch (NumberFormatException e) {\r
-      logger.error("ID is no number: " + id);\r
-    }\r
-    finally {\r
-      freeConnection(con, stmt);\r
-    }\r
-\r
-    return returnEntity;\r
-  }\r
-\r
-  /**\r
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
-   *   @param key  Datenbankfeld der Bedingung.\r
-   *   @param value  Wert die der key anehmen muss.\r
-   *   @return EntityList mit den gematchten Entities\r
-   */\r
-  public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {\r
-    return selectByFieldValue(aField, aValue, 0);\r
-  }\r
-\r
-  /**\r
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
-   *   @param key  Datenbankfeld der Bedingung.\r
-   *   @param value  Wert die der key anehmen muss.\r
-   *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.\r
-   *   @return EntityList mit den gematchten Entities\r
-   */\r
-  public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {\r
-    return selectByWhereClause(aField + "=" + aValue, offset);\r
-  }\r
-\r
-  /**\r
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
-   * Also offset wird der erste Datensatz genommen.\r
-   *\r
-   * @param wc where-Clause\r
-   * @return EntityList mit den gematchten Entities\r
-   * @exception StorageObjectException\r
-   */\r
-  public EntityList selectByWhereClause(String where) throws StorageObjectFailure {\r
-    return selectByWhereClause(where, 0);\r
-  }\r
-\r
-  /**\r
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
-   *\r
-   * @param wc where-Clause\r
-   * @param offset ab welchem Datensatz.\r
-   * @return EntityList mit den gematchten Entities\r
-   * @exception StorageObjectException\r
-   */\r
-  public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {\r
-    return selectByWhereClause(whereClause, null, offset);\r
-  }\r
-\r
-  /**\r
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
-   * Also offset wird der erste Datensatz genommen.\r
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
-   *\r
-   * @param wc where-Clause\r
-   * @param ob orderBy-Clause\r
-   * @return EntityList mit den gematchten Entities\r
-   * @exception StorageObjectException\r
-   */\r
-  public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {\r
-    return selectByWhereClause(where, order, 0);\r
-  }\r
-\r
-  /**\r
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
-   *\r
-   * @param wc where-Clause\r
-   * @param ob orderBy-Clause\r
-   * @param offset ab welchem Datensatz\r
-   * @return EntityList mit den gematchten Entities\r
-   * @exception StorageObjectException\r
-   */\r
-  public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {\r
-    return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);\r
-  }\r
-\r
-  /**\r
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
-   * @param aWhereClause where-Clause\r
-   * @param anOrderByClause orderBy-Clause\r
-   * @param offset ab welchem Datensatz\r
-   * @param limit wieviele Datens?tze\r
-   * @return EntityList mit den gematchten Entities\r
-   * @exception StorageObjectException\r
-   */\r
-  public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,\r
-            int offset, int limit) throws StorageObjectFailure {\r
-\r
-    // check o_store for entitylist\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      StoreIdentifier search_sid =\r
-          new StoreIdentifier(\r
-            theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,\r
-            StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));\r
-      EntityList hit = (EntityList) o_store.use(search_sid);\r
-\r
-      if (hit != null) {\r
-        logger.debug("CACHE (hit): " + search_sid.toString());\r
-\r
-        return hit;\r
-      }\r
-    }\r
-\r
-    // local\r
-    EntityList theReturnList = null;\r
-    Connection con = null;\r
-    Statement stmt = null;\r
-    ResultSet rs;\r
-    int offsetCount = 0;\r
-    int count = 0;\r
-\r
-    // build sql-statement\r
-\r
-    /** @todo count sql string should only be assembled if we really count\r
-     *  see below at the end of method //rk */\r
-    if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {\r
-      aWhereClause = null;\r
-    }\r
-\r
-    StringBuffer countSql =\r
-      new StringBuffer("select count(*) from ").append(theTable);\r
-    StringBuffer selectSql =\r
-      new StringBuffer("select * from ").append(theTable);\r
-\r
-    if (aWhereClause != null) {\r
-      selectSql.append(" where ").append(aWhereClause);\r
-      countSql.append(" where ").append(aWhereClause);\r
-    }\r
-\r
-    if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {\r
-      selectSql.append(" order by ").append(anOrderByClause);\r
-    }\r
-\r
-    if ((limit > -1) && (offset > -1)) {\r
-      selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);\r
-    }\r
-\r
-    // execute sql\r
-    try {\r
-      con = getPooledCon();\r
-      stmt = con.createStatement();\r
-\r
-      // selecting...\r
-      rs = executeSql(stmt, selectSql.toString());\r
-\r
-      if (rs != null) {\r
-        if (!evaluatedMetaData) {\r
-          evalMetaData(rs.getMetaData());\r
-        }\r
-\r
-        theReturnList = new EntityList();\r
-\r
-        Entity theResultEntity;\r
-\r
-        while (rs.next()) {\r
-          theResultEntity = makeEntityFromResultSet(rs);\r
-          theReturnList.add(theResultEntity);\r
-          offsetCount++;\r
-        }\r
-\r
-        rs.close();\r
-      }\r
-\r
-      // making entitylist infos\r
-      count = offsetCount;\r
-\r
-      if (theReturnList != null) {\r
-        // now we decide if we have to know an overall count...\r
-        count = offsetCount;\r
-\r
-        if ((limit > -1) && (offset > -1)) {\r
-          if (offsetCount == limit) {\r
-            /** @todo counting should be deffered to entitylist\r
-             *  getSize() should be used */\r
-            rs = executeSql(stmt, countSql.toString());\r
-\r
-            if (rs != null) {\r
-              if (rs.next()) {\r
-                count = rs.getInt(1);\r
-              }\r
-\r
-              rs.close();\r
-            }\r
-            else {\r
-              logger.error("Could not count: " + countSql);\r
-            }\r
-          }\r
-        }\r
-\r
-        theReturnList.setCount(count);\r
-        theReturnList.setOffset(offset);\r
-        theReturnList.setWhere(aWhereClause);\r
-        theReturnList.setOrder(anOrderByClause);\r
-        theReturnList.setStorage(this);\r
-        theReturnList.setLimit(limit);\r
-\r
-        if (offset >= limit) {\r
-          theReturnList.setPrevBatch(offset - limit);\r
-        }\r
-\r
-        if ((offset + offsetCount) < count) {\r
-          theReturnList.setNextBatch(offset + limit);\r
-        }\r
-\r
-        if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-          StoreIdentifier sid = theReturnList.getStoreIdentifier();\r
-          logger.debug("CACHE (add): " + sid.toString());\r
-          o_store.add(sid);\r
-        }\r
-      }\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "selectByWhereClause");\r
-    }\r
-    finally {\r
-      try {\r
-        if (con != null) {\r
-          freeConnection(con, stmt);\r
-        }\r
-      } catch (Throwable t) {\r
-      }\r
-    }\r
-\r
-    return theReturnList;\r
-  }\r
-\r
-  /**\r
-   *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.\r
-   *\r
-   *  @param rs Das ResultSetObjekt.\r
-   *  @return Entity Die Entity.\r
-   */\r
-  private Entity makeEntityFromResultSet(ResultSet rs)\r
-    throws StorageObjectFailure {\r
-    /** @todo OS: get Pkey from ResultSet and consult ObjectStore */\r
-    Map theResultHash = new HashMap();\r
-    String theResult = null;\r
-    int theType;\r
-    Entity returnEntity = null;\r
-\r
-    try {\r
-      int size = metadataFields.size();\r
-\r
-      for (int i = 0; i < size; i++) {\r
-        // alle durchlaufen bis nix mehr da\r
-        theType = metadataTypes[i];\r
-\r
-        if (theType == java.sql.Types.LONGVARBINARY) {\r
-          InputStreamReader is =\r
-            (InputStreamReader) rs.getCharacterStream(i + 1);\r
-\r
-          if (is != null) {\r
-            char[] data = new char[32768];\r
-            StringBuffer theResultString = new StringBuffer();\r
-            int len;\r
-\r
-            while ((len = is.read(data)) > 0) {\r
-              theResultString.append(data, 0, len);\r
-            }\r
-\r
-            is.close();\r
-            theResult = theResultString.toString();\r
-          } else {\r
-            theResult = null;\r
-          }\r
-        } else {\r
-          theResult = getValueAsString(rs, (i + 1), theType);\r
-        }\r
-\r
-        if (theResult != null) {\r
-          theResultHash.put(metadataFields.get(i), theResult);\r
-        }\r
-      }\r
-\r
-      if (theEntityClass != null) {\r
-        returnEntity = (Entity) theEntityClass.newInstance();\r
-        returnEntity.setStorage(this);\r
-        returnEntity.setValues(theResultHash);\r
-\r
-        if (returnEntity instanceof StorableObject) {\r
-          logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);\r
-          o_store.add(((StorableObject) returnEntity).getStoreIdentifier());\r
-        }\r
-      } else {\r
-        throwStorageObjectException("Internal Error: theEntityClass not set!");\r
-      }\r
-    }\r
-    catch (IllegalAccessException e) {\r
-      throwStorageObjectException("No access! -- " + e.getMessage());\r
-    }\r
-    catch (IOException e) {\r
-      throwStorageObjectException("IOException! -- " + e.getMessage());\r
-    }\r
-    catch (InstantiationException e) {\r
-      throwStorageObjectException("No Instatiation! -- " + e.getMessage());\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "makeEntityFromResultSet");\r
-\r
-      return null;\r
-    }\r
-\r
-    return returnEntity;\r
-  }\r
-\r
-  /**\r
-   * Inserts an entity into the database.\r
-   *\r
-   * @param theEntity\r
-   * @return der Wert des Primary-keys der eingef?gten Entity\r
-   */\r
-  public String insert(Entity theEntity) throws StorageObjectFailure {\r
-    //cache\r
-    invalidatePopupCache();\r
-\r
-    // invalidating all EntityLists corresponding with theEntityClass\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      StoreContainerType stoc_type =\r
-        StoreContainerType.valueOf(theEntityClass,\r
-          StoreContainerType.STOC_TYPE_ENTITYLIST);\r
-      o_store.invalidate(stoc_type);\r
-    }\r
-\r
-    String returnId = null;\r
-    Connection con = null;\r
-    PreparedStatement pstmt = null;\r
-\r
-    try {\r
-      List streamedInput = theEntity.streamedInput();\r
-      StringBuffer f = new StringBuffer();\r
-      StringBuffer v = new StringBuffer();\r
-      String aField;\r
-      String aValue;\r
-      boolean firstField = true;\r
-\r
-      // make sql-string\r
-      for (int i = 0; i < getFields().size(); i++) {\r
-        aField = (String) getFields().get(i);\r
-\r
-        if (!aField.equals(thePKeyName)) {\r
-          aValue = null;\r
-\r
-          // exceptions\r
-          if (!theEntity.hasValueForField(aField) && (\r
-              aField.equals("webdb_create") ||\r
-              aField.equals("webdb_lastchange"))) {\r
-            aValue = "NOW()";\r
-          }\r
-          else {\r
-            if ((streamedInput != null) && streamedInput.contains(aField)) {\r
-              aValue = "?";\r
-            }\r
-            else {\r
-              if (theEntity.hasValueForField(aField)) {\r
-                aValue =\r
-                  "'" +\r
-                   JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";\r
-              }\r
-            }\r
-          }\r
-\r
-          // wenn Wert gegeben, dann einbauen\r
-          if (aValue != null) {\r
-            if (firstField == false) {\r
-              f.append(",");\r
-              v.append(",");\r
-            }\r
-            else {\r
-              firstField = false;\r
-            }\r
-\r
-            f.append(aField);\r
-            v.append(aValue);\r
-          }\r
-        }\r
-      }\r
-       // end for\r
-\r
-      // insert into db\r
-      StringBuffer sqlBuf =\r
-        new StringBuffer("insert into ").append(theTable).append("(").append(f)\r
-                                        .append(") values (").append(v).append(")");\r
-      String sql = sqlBuf.toString();\r
-\r
-      logger.debug("INSERT: " + sql);\r
-      con = getPooledCon();\r
-      con.setAutoCommit(false);\r
-      pstmt = con.prepareStatement(sql);\r
-\r
-      if (streamedInput != null) {\r
-        for (int i = 0; i < streamedInput.size(); i++) {\r
-          String inputString =\r
-            (String) theEntity.getValue((String) streamedInput.get(i));\r
-          pstmt.setBytes(i + 1, inputString.getBytes());\r
-        }\r
-      }\r
-\r
-      int ret = pstmt.executeUpdate();\r
-\r
-      if (ret == 0) {\r
-        //insert failed\r
-        return null;\r
-      }\r
-\r
-      pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");\r
-\r
-      ResultSet rs = pstmt.executeQuery();\r
-      rs.next();\r
-      returnId = rs.getString(1);\r
-      theEntity.setId(returnId);\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "insert");\r
-    }\r
-    finally {\r
-      try {\r
-        con.setAutoCommit(true);\r
-      }\r
-      catch (Exception e) {\r
-      }\r
-\r
-      freeConnection(con, pstmt);\r
-    }\r
-\r
-    /** @todo store entity in o_store */\r
-    return returnId;\r
-  }\r
-\r
-  /**\r
-   * Updates an entity in the database\r
-   *\r
-   * @param theEntity\r
-   */\r
-  public void update(Entity theEntity) throws StorageObjectFailure {\r
-    Connection con = null;\r
-    PreparedStatement pstmt = null;\r
-\r
-    /** @todo this is stupid: why do we prepare statement, when we\r
-     *  throw it away afterwards. should be regular statement\r
-     *  update/insert could better be one routine called save()\r
-     *  that chooses to either insert or update depending if we\r
-     *  have a primary key in the entity. i don't know if we\r
-     *  still need the streamed input fields. // rk  */\r
-    /** @todo extension: check if Entity did change, otherwise we don't need\r
-     *  the roundtrip to the database */\r
-    /** invalidating corresponding entitylists in o_store*/\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      StoreContainerType stoc_type =\r
-        StoreContainerType.valueOf(theEntityClass,\r
-          StoreContainerType.STOC_TYPE_ENTITYLIST);\r
-      o_store.invalidate(stoc_type);\r
-    }\r
-\r
-    List streamedInput = theEntity.streamedInput();\r
-    String id = theEntity.getId();\r
-    String aField;\r
-    StringBuffer fv = new StringBuffer();\r
-    boolean firstField = true;\r
-\r
-    //cache\r
-    invalidatePopupCache();\r
-\r
-    // build sql statement\r
-    for (int i = 0; i < getFields().size(); i++) {\r
-      aField = (String) metadataFields.get(i);\r
-\r
-      // only normal cases\r
-      if (  !(aField.equals(thePKeyName) ||\r
-            aField.equals("webdb_create") ||\r
-            aField.equals("webdb_lastchange") ||\r
-            ((streamedInput != null) && streamedInput.contains(aField)))) {\r
-        if (theEntity.hasValueForField(aField)) {\r
-          if (firstField == false) {\r
-            fv.append(", ");\r
-          }\r
-          else {\r
-            firstField = false;\r
-          }\r
-\r
-          fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");\r
-\r
-          //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");\r
-        }\r
-      }\r
-    }\r
-\r
-    StringBuffer sql =\r
-      new StringBuffer("update ").append(theTable).append(" set ").append(fv);\r
-\r
-    // exceptions\r
-    if (metadataFields.contains("webdb_lastchange")) {\r
-      sql.append(",webdb_lastchange=NOW()");\r
-    }\r
-\r
-    // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm\r
-    // format so anything extra will be ignored. -mh\r
-    if (metadataFields.contains("webdb_create") &&\r
-        theEntity.hasValueForField("webdb_create")) {\r
-      // minimum of 10 (yyyy-mm-dd)...\r
-      if (theEntity.getValue("webdb_create").length() >= 10) {\r
-        String dateString = theEntity.getValue("webdb_create");\r
-\r
-        // if only 10, then add 00:00 so it doesn't throw a ParseException\r
-        if (dateString.length() == 10) {\r
-          dateString = dateString + " 00:00";\r
-        }\r
-\r
-        // TimeStamp stuff\r
-        try {\r
-          java.util.Date d = userInputDateFormat.parse(dateString);\r
-//          Timestamp tStamp = new Timestamp(d.getTime());\r
-          sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");\r
-        }\r
-        catch (ParseException e) {\r
-          throw new StorageObjectFailure(e);\r
-        }\r
-      }\r
-    }\r
-\r
-    if (streamedInput != null) {\r
-      for (int i = 0; i < streamedInput.size(); i++) {\r
-        sql.append(",").append(streamedInput.get(i)).append("=?");\r
-      }\r
-    }\r
-\r
-    sql.append(" where id=").append(id);\r
-    logger.debug("UPDATE: " + sql);\r
-\r
-    try {\r
-      con = getPooledCon();\r
-      con.setAutoCommit(false);\r
-      pstmt = con.prepareStatement(sql.toString());\r
-\r
-      if (streamedInput != null) {\r
-        for (int i = 0; i < streamedInput.size(); i++) {\r
-          String inputString =\r
-            theEntity.getValue((String) streamedInput.get(i));\r
-          pstmt.setBytes(i + 1, inputString.getBytes());\r
-        }\r
-      }\r
-\r
-      pstmt.executeUpdate();\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "update");\r
-    }\r
-    finally {\r
-      try {\r
-        con.setAutoCommit(true);\r
-      }\r
-      catch (Exception e) {\r
-        ;\r
-      }\r
-\r
-      freeConnection(con, pstmt);\r
-    }\r
-  }\r
-\r
-  /*\r
-  *   delete-Operator\r
-  *   @param id des zu loeschenden Datensatzes\r
-  *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.\r
-   */\r
-  public boolean delete(String id) throws StorageObjectFailure {\r
-    invalidatePopupCache();\r
-\r
-    // ostore send notification\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      String uniqueId = id;\r
-\r
-      if (theEntityClass.equals(StorableObjectEntity.class)) {\r
-        uniqueId += ("@" + theTable);\r
-      }\r
-\r
-      logger.debug("CACHE: (del) " + id);\r
-\r
-      StoreIdentifier search_sid =\r
-        new StoreIdentifier(theEntityClass,\r
-          StoreContainerType.STOC_TYPE_ENTITY, uniqueId);\r
-      o_store.invalidate(search_sid);\r
-    }\r
-\r
-    /** @todo could be prepared Statement */\r
-    Statement stmt = null;\r
-    Connection con = null;\r
-    int res = 0;\r
-    String sql =\r
-      "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";\r
-\r
-    //theLog.printInfo("DELETE " + sql);\r
-    try {\r
-      con = getPooledCon();\r
-      stmt = con.createStatement();\r
-      res = stmt.executeUpdate(sql);\r
-    } catch (SQLException sqe) {\r
-      throwSQLException(sqe, "delete");\r
-    } finally {\r
-      freeConnection(con, stmt);\r
-    }\r
-\r
-    return (res > 0) ? true : false;\r
-  }\r
-\r
-  /**\r
-   * Deletes entities based on a where clause\r
-   *\r
-   * @param aWhereClause\r
-   * @return\r
-   * @throws StorageObjectFailure\r
-   */\r
-  public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {\r
-    invalidatePopupCache();\r
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
-      StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);\r
-      o_store.invalidate(stoc_type);\r
-    }\r
-\r
-    Statement stmt = null;\r
-    Connection con = null;\r
-    int res = 0;\r
-    String sql =\r
-      "delete from " + theTable + " where " + aWhereClause;\r
-\r
-    //theLog.printInfo("DELETE " + sql);\r
-    try {\r
-      con = getPooledCon();\r
-      stmt = con.createStatement();\r
-      res = stmt.executeUpdate(sql);\r
-    }\r
-    catch (SQLException sqe) {\r
-      throwSQLException(sqe, "delete");\r
-    }\r
-    finally {\r
-      freeConnection(con, stmt);\r
-    }\r
-\r
-    return res;\r
-  }\r
-\r
-  /* noch nicht implementiert.\r
-  * @return immer false\r
-   */\r
-  public boolean delete(EntityList theEntityList) {\r
-    invalidatePopupCache();\r
-\r
-    return false;\r
-  }\r
-\r
-  /* invalidates the popupCache\r
-   */\r
-  protected void invalidatePopupCache() {\r
-    /** @todo  invalidates toooo much */\r
-    popupCache = null;\r
-    hashCache = null;\r
-  }\r
-\r
-  /**\r
-   * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.\r
-   * @param stmt Statemnt\r
-   * @param sql Sql-String\r
-   * @return ResultSet\r
-   * @exception StorageObjectException\r
-   */\r
-  public ResultSet executeSql(Statement stmt, String sql)\r
-                            throws StorageObjectFailure, SQLException {\r
-    ResultSet rs;\r
-    long startTime = System.currentTimeMillis();\r
-\r
-    try {\r
-      rs = stmt.executeQuery(sql);\r
-\r
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-    }\r
-    catch (SQLException e) {\r
-      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-      throw e;\r
-    }\r
-\r
-    return rs;\r
-  }\r
-/*\r
-  public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {\r
-    long startTime = System.currentTimeMillis();\r
-    Connection connection = null;\r
-    Statement statement = null;\r
-\r
-    try {\r
-      connection = getPooledCon();\r
-      statement = connection.createStatement();\r
-      ResultSet result;\r
-\r
-      result = statement.executeQuery(sql);\r
-\r
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-      return result;\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-      throw new StorageObjectFailure(e);\r
-    }\r
-    finally {\r
-      if (connection!=null) {\r
-        freeConnection(connection, statement);\r
-      }\r
-    }\r
-  }\r
-*/\r
-  private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {\r
-    try {\r
-      Map result = new HashMap();\r
-      ResultSetMetaData metaData = aResultSet.getMetaData();\r
-      int nrColumns = metaData.getColumnCount();\r
-      for (int i=0; i<nrColumns; i++) {\r
-        result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));\r
-      }\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable e) {\r
-      throw new StorageObjectFailure(e);\r
-    }\r
-  }\r
-\r
-  public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {\r
-    Connection connection = null;\r
-    Statement statement = null;\r
-    try {\r
-      List result = new Vector();\r
-      connection = getPooledCon();\r
-      statement = connection.createStatement();\r
-      ResultSet resultset = executeSql(statement, sql);\r
-      try {\r
-        while (resultset.next() && result.size() < aLimit) {\r
-          result.add(processRow(resultset));\r
-        }\r
-      }\r
-      finally {\r
-        resultset.close();\r
-      }\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable e) {\r
-      throw new StorageObjectFailure(e);\r
-    }\r
-    finally {\r
-      if (connection!=null) {\r
-        freeConnection(connection, statement);\r
-      }\r
-    }\r
-  };\r
-\r
-  public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {\r
-    try {\r
-      List resultList = executeFreeSql(anSqlStatement, 1);\r
-      try {\r
-        if (resultList.size()>0)\r
-          return (Map) resultList.get(0);\r
-        else\r
-          return null;\r
-      }\r
-      finally {\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      throw new StorageObjectFailure(t);\r
-    }\r
-  };\r
-\r
-  public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {\r
-    Map row = executeFreeSingleRowSql(sql);\r
-\r
-    if (row==null)\r
-      return null;\r
-\r
-    Iterator i = row.values().iterator();\r
-    if (i.hasNext())\r
-      return (String) i.next();\r
-    else\r
-      return null;\r
-  };\r
-\r
-  /**\r
-   * returns the number of rows in the table\r
-   */\r
-  public int getSize(String where) throws SQLException, StorageObjectFailure {\r
-    long startTime = System.currentTimeMillis();\r
-    String sql = "SELECT Count(*) FROM " + theTable;\r
-\r
-    if ((where != null) && (where.length() != 0)) {\r
-      sql = sql + " where " + where;\r
-    }\r
-\r
-    Connection con = null;\r
-    Statement stmt = null;\r
-    int result = 0;\r
-\r
-    try {\r
-      con = getPooledCon();\r
-      stmt = con.createStatement();\r
-\r
-      ResultSet rs = executeSql(stmt, sql);\r
-\r
-      while (rs.next()) {\r
-        result = rs.getInt(1);\r
-      }\r
-    }\r
-    catch (SQLException e) {\r
-      logger.error("Database.getSize: " + e.getMessage());\r
-    }\r
-    finally {\r
-      freeConnection(con, stmt);\r
-    }\r
-\r
-    //theLog.printInfo(theTable + " has "+ result +" rows where " + where);\r
-    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-\r
-    return result;\r
-  }\r
-\r
-  public int executeUpdate(Statement stmt, String sql)\r
-    throws StorageObjectFailure, SQLException {\r
-    int rs;\r
-    long startTime = System.currentTimeMillis();\r
-\r
-    try {\r
-      rs = stmt.executeUpdate(sql);\r
-\r
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-    }\r
-    catch (SQLException e) {\r
-      logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-      throw e;\r
-    }\r
-\r
-    return rs;\r
-  }\r
-\r
-  public int executeUpdate(String sql)\r
-    throws StorageObjectFailure, SQLException {\r
-    int result = -1;\r
-    long startTime = System.currentTimeMillis();\r
-    Connection con = null;\r
-    PreparedStatement pstmt = null;\r
-\r
-    try {\r
-      con = getPooledCon();\r
-      pstmt = con.prepareStatement(sql);\r
-      result = pstmt.executeUpdate();\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());\r
-      throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);\r
-    }\r
-    finally {\r
-      freeConnection(con, pstmt);\r
-    }\r
-\r
-    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
-    return result;\r
-  }\r
-\r
-  /**\r
-   * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend\r
-   * @param md ResultSetMetaData\r
-   * @exception StorageObjectException\r
-   */\r
-  private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {\r
-    this.evaluatedMetaData = true;\r
-    this.metadataFields = new ArrayList();\r
-    this.metadataLabels = new ArrayList();\r
-    this.metadataNotNullFields = new ArrayList();\r
-\r
-    try {\r
-      int numFields = md.getColumnCount();\r
-      this.metadataTypes = new int[numFields];\r
-\r
-      String aField;\r
-      int aType;\r
-\r
-      for (int i = 1; i <= numFields; i++) {\r
-        aField = md.getColumnName(i);\r
-        metadataFields.add(aField);\r
-        metadataLabels.add(md.getColumnLabel(i));\r
-        aType = md.getColumnType(i);\r
-        metadataTypes[i - 1] = aType;\r
-\r
-        if (aField.equals(thePKeyName)) {\r
-          thePKeyType = aType;\r
-          thePKeyIndex = i;\r
-        }\r
-\r
-        if (md.isNullable(i) == ResultSetMetaData.columnNullable) {\r
-          metadataNotNullFields.add(aField);\r
-        }\r
-      }\r
-    }\r
-    catch (SQLException e) {\r
-      throwSQLException(e, "evalMetaData");\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,\r
-   *  um die alle Columns und Typen einer Tabelle zu ermitteln.\r
-   */\r
-  private void get_meta_data() throws StorageObjectFailure {\r
-    Connection con = null;\r
-    PreparedStatement pstmt = null;\r
-    String sql = "select * from " + theTable + " where 0=1";\r
-\r
-    try {\r
-      con = getPooledCon();\r
-      pstmt = con.prepareStatement(sql);\r
-\r
-      logger.debug("METADATA: " + sql);\r
-      ResultSet rs = pstmt.executeQuery();\r
-      evalMetaData(rs.getMetaData());\r
-      rs.close();\r
-    }\r
-    catch (SQLException e) {\r
-      throwSQLException(e, "get_meta_data");\r
-    }\r
-    finally {\r
-      freeConnection(con, pstmt);\r
-    }\r
-  }\r
-\r
-  public Connection getPooledCon() throws StorageObjectFailure {\r
-    Connection con = null;\r
-\r
-    try {\r
-      con = SQLManager.getInstance().requestConnection();\r
-    }\r
-    catch (SQLException e) {\r
-      logger.error("could not connect to the database " + e.getMessage());\r
-\r
-      throw new StorageObjectFailure("Could not connect to the database", e);\r
-    }\r
-\r
-    return con;\r
-  }\r
-\r
-  public void freeConnection(Connection con, Statement stmt)\r
-    throws StorageObjectFailure {\r
-    SQLManager.closeStatement(stmt);\r
-    SQLManager.getInstance().returnConnection(con);\r
-  }\r
-\r
-  /**\r
-   * Wertet SQLException aus und wirft dannach eine StorageObjectException\r
-   * @param sqe SQLException\r
-   * @param wo Funktonsname, in der die SQLException geworfen wurde\r
-   * @exception StorageObjectException\r
-   */\r
-  protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {\r
-    String state = "";\r
-    String message = "";\r
-    int vendor = 0;\r
-\r
-    if (sqe != null) {\r
-      state = sqe.getSQLState();\r
-      message = sqe.getMessage();\r
-      vendor = sqe.getErrorCode();\r
-    }\r
-\r
-    String information =\r
-        "SQL Error: " +\r
-        "state= " + state +\r
-        ", vendor= " + vendor +\r
-        ", message=" + message +\r
-        ", function= " + aFunction;\r
-\r
-    logger.error(information);\r
-\r
-    throw new StorageObjectFailure(information, sqe);\r
-  }\r
-\r
-  protected void _throwStorageObjectException(Exception e, String aFunction)\r
-    throws StorageObjectFailure {\r
-\r
-    if (e != null) {\r
-      logger.error(e.getMessage() + aFunction);\r
-      throw new StorageObjectFailure(aFunction, e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach\r
-   * eine StorageObjectException\r
-   * @param message Nachricht mit dem Fehler\r
-   * @exception StorageObjectException\r
-   */\r
-  void throwStorageObjectException(String aMessage) throws StorageObjectFailure {\r
-    logger.error(aMessage);\r
-    throw new StorageObjectFailure(aMessage, null);\r
-  }\r
-}\r
+/*
+ * 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.storage;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.Vector;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
+import mir.entity.Entity;
+import mir.entity.EntityList;
+import mir.entity.StorableObjectEntity;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.storage.store.ObjectStore;
+import mir.storage.store.StorableObject;
+import mir.storage.store.StoreContainerType;
+import mir.storage.store.StoreIdentifier;
+import mir.storage.store.StoreUtil;
+import mir.util.JDBCStringRoutines;
+
+import com.codestudio.util.SQLManager;
+
+
+/**
+ * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
+ * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
+ * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
+ * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
+ * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
+ * Datenbank erfolgt.
+ *
+ * @version $Id: Database.java,v 1.44.2.7 2003/10/23 14:55:29 rk Exp $
+ * @author rk
+ *
+ */
+public class Database implements StorageObject {
+  private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
+  private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
+
+
+  private static Map POPUP_EMPTYLINE = new HashMap();
+  protected static final ObjectStore o_store = ObjectStore.getInstance();
+  private static final int _millisPerHour = 60 * 60 * 1000;
+  private static final int _millisPerMinute = 60 * 1000;
+
+  static {
+    // always same object saves a little space
+    POPUP_EMPTYLINE.put("key", "");
+    POPUP_EMPTYLINE.put("value", "--");
+  }
+
+  protected LoggerWrapper logger;
+  protected MirPropertiesConfiguration configuration;
+  protected String theTable;
+  protected String theCoreTable = null;
+  protected String thePKeyName = "id";
+  protected int thePKeyType;
+  protected int thePKeyIndex;
+  protected boolean evaluatedMetaData = false;
+  protected ArrayList metadataFields;
+  protected ArrayList metadataLabels;
+  protected ArrayList metadataNotNullFields;
+  protected int[] metadataTypes;
+  protected Class theEntityClass;
+  protected List popupCache = null;
+  protected boolean hasPopupCache = false;
+  protected Map hashCache = null;
+  protected boolean hasTimestamp = true;
+  private String database_driver;
+  private String database_url;
+  private int defaultLimit;
+
+  TimeZone timezone;
+  SimpleDateFormat internalDateFormat;
+  SimpleDateFormat userInputDateFormat;
+/*
+  private SimpleDateFormat _dateFormatterOut;
+  private SimpleDateFormat _dateFormatterIn;
+  _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+  _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+*/
+
+  /**
+   * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
+   * Aus diesem file werden <code>Database.Logfile</code>,
+   * <code>Database.Username</code>,<code>Database.Password</code>,
+   * <code>Database.Host</code> und <code>Database.Adaptor</code>
+   * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
+   * erzeugt.
+   *
+   * @param   String confFilename Dateiname der Konfigurationsdatei
+   */
+  public Database() throws StorageObjectFailure {
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (PropertiesConfigExc e) {
+      throw new StorageObjectFailure(e);
+    }
+    logger = new LoggerWrapper("Database");
+    timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
+    internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+    internalDateFormat.setTimeZone(timezone);
+
+    userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+    userInputDateFormat.setTimeZone(timezone);
+
+
+    String theAdaptorName = configuration.getString("Database.Adaptor");
+    defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
+
+    try {
+      theEntityClass = GENERIC_ENTITY_CLASS;
+    }
+    catch (Throwable e) {
+      logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
+      throw new StorageObjectFailure("Error in Database() constructor.", e);
+    }
+  }
+
+  /**
+   * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
+   * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
+   * wird eine mir.entity.GenericEntity erzeugt.
+   *
+   * @return Class-Objekt der Entity
+   */
+  public java.lang.Class getEntityClass() {
+    return theEntityClass;
+  }
+
+  /**
+   * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
+   * wieviel Datens?tze per Default selektiert werden.
+   *
+   * @return Standard-Anzahl der Datens?tze
+   */
+  public int getLimit() {
+    return defaultLimit;
+  }
+
+  /**
+   * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
+   * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
+   * @return Name des Primary-Keys
+   */
+  public String getIdName() {
+    return thePKeyName;
+  }
+
+  /**
+   * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
+   *
+   * @return Name der Tabelle
+   */
+  public String getTableName() {
+    return theTable;
+  }
+
+  /*
+  *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
+  *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
+  *   wird.
+  *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
+  *    the Table
+   */
+  public String getCoreTable() {
+    if (theCoreTable != null) {
+      return theCoreTable;
+    }
+    else {
+      return theTable;
+    }
+  }
+
+  /**
+   * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
+   * @return int-Array mit den Typen der Felder
+   * @exception StorageObjectException
+   */
+  public int[] getTypes() throws StorageObjectFailure {
+    if (metadataTypes == null) {
+      get_meta_data();
+    }
+
+    return metadataTypes;
+  }
+
+  /**
+   * Liefert eine Liste der Labels der Tabellenfelder
+   * @return ArrayListe mit Labeln
+   * @exception StorageObjectException
+   */
+  public List getLabels() throws StorageObjectFailure {
+    if (metadataLabels == null) {
+      get_meta_data();
+    }
+
+    return metadataLabels;
+  }
+
+  /**
+   * Liefert eine Liste der Felder der Tabelle
+   * @return ArrayList mit Feldern
+   * @exception StorageObjectException
+   */
+  public List getFields() throws StorageObjectFailure {
+    if (metadataFields == null) {
+      get_meta_data();
+    }
+
+    return metadataFields;
+  }
+
+  /*
+  *   Gets value out of ResultSet according to type and converts to String
+  *   @param inValue  Wert aus ResultSet.
+  *   @param aType  Datenbanktyp.
+  *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
+  *           dann /unsupported value/
+   */
+  private String getValueAsString(ResultSet rs, int valueIndex, int aType)
+    throws StorageObjectFailure {
+    String outValue = null;
+
+    if (rs != null) {
+      try {
+        switch (aType) {
+          case java.sql.Types.BIT:
+            outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
+
+            break;
+
+          case java.sql.Types.INTEGER:
+          case java.sql.Types.SMALLINT:
+          case java.sql.Types.TINYINT:
+          case java.sql.Types.BIGINT:
+
+            int out = rs.getInt(valueIndex);
+
+            if (!rs.wasNull()) {
+              outValue = new Integer(out).toString();
+            }
+
+            break;
+
+          case java.sql.Types.NUMERIC:
+
+            /** @todo Numeric can be float or double depending upon
+             *  metadata.getScale() / especially with oracle */
+            long outl = rs.getLong(valueIndex);
+
+            if (!rs.wasNull()) {
+              outValue = new Long(outl).toString();
+            }
+
+            break;
+
+          case java.sql.Types.REAL:
+
+            float tempf = rs.getFloat(valueIndex);
+
+            if (!rs.wasNull()) {
+              tempf *= 10;
+              tempf += 0.5;
+
+              int tempf_int = (int) tempf;
+              tempf = (float) tempf_int;
+              tempf /= 10;
+              outValue = "" + tempf;
+              outValue = outValue.replace('.', ',');
+            }
+
+            break;
+
+          case java.sql.Types.DOUBLE:
+
+            double tempd = rs.getDouble(valueIndex);
+
+            if (!rs.wasNull()) {
+              tempd *= 10;
+              tempd += 0.5;
+
+              int tempd_int = (int) tempd;
+              tempd = (double) tempd_int;
+              tempd /= 10;
+              outValue = "" + tempd;
+              outValue = outValue.replace('.', ',');
+            }
+
+            break;
+
+          case java.sql.Types.CHAR:
+          case java.sql.Types.VARCHAR:
+          case java.sql.Types.LONGVARCHAR:
+            outValue = rs.getString(valueIndex);
+
+            break;
+
+          case java.sql.Types.LONGVARBINARY:
+            outValue = rs.getString(valueIndex);
+
+            break;
+
+          case java.sql.Types.TIMESTAMP:
+
+            // it's important to use Timestamp here as getting it
+            // as a string is undefined and is only there for debugging
+            // according to the API. we can make it a string through formatting.
+            // -mh
+            Timestamp timestamp = (rs.getTimestamp(valueIndex));
+
+            if (!rs.wasNull()) {
+              java.util.Date date = new java.util.Date(timestamp.getTime());
+
+              Calendar calendar = new GregorianCalendar();
+              calendar.setTime(date);
+              calendar.setTimeZone(timezone);
+              outValue = internalDateFormat.format(date);
+
+              int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
+              String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
+
+              if (offset<0)
+                outValue = outValue + "-";
+              else
+                outValue = outValue + "+";
+              outValue = outValue + tzOffset;
+            }
+
+            break;
+
+          default:
+            outValue = "<unsupported value>";
+            logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
+        }
+      } catch (SQLException e) {
+        throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
+          e);
+      }
+    }
+
+    return outValue;
+  }
+
+  /*
+  *   select-Operator um einen Datensatz zu bekommen.
+  *   @param id Primaerschluessel des Datensatzes.
+  *   @return liefert EntityObject des gefundenen Datensatzes oder null.
+   */
+  public Entity selectById(String id) throws StorageObjectExc {
+    if ((id == null) || id.equals("")) {
+      throw new StorageObjectExc("Database.selectById: Missing id");
+    }
+
+    // ask object store for object
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      String uniqueId = id;
+
+      if (theEntityClass.equals(StorableObjectEntity.class)) {
+        uniqueId += ("@" + theTable);
+      }
+
+      StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
+      logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
+
+      Entity hit = (Entity) o_store.use(search_sid);
+
+      if (hit != null) {
+        return hit;
+      }
+    }
+
+    Statement stmt = null;
+    Connection con = getPooledCon();
+    Entity returnEntity = null;
+
+    try {
+      ResultSet rs;
+
+      /** @todo better prepared statement */
+      String selectSql =
+        "select * from " + theTable + " where " + thePKeyName + "=" + id;
+      stmt = con.createStatement();
+      rs = executeSql(stmt, selectSql);
+
+      if (rs != null) {
+        if (evaluatedMetaData == false) {
+          evalMetaData(rs.getMetaData());
+        }
+
+        if (rs.next()) {
+          returnEntity = makeEntityFromResultSet(rs);
+        }
+        else {
+          logger.debug("No data for id: " + id + " in table " + theTable);
+        }
+
+        rs.close();
+      }
+      else {
+        logger.debug("No Data for Id " + id + " in Table " + theTable);
+      }
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "selectById");
+      return null;
+    }
+    catch (NumberFormatException e) {
+      logger.error("ID is no number: " + id);
+    }
+    finally {
+      freeConnection(con, stmt);
+    }
+
+    return returnEntity;
+  }
+
+  /**
+   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
+   *   @param key  Datenbankfeld der Bedingung.
+   *   @param value  Wert die der key anehmen muss.
+   *   @return EntityList mit den gematchten Entities
+   */
+  public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
+    return selectByFieldValue(aField, aValue, 0);
+  }
+
+  /**
+   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
+   *   @param key  Datenbankfeld der Bedingung.
+   *   @param value  Wert die der key anehmen muss.
+   *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
+   *   @return EntityList mit den gematchten Entities
+   */
+  public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
+    return selectByWhereClause(aField + "=" + aValue, offset);
+  }
+
+  /**
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+   * Also offset wird der erste Datensatz genommen.
+   *
+   * @param wc where-Clause
+   * @return EntityList mit den gematchten Entities
+   * @exception StorageObjectException
+   */
+  public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
+    return selectByWhereClause(where, 0);
+  }
+
+  /**
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+   *
+   * @param wc where-Clause
+   * @param offset ab welchem Datensatz.
+   * @return EntityList mit den gematchten Entities
+   * @exception StorageObjectException
+   */
+  public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
+    return selectByWhereClause(whereClause, null, offset);
+  }
+
+  /**
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+   * Also offset wird der erste Datensatz genommen.
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+   *
+   * @param wc where-Clause
+   * @param ob orderBy-Clause
+   * @return EntityList mit den gematchten Entities
+   * @exception StorageObjectException
+   */
+  public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
+    return selectByWhereClause(where, order, 0);
+  }
+
+  /**
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+   *
+   * @param wc where-Clause
+   * @param ob orderBy-Clause
+   * @param offset ab welchem Datensatz
+   * @return EntityList mit den gematchten Entities
+   * @exception StorageObjectException
+   */
+  public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
+    return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
+  }
+
+  /**
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+   * @param aWhereClause where-Clause
+   * @param anOrderByClause orderBy-Clause
+   * @param offset ab welchem Datensatz
+   * @param limit wieviele Datens?tze
+   * @return EntityList mit den gematchten Entities
+   * @exception StorageObjectException
+   */
+  public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
+            int offset, int limit) throws StorageObjectFailure {
+
+    // check o_store for entitylist
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      StoreIdentifier search_sid =
+          new StoreIdentifier(
+            theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
+            StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));
+      EntityList hit = (EntityList) o_store.use(search_sid);
+
+      if (hit != null) {
+        logger.debug("CACHE (hit): " + search_sid.toString());
+
+        return hit;
+      }
+    }
+
+    // local
+    EntityList theReturnList = null;
+    Connection con = null;
+    Statement stmt = null;
+    ResultSet rs;
+    int offsetCount = 0;
+    int count = 0;
+
+    // build sql-statement
+
+    /** @todo count sql string should only be assembled if we really count
+     *  see below at the end of method //rk */
+    if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
+      aWhereClause = null;
+    }
+
+    StringBuffer countSql =
+      new StringBuffer("select count(*) from ").append(theTable);
+    StringBuffer selectSql =
+      new StringBuffer("select * from ").append(theTable);
+
+    if (aWhereClause != null) {
+      selectSql.append(" where ").append(aWhereClause);
+      countSql.append(" where ").append(aWhereClause);
+    }
+
+    if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
+      selectSql.append(" order by ").append(anOrderByClause);
+    }
+
+    if ((limit > -1) && (offset > -1)) {
+      selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
+    }
+
+    // execute sql
+    try {
+      con = getPooledCon();
+      stmt = con.createStatement();
+
+      // selecting...
+      rs = executeSql(stmt, selectSql.toString());
+
+      if (rs != null) {
+        if (!evaluatedMetaData) {
+          evalMetaData(rs.getMetaData());
+        }
+
+        theReturnList = new EntityList();
+
+        Entity theResultEntity;
+
+        while (rs.next()) {
+          theResultEntity = makeEntityFromResultSet(rs);
+          theReturnList.add(theResultEntity);
+          offsetCount++;
+        }
+
+        rs.close();
+      }
+
+      // making entitylist infos
+      count = offsetCount;
+
+      if (theReturnList != null) {
+        // now we decide if we have to know an overall count...
+        count = offsetCount;
+
+        if ((limit > -1) && (offset > -1)) {
+          if (offsetCount == limit) {
+            /** @todo counting should be deffered to entitylist
+             *  getSize() should be used */
+            rs = executeSql(stmt, countSql.toString());
+
+            if (rs != null) {
+              if (rs.next()) {
+                count = rs.getInt(1);
+              }
+
+              rs.close();
+            }
+            else {
+              logger.error("Could not count: " + countSql);
+            }
+          }
+        }
+
+        theReturnList.setCount(count);
+        theReturnList.setOffset(offset);
+        theReturnList.setWhere(aWhereClause);
+        theReturnList.setOrder(anOrderByClause);
+        theReturnList.setStorage(this);
+        theReturnList.setLimit(limit);
+
+        if (offset >= limit) {
+          theReturnList.setPrevBatch(offset - limit);
+        }
+
+        if ((offset + offsetCount) < count) {
+          theReturnList.setNextBatch(offset + limit);
+        }
+
+        if (StoreUtil.implementsStorableObject(theEntityClass)) {
+          StoreIdentifier sid = theReturnList.getStoreIdentifier();
+          logger.debug("CACHE (add): " + sid.toString());
+          o_store.add(sid);
+        }
+      }
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "selectByWhereClause");
+    }
+    finally {
+      try {
+        if (con != null) {
+          freeConnection(con, stmt);
+        }
+      } catch (Throwable t) {
+      }
+    }
+
+    return theReturnList;
+  }
+
+  /**
+   *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
+   *
+   *  @param rs Das ResultSetObjekt.
+   *  @return Entity Die Entity.
+   */
+  private Entity makeEntityFromResultSet(ResultSet rs)
+    throws StorageObjectFailure {
+    /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
+    Map theResultHash = new HashMap();
+    String theResult = null;
+    int theType;
+    Entity returnEntity = null;
+
+    try {
+      int size = metadataFields.size();
+
+      for (int i = 0; i < size; i++) {
+        // alle durchlaufen bis nix mehr da
+        theType = metadataTypes[i];
+
+        if (theType == java.sql.Types.LONGVARBINARY) {
+          InputStreamReader is =
+            (InputStreamReader) rs.getCharacterStream(i + 1);
+
+          if (is != null) {
+            char[] data = new char[32768];
+            StringBuffer theResultString = new StringBuffer();
+            int len;
+
+            while ((len = is.read(data)) > 0) {
+              theResultString.append(data, 0, len);
+            }
+
+            is.close();
+            theResult = theResultString.toString();
+          } else {
+            theResult = null;
+          }
+        } else {
+          theResult = getValueAsString(rs, (i + 1), theType);
+        }
+
+        if (theResult != null) {
+          theResultHash.put(metadataFields.get(i), theResult);
+        }
+      }
+
+      if (theEntityClass != null) {
+        returnEntity = (Entity) theEntityClass.newInstance();
+        returnEntity.setStorage(this);
+        returnEntity.setValues(theResultHash);
+
+        if (returnEntity instanceof StorableObject) {
+          logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
+          o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
+        }
+      } else {
+        throwStorageObjectException("Internal Error: theEntityClass not set!");
+      }
+    }
+    catch (IllegalAccessException e) {
+      throwStorageObjectException("No access! -- " + e.getMessage());
+    }
+    catch (IOException e) {
+      throwStorageObjectException("IOException! -- " + e.getMessage());
+    }
+    catch (InstantiationException e) {
+      throwStorageObjectException("No Instatiation! -- " + e.getMessage());
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "makeEntityFromResultSet");
+
+      return null;
+    }
+
+    return returnEntity;
+  }
+
+  /**
+   * Inserts an entity into the database.
+   *
+   * @param theEntity
+   * @return der Wert des Primary-keys der eingef?gten Entity
+   */
+  public String insert(Entity theEntity) throws StorageObjectFailure {
+    //cache
+    invalidatePopupCache();
+
+    // invalidating all EntityLists corresponding with theEntityClass
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      StoreContainerType stoc_type =
+        StoreContainerType.valueOf(theEntityClass,
+          StoreContainerType.STOC_TYPE_ENTITYLIST);
+      o_store.invalidate(stoc_type);
+    }
+
+    String returnId = null;
+    Connection con = null;
+    PreparedStatement pstmt = null;
+
+    try {
+      List streamedInput = theEntity.streamedInput();
+      StringBuffer f = new StringBuffer();
+      StringBuffer v = new StringBuffer();
+      String aField;
+      String aValue;
+      boolean firstField = true;
+
+      // make sql-string
+      for (int i = 0; i < getFields().size(); i++) {
+        aField = (String) getFields().get(i);
+
+        if (!aField.equals(thePKeyName)) {
+          aValue = null;
+
+          // exceptions
+          if (!theEntity.hasValueForField(aField) && (
+              aField.equals("webdb_create") ||
+              aField.equals("webdb_lastchange"))) {
+            aValue = "NOW()";
+          }
+          else {
+            if ((streamedInput != null) && streamedInput.contains(aField)) {
+              aValue = "?";
+            }
+            else {
+              if (theEntity.hasValueForField(aField)) {
+                aValue =
+                  "'" +
+                   JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
+              }
+            }
+          }
+
+          // wenn Wert gegeben, dann einbauen
+          if (aValue != null) {
+            if (firstField == false) {
+              f.append(",");
+              v.append(",");
+            }
+            else {
+              firstField = false;
+            }
+
+            f.append(aField);
+            v.append(aValue);
+          }
+        }
+      }
+       // end for
+
+      // insert into db
+      StringBuffer sqlBuf =
+        new StringBuffer("insert into ").append(theTable).append("(").append(f)
+                                        .append(") values (").append(v).append(")");
+      String sql = sqlBuf.toString();
+
+      logger.debug("INSERT: " + sql);
+      con = getPooledCon();
+      con.setAutoCommit(false);
+      pstmt = con.prepareStatement(sql);
+
+      if (streamedInput != null) {
+        for (int i = 0; i < streamedInput.size(); i++) {
+          String inputString =
+            (String) theEntity.getValue((String) streamedInput.get(i));
+          pstmt.setBytes(i + 1, inputString.getBytes());
+        }
+      }
+
+      int ret = pstmt.executeUpdate();
+
+      if (ret == 0) {
+        //insert failed
+        return null;
+      }
+
+      pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
+
+      ResultSet rs = pstmt.executeQuery();
+      rs.next();
+      returnId = rs.getString(1);
+      theEntity.setId(returnId);
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "insert");
+    }
+    finally {
+      try {
+        con.setAutoCommit(true);
+      }
+      catch (Exception e) {
+      }
+
+      freeConnection(con, pstmt);
+    }
+
+    /** @todo store entity in o_store */
+    return returnId;
+  }
+
+  /**
+   * Updates an entity in the database
+   *
+   * @param theEntity
+   */
+  public void update(Entity theEntity) throws StorageObjectFailure {
+    Connection con = null;
+    PreparedStatement pstmt = null;
+
+    /** @todo this is stupid: why do we prepare statement, when we
+     *  throw it away afterwards. should be regular statement
+     *  update/insert could better be one routine called save()
+     *  that chooses to either insert or update depending if we
+     *  have a primary key in the entity. i don't know if we
+     *  still need the streamed input fields. // rk  */
+    /** @todo extension: check if Entity did change, otherwise we don't need
+     *  the roundtrip to the database */
+    /** invalidating corresponding entitylists in o_store*/
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      StoreContainerType stoc_type =
+        StoreContainerType.valueOf(theEntityClass,
+          StoreContainerType.STOC_TYPE_ENTITYLIST);
+      o_store.invalidate(stoc_type);
+    }
+
+    List streamedInput = theEntity.streamedInput();
+    String id = theEntity.getId();
+    String aField;
+    StringBuffer fv = new StringBuffer();
+    boolean firstField = true;
+
+    //cache
+    invalidatePopupCache();
+
+    // build sql statement
+    for (int i = 0; i < getFields().size(); i++) {
+      aField = (String) metadataFields.get(i);
+
+      // only normal cases
+      if (  !(aField.equals(thePKeyName) ||
+            aField.equals("webdb_create") ||
+            aField.equals("webdb_lastchange") ||
+            ((streamedInput != null) && streamedInput.contains(aField)))) {
+        if (theEntity.hasValueForField(aField)) {
+          if (firstField == false) {
+            fv.append(", ");
+          }
+          else {
+            firstField = false;
+          }
+
+          fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
+
+          //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
+        }
+      }
+    }
+
+    StringBuffer sql =
+      new StringBuffer("update ").append(theTable).append(" set ").append(fv);
+
+    // exceptions
+    if (metadataFields.contains("webdb_lastchange")) {
+      sql.append(",webdb_lastchange=NOW()");
+    }
+
+    // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
+    // format so anything extra will be ignored. -mh
+    if (metadataFields.contains("webdb_create") &&
+        theEntity.hasValueForField("webdb_create")) {
+      // minimum of 10 (yyyy-mm-dd)...
+      if (theEntity.getValue("webdb_create").length() >= 10) {
+        String dateString = theEntity.getValue("webdb_create");
+
+        // if only 10, then add 00:00 so it doesn't throw a ParseException
+        if (dateString.length() == 10) {
+          dateString = dateString + " 00:00";
+        }
+
+        // TimeStamp stuff
+        try {
+          java.util.Date d = userInputDateFormat.parse(dateString);
+//          Timestamp tStamp = new Timestamp(d.getTime());
+          sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
+        }
+        catch (ParseException e) {
+          throw new StorageObjectFailure(e);
+        }
+      }
+    }
+
+    if (streamedInput != null) {
+      for (int i = 0; i < streamedInput.size(); i++) {
+        sql.append(",").append(streamedInput.get(i)).append("=?");
+      }
+    }
+
+    sql.append(" where id=").append(id);
+    logger.debug("UPDATE: " + sql);
+
+    try {
+      con = getPooledCon();
+      con.setAutoCommit(false);
+      pstmt = con.prepareStatement(sql.toString());
+
+      if (streamedInput != null) {
+        for (int i = 0; i < streamedInput.size(); i++) {
+          String inputString =
+            theEntity.getValue((String) streamedInput.get(i));
+          pstmt.setBytes(i + 1, inputString.getBytes());
+        }
+      }
+
+      pstmt.executeUpdate();
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "update");
+    }
+    finally {
+      try {
+        con.setAutoCommit(true);
+      }
+      catch (Exception e) {
+        ;
+      }
+
+      freeConnection(con, pstmt);
+    }
+  }
+
+  /*
+  *   delete-Operator
+  *   @param id des zu loeschenden Datensatzes
+  *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
+   */
+  public boolean delete(String id) throws StorageObjectFailure {
+    invalidatePopupCache();
+
+    // ostore send notification
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      String uniqueId = id;
+
+      if (theEntityClass.equals(StorableObjectEntity.class)) {
+        uniqueId += ("@" + theTable);
+      }
+
+      logger.debug("CACHE: (del) " + id);
+
+      StoreIdentifier search_sid =
+        new StoreIdentifier(theEntityClass,
+          StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
+      o_store.invalidate(search_sid);
+    }
+
+    /** @todo could be prepared Statement */
+    Statement stmt = null;
+    Connection con = null;
+    int res = 0;
+    String sql =
+      "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
+
+    //theLog.printInfo("DELETE " + sql);
+    try {
+      con = getPooledCon();
+      stmt = con.createStatement();
+      res = stmt.executeUpdate(sql);
+    } catch (SQLException sqe) {
+      throwSQLException(sqe, "delete");
+    } finally {
+      freeConnection(con, stmt);
+    }
+
+    return (res > 0) ? true : false;
+  }
+
+  /**
+   * Deletes entities based on a where clause
+   *
+   * @param aWhereClause
+   * @return
+   * @throws StorageObjectFailure
+   */
+  public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
+    invalidatePopupCache();
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {
+      StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
+      o_store.invalidate(stoc_type);
+    }
+
+    Statement stmt = null;
+    Connection con = null;
+    int res = 0;
+    String sql =
+      "delete from " + theTable + " where " + aWhereClause;
+
+    //theLog.printInfo("DELETE " + sql);
+    try {
+      con = getPooledCon();
+      stmt = con.createStatement();
+      res = stmt.executeUpdate(sql);
+    }
+    catch (SQLException sqe) {
+      throwSQLException(sqe, "delete");
+    }
+    finally {
+      freeConnection(con, stmt);
+    }
+
+    return res;
+  }
+
+  /* noch nicht implementiert.
+  * @return immer false
+   */
+  public boolean delete(EntityList theEntityList) {
+    invalidatePopupCache();
+
+    return false;
+  }
+
+  /* invalidates the popupCache
+   */
+  protected void invalidatePopupCache() {
+    /** @todo  invalidates toooo much */
+    popupCache = null;
+    hashCache = null;
+  }
+
+  /**
+   * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
+   * @param stmt Statemnt
+   * @param sql Sql-String
+   * @return ResultSet
+   * @exception StorageObjectException
+   */
+  public ResultSet executeSql(Statement stmt, String sql)
+                            throws StorageObjectFailure, SQLException {
+    ResultSet rs;
+    long startTime = System.currentTimeMillis();
+
+    try {
+      rs = stmt.executeQuery(sql);
+
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+    }
+    catch (SQLException e) {
+      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      throw e;
+    }
+
+    return rs;
+  }
+/*
+  public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
+    long startTime = System.currentTimeMillis();
+    Connection connection = null;
+    Statement statement = null;
+
+    try {
+      connection = getPooledCon();
+      statement = connection.createStatement();
+      ResultSet result;
+
+      result = statement.executeQuery(sql);
+
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      return result;
+    }
+    catch (Throwable e) {
+      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      throw new StorageObjectFailure(e);
+    }
+    finally {
+      if (connection!=null) {
+        freeConnection(connection, statement);
+      }
+    }
+  }
+*/
+  private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
+    try {
+      Map result = new HashMap();
+      ResultSetMetaData metaData = aResultSet.getMetaData();
+      int nrColumns = metaData.getColumnCount();
+      for (int i=0; i<nrColumns; i++) {
+        result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
+      }
+
+      return result;
+    }
+    catch (Throwable e) {
+      throw new StorageObjectFailure(e);
+    }
+  }
+
+  public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
+    Connection connection = null;
+    Statement statement = null;
+    try {
+      List result = new Vector();
+      connection = getPooledCon();
+      statement = connection.createStatement();
+      ResultSet resultset = executeSql(statement, sql);
+      try {
+        while (resultset.next() && result.size() < aLimit) {
+          result.add(processRow(resultset));
+        }
+      }
+      finally {
+        resultset.close();
+      }
+
+      return result;
+    }
+    catch (Throwable e) {
+      throw new StorageObjectFailure(e);
+    }
+    finally {
+      if (connection!=null) {
+        freeConnection(connection, statement);
+      }
+    }
+  };
+
+  public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
+    try {
+      List resultList = executeFreeSql(anSqlStatement, 1);
+      try {
+        if (resultList.size()>0)
+          return (Map) resultList.get(0);
+        else
+          return null;
+      }
+      finally {
+      }
+    }
+    catch (Throwable t) {
+      throw new StorageObjectFailure(t);
+    }
+  };
+
+  public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
+    Map row = executeFreeSingleRowSql(sql);
+
+    if (row==null)
+      return null;
+
+    Iterator i = row.values().iterator();
+    if (i.hasNext())
+      return (String) i.next();
+    else
+      return null;
+  };
+
+  /**
+   * returns the number of rows in the table
+   */
+  public int getSize(String where) throws SQLException, StorageObjectFailure {
+    long startTime = System.currentTimeMillis();
+    String sql = "SELECT Count(*) FROM " + theTable;
+
+    if ((where != null) && (where.length() != 0)) {
+      sql = sql + " where " + where;
+    }
+
+    Connection con = null;
+    Statement stmt = null;
+    int result = 0;
+
+    try {
+      con = getPooledCon();
+      stmt = con.createStatement();
+
+      ResultSet rs = executeSql(stmt, sql);
+
+      while (rs.next()) {
+        result = rs.getInt(1);
+      }
+    }
+    catch (SQLException e) {
+      logger.error("Database.getSize: " + e.getMessage());
+    }
+    finally {
+      freeConnection(con, stmt);
+    }
+
+    //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
+    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+
+    return result;
+  }
+
+  public int executeUpdate(Statement stmt, String sql)
+    throws StorageObjectFailure, SQLException {
+    int rs;
+    long startTime = System.currentTimeMillis();
+
+    try {
+      rs = stmt.executeUpdate(sql);
+
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+    }
+    catch (SQLException e) {
+      logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      throw e;
+    }
+
+    return rs;
+  }
+
+  public int executeUpdate(String sql)
+    throws StorageObjectFailure, SQLException {
+    int result = -1;
+    long startTime = System.currentTimeMillis();
+    Connection con = null;
+    PreparedStatement pstmt = null;
+
+    try {
+      con = getPooledCon();
+      pstmt = con.prepareStatement(sql);
+      result = pstmt.executeUpdate();
+    }
+    catch (Throwable e) {
+      logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
+      throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
+    }
+    finally {
+      freeConnection(con, pstmt);
+    }
+
+    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+    return result;
+  }
+
+  /**
+   * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
+   * @param md ResultSetMetaData
+   * @exception StorageObjectException
+   */
+  private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
+    this.evaluatedMetaData = true;
+    this.metadataFields = new ArrayList();
+    this.metadataLabels = new ArrayList();
+    this.metadataNotNullFields = new ArrayList();
+
+    try {
+      int numFields = md.getColumnCount();
+      this.metadataTypes = new int[numFields];
+
+      String aField;
+      int aType;
+
+      for (int i = 1; i <= numFields; i++) {
+        aField = md.getColumnName(i);
+        metadataFields.add(aField);
+        metadataLabels.add(md.getColumnLabel(i));
+        aType = md.getColumnType(i);
+        metadataTypes[i - 1] = aType;
+
+        if (aField.equals(thePKeyName)) {
+          thePKeyType = aType;
+          thePKeyIndex = i;
+        }
+
+        if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
+          metadataNotNullFields.add(aField);
+        }
+      }
+    }
+    catch (SQLException e) {
+      throwSQLException(e, "evalMetaData");
+    }
+  }
+
+  /**
+   *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
+   *  um die alle Columns und Typen einer Tabelle zu ermitteln.
+   */
+  private void get_meta_data() throws StorageObjectFailure {
+    Connection con = null;
+    PreparedStatement pstmt = null;
+    String sql = "select * from " + theTable + " where 0=1";
+
+    try {
+      con = getPooledCon();
+      pstmt = con.prepareStatement(sql);
+
+      logger.debug("METADATA: " + sql);
+      ResultSet rs = pstmt.executeQuery();
+      evalMetaData(rs.getMetaData());
+      rs.close();
+    }
+    catch (SQLException e) {
+      throwSQLException(e, "get_meta_data");
+    }
+    finally {
+      freeConnection(con, pstmt);
+    }
+  }
+
+  public Connection getPooledCon() throws StorageObjectFailure {
+    Connection con = null;
+
+    try {
+      con = SQLManager.getInstance().requestConnection();
+    }
+    catch (SQLException e) {
+      logger.error("could not connect to the database " + e.getMessage());
+
+      throw new StorageObjectFailure("Could not connect to the database", e);
+    }
+
+    return con;
+  }
+
+  public void freeConnection(Connection con, Statement stmt)
+    throws StorageObjectFailure {
+    SQLManager.closeStatement(stmt);
+    SQLManager.getInstance().returnConnection(con);
+  }
+
+  /**
+   * Wertet SQLException aus und wirft dannach eine StorageObjectException
+   * @param sqe SQLException
+   * @param wo Funktonsname, in der die SQLException geworfen wurde
+   * @exception StorageObjectException
+   */
+  protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
+    String state = "";
+    String message = "";
+    int vendor = 0;
+
+    if (sqe != null) {
+      state = sqe.getSQLState();
+      message = sqe.getMessage();
+      vendor = sqe.getErrorCode();
+    }
+
+    String information =
+        "SQL Error: " +
+        "state= " + state +
+        ", vendor= " + vendor +
+        ", message=" + message +
+        ", function= " + aFunction;
+
+    logger.error(information);
+
+    throw new StorageObjectFailure(information, sqe);
+  }
+
+  protected void _throwStorageObjectException(Exception e, String aFunction)
+    throws StorageObjectFailure {
+
+    if (e != null) {
+      logger.error(e.getMessage() + aFunction);
+      throw new StorageObjectFailure(aFunction, e);
+    }
+  }
+
+  /**
+   * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
+   * eine StorageObjectException
+   * @param message Nachricht mit dem Fehler
+   * @exception StorageObjectException
+   */
+  void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
+    logger.error(aMessage);
+    throw new StorageObjectFailure(aMessage, null);
+  }
+}
index 691bd57..f89ef89 100755 (executable)
@@ -33,7 +33,6 @@ import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.GregorianCalendar;
-import java.util.SimpleTimeZone;
 import java.util.TimeZone;
 
 public class DateTimeFunctions {
index 4df8058..cd06169 100755 (executable)
@@ -29,6 +29,8 @@
  */
 package mir.util;
 
+import gnu.regexp.RE;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -38,8 +40,6 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Vector;
 
-import gnu.regexp.RE;
-
 public class FileFunctions {
   protected static final int FILE_COPY_BUFFER_SIZE = 65536;
 
index 9825ca2..bcedf17 100755 (executable)
@@ -30,7 +30,6 @@
 package mir.util;
 
 import java.util.List;
-import java.io.*;
 
 import mir.generator.Generator;
 import mir.generator.GeneratorExc;
index 54dbea5..60df288 100755 (executable)
@@ -30,7 +30,8 @@
 
 package mir.util;
 
-import java.util.*;
+import java.util.List;
+import java.util.Vector;
 
 import javax.servlet.http.HttpServletRequest;
 
index cae60e5..4d3bff8 100755 (executable)
@@ -38,8 +38,9 @@ package mir.util;
  * @version 1.0
  */
 
-import java.util.*;
-import java.text.*;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
 
 public class JDBCStringRoutines {
   private JDBCStringRoutines() {
index a65015b..71e154a 100755 (executable)
@@ -35,12 +35,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
-import org.apache.commons.beanutils.*;
-
-import multex.Exc;
-
 import mir.generator.Generator;
 import mir.generator.GeneratorExc;
+import multex.Exc;
+
+import org.apache.commons.beanutils.MethodUtils;
+import org.apache.commons.beanutils.PropertyUtils;
 
 public class ParameterExpander {
   final static String NODE_SEPARATOR = ".";
index 16e9846..bd6f274 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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.util;\r
-\r
-import gnu.regexp.RE;\r
-import gnu.regexp.REException;\r
-\r
-import java.util.List;\r
-import java.util.Vector;\r
-\r
-public class StringRoutines {\r
-\r
-  private StringRoutines() {\r
-  }\r
-\r
-  public static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {\r
-    int i;\r
-    int result=-1;\r
-    int position;\r
-\r
-    for (i=0; i<aCharacters.length ; i++) {\r
-      position = aString.indexOf(aCharacters[i], aFrom);\r
-\r
-      if (position != -1 && ( result == -1 || position < result )) {\r
-        result = position;\r
-      }\r
-    }\r
-\r
-    return result;\r
-  }\r
-\r
-  public static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {\r
-    if (aText==null)\r
-      return null;\r
-\r
-    int position, nextPosition;\r
-    int i;\r
-    StringBuffer result = new StringBuffer();\r
-\r
-    position=0;\r
-    do {\r
-      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);\r
-\r
-      if (nextPosition<0)\r
-        nextPosition = aText.length();\r
-\r
-      result.append(aText.substring(position, nextPosition));\r
-\r
-      if (nextPosition<aText.length())\r
-        for (i=0; i<aCharactersToReplace.length; i++) {\r
-          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {\r
-            result.append(aStringsToSubstitute[i]);\r
-            break;\r
-          }\r
-        }\r
-      position=nextPosition+1;\r
-    }\r
-    while (nextPosition<aText.length()) ;\r
-\r
-    return result.toString();\r
-  }\r
-  /**\r
-   *\r
-   * @param aText\r
-   * @param anEscapeCharacater\r
-   * @param aCharactersToReplace\r
-   * @param aStringsToSubstitute\r
-   * @return\r
-   */\r
-\r
-  public static String replaceEscapedStringCharacters(String aText, char anEscapeCharacter, char[] aCharactersToReplace, String[] aStringsToSubstitute) {\r
-    if (aText==null)\r
-      return null;\r
-\r
-    int position, nextPosition;\r
-    int i;\r
-    StringBuffer result = new StringBuffer();\r
-\r
-    position=0;\r
-    do {\r
-      nextPosition = aText.indexOf(anEscapeCharacter, position);\r
-\r
-      if (nextPosition<0)\r
-        nextPosition = aText.length();\r
-\r
-      result.append(aText.substring(position, nextPosition));\r
-\r
-      if (nextPosition+1<aText.length()) {\r
-        nextPosition = nextPosition+1;\r
-\r
-        boolean found = false;\r
-        for (i = 0; i < aCharactersToReplace.length; i++) {\r
-          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {\r
-            result.append(aStringsToSubstitute[i]);\r
-            found=true;\r
-            break;\r
-          }\r
-        }\r
-\r
-        if (!found) {\r
-          result.append(aText.charAt(nextPosition));\r
-        }\r
-      }\r
-      position=nextPosition+1;\r
-    }\r
-    while (nextPosition<aText.length()) ;\r
-\r
-    return result.toString();\r
-  }\r
-\r
-  public static String interpretAsString(Object aValue) throws Exception {\r
-    if (aValue instanceof String)\r
-      return (String) aValue;\r
-\r
-    if (aValue instanceof Integer)\r
-      return ((Integer) aValue).toString();\r
-\r
-    if (aValue == null)\r
-      return "";\r
-\r
-    throw new Exception("String expected, "+aValue+" found");\r
-  }\r
-\r
-  public static int interpretAsInteger(Object aValue) throws Exception {\r
-    if (aValue instanceof Integer)\r
-      return ((Integer) aValue).intValue();\r
-\r
-    if (aValue instanceof String)\r
-      try {\r
-        return Integer.parseInt((String) aValue);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new Exception("Integer expected, "+aValue+" found");\r
-      }\r
-\r
-    throw new Exception("Integer expected, "+aValue+" found");\r
-  }\r
-\r
-  /**\r
-   *\r
-   * @param aSource\r
-   * @param aSearchExpression\r
-   * @param aReplacement\r
-   * @return\r
-   * @throws Exception\r
-   */\r
-  public static String performRegularExpressionReplacement(String aSource,\r
-      String aSearchExpression, String aReplacement) throws UtilExc {\r
-    try {\r
-      RE regularExpression;\r
-\r
-      regularExpression = new RE(aSearchExpression);\r
-\r
-      return regularExpression.substituteAll(aSource, aReplacement);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);\r
-    }\r
-  }\r
-\r
-  public static String performCaseInsensitiveRegularExpressionReplacement(String aSource,\r
-      String aSearchExpression, String aReplacement) throws UtilExc {\r
-    try {\r
-      RE regularExpression;\r
-\r
-      regularExpression = new RE(aSearchExpression, RE.REG_ICASE);\r
-\r
-      return regularExpression.substituteAll(aSource, aReplacement);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *\r
-   * @param aSource\r
-   * @param aSearchExpression\r
-   * @return\r
-   * @throws REException\r
-   */\r
-  public static boolean performRegularExpressionSearch(String aSource,\r
-      String aSearchExpression) throws UtilExc {\r
-    try {\r
-      RE regularExpression;\r
-\r
-      regularExpression = new RE(aSearchExpression);\r
-\r
-      return regularExpression.isMatch(aSource);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new UtilFailure("StringRoutines.performRegularExpressionSearch: " + t.toString(), t);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Separates a string based on a separator:\r
-   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
-   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>\r
-   *\r
-   * @param aString     The string to split\r
-   * @param aSeparator\r
-   * @return\r
-   */\r
-\r
-  public static List splitString(String aString, String aSeparator) {\r
-    List result= new Vector();\r
-    int previousPosition = 0;\r
-    int position;\r
-    int endOfNamePosition;\r
-\r
-    if (aString!=null) {\r
-      while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {\r
-        result.add(aString.substring(previousPosition, position));\r
-        previousPosition = position + aSeparator.length();\r
-      }\r
-      result.add(aString.substring(previousPosition, aString.length()));\r
-    }\r
-\r
-    return result;\r
-  }\r
-\r
-  /**\r
-   * Separates a String into at most 2 parts based on a separator:\r
-   * <ul>\r
-   *   <li>\r
-   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
-   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>\r
-   *   <li>\r
-   *     <code>seperateString("abc", ":");</code> will lead to\r
-   *     a List with a single String: <code>"abc"</code>\r
-   * </ul>\r
-   *\r
-   *\r
-   * @param aString\r
-   * @param aSeparator\r
-   * @return\r
-   */\r
-  public static List separateString(String aString, String aSeparator) {\r
-    List result= new Vector();\r
-    int previousPosition = 0;\r
-    int position;\r
-\r
-    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {\r
-      result.add(aString.substring(previousPosition, position));\r
-      previousPosition = position + aSeparator.length();\r
-    }\r
-\r
-    result.add(aString.substring(previousPosition, aString.length()));\r
-\r
-    return result;\r
-  }\r
-\r
-  public static List splitStringWithEscape(String aString, char aSeparator, char anEscape) {\r
-    List result= new Vector();\r
-    int previousPosition = 0;\r
-    int position;\r
-    int endOfNamePosition;\r
-    StringBuffer currentItem = new StringBuffer();\r
-\r
-    if (aString!=null) {\r
-      while ((position = indexOfCharacters(aString, new char[] {aSeparator, anEscape}, previousPosition))>=0) {\r
-        currentItem.append(aString.substring(previousPosition, position));\r
-\r
-        if (aString.charAt(position)==aSeparator) {\r
-          result.add(currentItem.toString());\r
-          currentItem.delete(0, currentItem.length());\r
-        }\r
-        else {\r
-          currentItem.append(aString.charAt(position));\r
-          if (aString.length()>position+1) {\r
-            position=position+1;\r
-            currentItem.append(aString.charAt(position));\r
-          }\r
-        }\r
-        previousPosition = position + 1;\r
-      }\r
-      currentItem.append(aString.substring(previousPosition, aString.length()));\r
-      result.add(currentItem.toString());\r
-    }\r
-\r
-    return result;\r
-  }\r
-\r
-  public static String replicateString(String aString, int aCount) {\r
-    StringBuffer result = new StringBuffer();\r
-\r
-    for (int i=0; i<aCount; i++)\r
-      result.append(aString);\r
-\r
-    return result.toString();\r
-  }\r
-\r
-  public static String replicateChar(char aCharacter, int aCount) {\r
-    char result[] = new char[aCount];\r
-\r
-    for (int i=0; i<aCount; i++)\r
-      result[i]= aCharacter;\r
-\r
-    return new String(result);\r
-  }\r
-\r
-  public static String padStringLeft(String aString, int aLength, char aPadCharacter) {\r
-    if (aString.length()<aLength)\r
-      return replicateChar(aPadCharacter, aLength-aString.length()) + aString;\r
-    else\r
-      return aString;\r
-  }\r
-\r
-  private static final char HEX_CHARACTERS[] = {\r
-      '0', '1', '2', '3', '4', '5', '6', '7',\r
-      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'\r
-  };\r
-\r
-  public static String convertToHex(long aData, int aNumberOfDigits) {\r
-    StringBuffer result = new StringBuffer();\r
-\r
-    for (int digit = aNumberOfDigits-1; digit>=0; digit--) {\r
-      int value = (int) (aData >> (digit*4)) & 0xf;\r
-      result.append(HEX_CHARACTERS[value]);\r
-    }\r
-\r
-    return result.toString();\r
-  }\r
-\r
-  public static String convertToHex(byte[] aData) {\r
-    StringBuffer result = new StringBuffer();\r
-\r
-    for (int i = 0; i<aData.length; i++) {\r
-      result.append(convertToHex(aData[i], 2));\r
-\r
-    }\r
-\r
-    return result.toString();\r
-  }\r
-}\r
+/*
+ * 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.util;
+
+import gnu.regexp.RE;
+
+import java.util.List;
+import java.util.Vector;
+
+public class StringRoutines {
+
+  private StringRoutines() {
+  }
+
+  public static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {
+    int i;
+    int result=-1;
+    int position;
+
+    for (i=0; i<aCharacters.length ; i++) {
+      position = aString.indexOf(aCharacters[i], aFrom);
+
+      if (position != -1 && ( result == -1 || position < result )) {
+        result = position;
+      }
+    }
+
+    return result;
+  }
+
+  public static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
+    if (aText==null)
+      return null;
+
+    int position, nextPosition;
+    int i;
+    StringBuffer result = new StringBuffer();
+
+    position=0;
+    do {
+      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);
+
+      if (nextPosition<0)
+        nextPosition = aText.length();
+
+      result.append(aText.substring(position, nextPosition));
+
+      if (nextPosition<aText.length())
+        for (i=0; i<aCharactersToReplace.length; i++) {
+          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
+            result.append(aStringsToSubstitute[i]);
+            break;
+          }
+        }
+      position=nextPosition+1;
+    }
+    while (nextPosition<aText.length()) ;
+
+    return result.toString();
+  }
+  /**
+   *
+   * @param aText
+   * @param anEscapeCharacater
+   * @param aCharactersToReplace
+   * @param aStringsToSubstitute
+   * @return
+   */
+
+  public static String replaceEscapedStringCharacters(String aText, char anEscapeCharacter, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
+    if (aText==null)
+      return null;
+
+    int position, nextPosition;
+    int i;
+    StringBuffer result = new StringBuffer();
+
+    position=0;
+    do {
+      nextPosition = aText.indexOf(anEscapeCharacter, position);
+
+      if (nextPosition<0)
+        nextPosition = aText.length();
+
+      result.append(aText.substring(position, nextPosition));
+
+      if (nextPosition+1<aText.length()) {
+        nextPosition = nextPosition+1;
+
+        boolean found = false;
+        for (i = 0; i < aCharactersToReplace.length; i++) {
+          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
+            result.append(aStringsToSubstitute[i]);
+            found=true;
+            break;
+          }
+        }
+
+        if (!found) {
+          result.append(aText.charAt(nextPosition));
+        }
+      }
+      position=nextPosition+1;
+    }
+    while (nextPosition<aText.length()) ;
+
+    return result.toString();
+  }
+
+  public static String interpretAsString(Object aValue) throws Exception {
+    if (aValue instanceof String)
+      return (String) aValue;
+
+    if (aValue instanceof Integer)
+      return ((Integer) aValue).toString();
+
+    if (aValue == null)
+      return "";
+
+    throw new Exception("String expected, "+aValue+" found");
+  }
+
+  public static int interpretAsInteger(Object aValue) throws Exception {
+    if (aValue instanceof Integer)
+      return ((Integer) aValue).intValue();
+
+    if (aValue instanceof String)
+      try {
+        return Integer.parseInt((String) aValue);
+      }
+      catch (Throwable t) {
+        throw new Exception("Integer expected, "+aValue+" found");
+      }
+
+    throw new Exception("Integer expected, "+aValue+" found");
+  }
+
+  /**
+   *
+   * @param aSource
+   * @param aSearchExpression
+   * @param aReplacement
+   * @return
+   * @throws Exception
+   */
+  public static String performRegularExpressionReplacement(String aSource,
+      String aSearchExpression, String aReplacement) throws UtilExc {
+    try {
+      RE regularExpression;
+
+      regularExpression = new RE(aSearchExpression);
+
+      return regularExpression.substituteAll(aSource, aReplacement);
+    }
+    catch (Throwable t) {
+      throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
+    }
+  }
+
+  public static String performCaseInsensitiveRegularExpressionReplacement(String aSource,
+      String aSearchExpression, String aReplacement) throws UtilExc {
+    try {
+      RE regularExpression;
+
+      regularExpression = new RE(aSearchExpression, RE.REG_ICASE);
+
+      return regularExpression.substituteAll(aSource, aReplacement);
+    }
+    catch (Throwable t) {
+      throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
+    }
+  }
+
+  /**
+   *
+   * @param aSource
+   * @param aSearchExpression
+   * @return
+   * @throws REException
+   */
+  public static boolean performRegularExpressionSearch(String aSource,
+      String aSearchExpression) throws UtilExc {
+    try {
+      RE regularExpression;
+
+      regularExpression = new RE(aSearchExpression);
+
+      return regularExpression.isMatch(aSource);
+    }
+    catch (Throwable t) {
+      throw new UtilFailure("StringRoutines.performRegularExpressionSearch: " + t.toString(), t);
+    }
+  }
+
+  /**
+   * Separates a string based on a separator:
+   *     <code>seperateString("a:b:c", ":");</code> will lead to
+   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>
+   *
+   * @param aString     The string to split
+   * @param aSeparator
+   * @return
+   */
+
+  public static List splitString(String aString, String aSeparator) {
+    List result= new Vector();
+    int previousPosition = 0;
+    int position;
+    int endOfNamePosition;
+
+    if (aString!=null) {
+      while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {
+        result.add(aString.substring(previousPosition, position));
+        previousPosition = position + aSeparator.length();
+      }
+      result.add(aString.substring(previousPosition, aString.length()));
+    }
+
+    return result;
+  }
+
+  /**
+   * Separates a String into at most 2 parts based on a separator:
+   * <ul>
+   *   <li>
+   *     <code>seperateString("a:b:c", ":");</code> will lead to
+   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>
+   *   <li>
+   *     <code>seperateString("abc", ":");</code> will lead to
+   *     a List with a single String: <code>"abc"</code>
+   * </ul>
+   *
+   *
+   * @param aString
+   * @param aSeparator
+   * @return
+   */
+  public static List separateString(String aString, String aSeparator) {
+    List result= new Vector();
+    int previousPosition = 0;
+    int position;
+
+    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {
+      result.add(aString.substring(previousPosition, position));
+      previousPosition = position + aSeparator.length();
+    }
+
+    result.add(aString.substring(previousPosition, aString.length()));
+
+    return result;
+  }
+
+  public static List splitStringWithEscape(String aString, char aSeparator, char anEscape) {
+    List result= new Vector();
+    int previousPosition = 0;
+    int position;
+    int endOfNamePosition;
+    StringBuffer currentItem = new StringBuffer();
+
+    if (aString!=null) {
+      while ((position = indexOfCharacters(aString, new char[] {aSeparator, anEscape}, previousPosition))>=0) {
+        currentItem.append(aString.substring(previousPosition, position));
+
+        if (aString.charAt(position)==aSeparator) {
+          result.add(currentItem.toString());
+          currentItem.delete(0, currentItem.length());
+        }
+        else {
+          currentItem.append(aString.charAt(position));
+          if (aString.length()>position+1) {
+            position=position+1;
+            currentItem.append(aString.charAt(position));
+          }
+        }
+        previousPosition = position + 1;
+      }
+      currentItem.append(aString.substring(previousPosition, aString.length()));
+      result.add(currentItem.toString());
+    }
+
+    return result;
+  }
+
+  public static String replicateString(String aString, int aCount) {
+    StringBuffer result = new StringBuffer();
+
+    for (int i=0; i<aCount; i++)
+      result.append(aString);
+
+    return result.toString();
+  }
+
+  public static String replicateChar(char aCharacter, int aCount) {
+    char result[] = new char[aCount];
+
+    for (int i=0; i<aCount; i++)
+      result[i]= aCharacter;
+
+    return new String(result);
+  }
+
+  public static String padStringLeft(String aString, int aLength, char aPadCharacter) {
+    if (aString.length()<aLength)
+      return replicateChar(aPadCharacter, aLength-aString.length()) + aString;
+    else
+      return aString;
+  }
+
+  private static final char HEX_CHARACTERS[] = {
+      '0', '1', '2', '3', '4', '5', '6', '7',
+      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
+  };
+
+  public static String convertToHex(long aData, int aNumberOfDigits) {
+    StringBuffer result = new StringBuffer();
+
+    for (int digit = aNumberOfDigits-1; digit>=0; digit--) {
+      int value = (int) (aData >> (digit*4)) & 0xf;
+      result.append(HEX_CHARACTERS[value]);
+    }
+
+    return result.toString();
+  }
+
+  public static String convertToHex(byte[] aData) {
+    StringBuffer result = new StringBuffer();
+
+    for (int i = 0; i<aData.length; i++) {
+      result.append(convertToHex(aData[i], 2));
+
+    }
+
+    return result.toString();
+  }
+}
index cc42565..ff32bc3 100755 (executable)
 
 package mir.util;
 
-import java.util.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
 
 
 /**
index 0074a08..2417e20 100755 (executable)
@@ -39,10 +39,6 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 
-import org.postgresql.largeobject.BlobInputStream;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-
 import mir.config.MirPropertiesConfiguration;
 import mir.log.LoggerWrapper;
 import mir.misc.FileUtil;
@@ -50,11 +46,15 @@ import mir.storage.StorageObject;
 import mir.storage.StorageObjectFailure;
 import mircoders.media.ImageProcessor;
 
+import org.postgresql.largeobject.BlobInputStream;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
+
 /**
  * Diese Klasse enth?lt die Daten eines MetaObjekts
  *
  * @author RK, mh, mir-coders
- * @version $Id: EntityImages.java,v 1.21 2003/04/30 00:37:27 zapata Exp $
+ * @version $Id: EntityImages.java,v 1.21.2.1 2003/10/23 14:55:28 rk Exp $
  */
 
 
index c5cee47..d8ca8f8 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.global;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileOutputStream;\r
-import java.util.Arrays;\r
-import java.util.Date;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Random;\r
-import java.util.Vector;\r
-import javax.servlet.http.Cookie;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import org.apache.commons.collections.ExtendedProperties;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.session.Request;\r
-import mir.util.DateTimeFunctions;\r
-import mir.util.GeneratorFormatAdapters;\r
-import mir.util.StringRoutines;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirAntiAbuseFilterType;\r
-\r
-\r
-public class Abuse {\r
-  private List filterRules;\r
-  private Map filterTypes;\r
-  private List filterTypeIds;\r
-  private int maxIdentifier;\r
-  private LoggerWrapper logger;\r
-  private int logSize;\r
-  private boolean logEnabled;\r
-  private boolean openPostingDisabled;\r
-  private boolean openPostingPassword;\r
-  private boolean cookieOnBlock;\r
-  private String articleBlockAction;\r
-  private String commentBlockAction;\r
-  private List log;\r
-  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");\r
-\r
-  private MirPropertiesConfiguration configuration;\r
-\r
-  private static String cookieName = MirGlobal.config().getString("Abuse.CookieName");\r
-  private static int cookieMaxAge = 60 * 60 * MirGlobal.config().getInt("Abuse.CookieMaxAge");\r
-\r
-  public Abuse() {\r
-    logger = new LoggerWrapper("Global.Abuse");\r
-    filterRules = new Vector();\r
-    maxIdentifier = 0;\r
-    log = new Vector();\r
-\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (Throwable e) {\r
-      throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
-    }\r
-\r
-    logSize = 100;\r
-    logEnabled = false;\r
-    articleBlockAction = "";\r
-    commentBlockAction = "";\r
-    openPostingPassword = false;\r
-    openPostingDisabled = false;\r
-    cookieOnBlock = false;\r
-\r
-    try {\r
-      filterTypes = new HashMap();\r
-      filterTypeIds = new Vector();\r
-\r
-      Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();\r
-\r
-      while (i.hasNext()) {\r
-        MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();\r
-        filterTypes.put(filterType.getName(), filterType);\r
-        filterTypeIds.add(filterType.getName());\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException("Can't get filter types: " + t.getMessage());\r
-    }\r
-\r
-    load();\r
-  }\r
-\r
-  private void setCookie(HttpServletResponse aResponse) {\r
-    Random random = new Random();\r
-\r
-    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));\r
-    cookie.setMaxAge(cookieMaxAge);\r
-    cookie.setPath("/");\r
-\r
-    if (aResponse != null)\r
-      aResponse.addCookie(cookie);\r
-  }\r
-\r
-  private boolean checkCookie(List aCookies) {\r
-    if (getCookieOnBlock()) {\r
-      Iterator i = aCookies.iterator();\r
-\r
-      while (i.hasNext()) {\r
-        Cookie cookie = (Cookie) i.next();\r
-\r
-        if (cookie.getName().equals(cookieName)) {\r
-          logger.debug("cookie match");\r
-          return true;\r
-        }\r
-      }\r
-    }\r
-\r
-    return false;\r
-  }\r
-\r
-  FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {\r
-    Iterator iterator = filterRules.iterator();\r
-\r
-    while (iterator.hasNext()) {\r
-      FilterRule rule = (FilterRule) iterator.next();\r
-\r
-      if (rule.test(anEntity, aRequest))\r
-        return rule;\r
-    }\r
-\r
-    return null;\r
-  }\r
-\r
-  public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      long time = System.currentTimeMillis();\r
-\r
-      FilterRule filterRule = findMatchingFilter(aComment, aRequest);\r
-\r
-      if (filterRule != null) {\r
-        logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");\r
-        filterRule.setLastHit(new GregorianCalendar().getTime());\r
-        MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());\r
-        setCookie(aResponse);\r
-        save();\r
-        logComment(aComment, aRequest, filterRule.getType(), filterRule.getExpression());\r
-      }\r
-      else\r
-        logComment(aComment, aRequest);\r
-\r
-\r
-      logger.info("checkComment: " + (System.currentTimeMillis() - time) + "ms");\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
-      logger.error("Abuse.checkComment: " + t.toString());\r
-    }\r
-  }\r
-\r
-  public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      long time = System.currentTimeMillis();\r
-\r
-      FilterRule filterRule = findMatchingFilter(anArticle, aRequest);\r
-\r
-      if (filterRule != null) {\r
-        logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");\r
-        filterRule.setLastHit(new GregorianCalendar().getTime());\r
-\r
-        StringBuffer line = new StringBuffer();\r
-\r
-        line.append(DateTimeFunctions.advancedDateFormat(\r
-            configuration.getString("Mir.DefaultDateTimeFormat"),\r
-            (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));\r
-\r
-        line.append(" ");\r
-        line.append("filter");\r
-\r
-        line.append(" ");\r
-        line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");\r
-        anArticle.appendToComments(line.toString());\r
-\r
-        MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());\r
-        setCookie(aResponse);\r
-        save();\r
-        logArticle(anArticle, aRequest, filterRule.getType(), filterRule.getExpression());\r
-      }\r
-      else\r
-        logArticle(anArticle, aRequest);\r
-\r
-      logger.info("checkArticle: " + (System.currentTimeMillis() - time) + "ms");\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
-      logger.error("Abuse.checkArticle: " + t.toString());\r
-    }\r
-  }\r
-\r
-  public boolean getLogEnabled() {\r
-    return logEnabled;\r
-  }\r
-\r
-  public void setLogEnabled(boolean anEnabled) {\r
-    if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))\r
-      logEnabled = anEnabled;\r
-    truncateLog();\r
-  }\r
-\r
-  public int getLogSize() {\r
-    return logSize;\r
-  }\r
-\r
-  public void setLogSize(int aSize) {\r
-    logSize = aSize;\r
-    truncateLog();\r
-  }\r
-\r
-  public boolean getOpenPostingDisabled() {\r
-    return openPostingDisabled;\r
-  }\r
-\r
-  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {\r
-    openPostingDisabled = anOpenPostingDisabled;\r
-  }\r
-\r
-  public boolean getOpenPostingPassword() {\r
-    return openPostingPassword;\r
-  }\r
-\r
-  public void setOpenPostingPassword(boolean anOpenPostingPassword) {\r
-    openPostingPassword = anOpenPostingPassword;\r
-  }\r
-\r
-  public boolean getCookieOnBlock() {\r
-    return cookieOnBlock;\r
-  }\r
-\r
-  public void setCookieOnBlock(boolean aCookieOnBlock) {\r
-    cookieOnBlock = aCookieOnBlock;\r
-  }\r
-\r
-  public String getArticleBlockAction() {\r
-    return articleBlockAction;\r
-  }\r
-\r
-  public void setArticleBlockAction(String anAction) {\r
-    articleBlockAction = anAction;\r
-  }\r
-\r
-  public String getCommentBlockAction() {\r
-    return commentBlockAction;\r
-  }\r
-\r
-  public void setCommentBlockAction(String anAction) {\r
-    commentBlockAction = anAction;\r
-  }\r
-\r
-  public List getLog() {\r
-    synchronized (log) {\r
-      try {\r
-        List result = new Vector();\r
-\r
-        Iterator i = log.iterator();\r
-        while (i.hasNext()) {\r
-          LogEntry logEntry = (LogEntry) i.next();\r
-          Map entry = new HashMap();\r
-\r
-          entry.put("ip", logEntry.getIpNumber());\r
-          entry.put("id", logEntry.getId());\r
-          entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));\r
-          if (logEntry.getIsArticle())\r
-            entry.put("type", "content");\r
-          else\r
-            entry.put("type", "comment");\r
-          entry.put("browser", logEntry.getBrowserString());\r
-          entry.put("hitfiltertype", logEntry.getHitFilterType());\r
-          entry.put("hitfilterexpression", logEntry.getHitFilterExpression());\r
-\r
-          result.add(entry);\r
-        }\r
-\r
-        return result;\r
-      }\r
-      catch (Throwable t) {\r
-        throw new RuntimeException(t.toString());\r
-      }\r
-    }\r
-  }\r
-\r
-  public void logComment(Entity aComment, Request aRequest) {\r
-    logComment(aComment, aRequest, null, null);\r
-  }\r
-\r
-  public void logComment(Entity aComment, Request aRequest, String aHitFilterType, String aHitFilterExpression) {\r
-    String ipAddress = aRequest.getHeader("ip");\r
-    String id = aComment.getId();\r
-    String browser = aRequest.getHeader("User-Agent");\r
-\r
-    logComment(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);\r
-  }\r
-\r
-  public void logArticle(Entity anArticle, Request aRequest) {\r
-    logArticle(anArticle, aRequest, null, null);\r
-  }\r
-\r
-  public void logArticle(Entity anArticle, Request aRequest, String aHitFilterType, String aHitFilterExpression) {\r
-    String ipAddress = aRequest.getHeader("ip");\r
-    String id = anArticle.getId();\r
-    String browser = aRequest.getHeader("User-Agent");\r
-\r
-    logArticle(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);\r
-  }\r
-\r
-  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {\r
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false, aHitFilterType, aHitFilterExpression));\r
-  }\r
-\r
-  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {\r
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true, aHitFilterType, aHitFilterExpression));\r
-  }\r
-\r
-  public void load() {\r
-    synchronized (filterRules) {\r
-      try {\r
-        ExtendedProperties configuration = new ExtendedProperties();\r
-\r
-        try {\r
-          configuration = new ExtendedProperties(configFile);\r
-        }\r
-        catch (FileNotFoundException e) {\r
-        }\r
-\r
-        getFilterConfig(filterRules, "abuse.filter", configuration);\r
-\r
-        setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));\r
-        setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));\r
-        setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));\r
-        setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));\r
-        setLogSize(configuration.getInt("abuse.logSize", 10));\r
-        setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));\r
-        setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));\r
-      }\r
-      catch (Throwable t) {\r
-        throw new RuntimeException(t.toString());\r
-      }\r
-    }\r
-  }\r
-\r
-  public void save() {\r
-    synchronized (filterRules) {\r
-      try {\r
-        ExtendedProperties configuration = new ExtendedProperties();\r
-\r
-        setFilterConfig(filterRules, "abuse.filter", configuration);\r
-\r
-        configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled() ? "1" : "0");\r
-        configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword() ? "1" : "0");\r
-        configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock() ? "1" : "0");\r
-        configuration.addProperty("abuse.logEnabled", getLogEnabled() ? "1" : "0");\r
-        configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));\r
-        configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());\r
-        configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());\r
-\r
-        configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");\r
-      }\r
-      catch (Throwable t) {\r
-        throw new RuntimeException(t.toString());\r
-      }\r
-    }\r
-  }\r
-\r
-  public List getFilterTypes() {\r
-    try {\r
-      List result = new Vector();\r
-\r
-      Iterator i = filterTypeIds.iterator();\r
-      while (i.hasNext()) {\r
-        String id = (String) i.next();\r
-\r
-        Map action = new HashMap();\r
-        action.put("resource", id);\r
-        action.put("identifier", id);\r
-\r
-        result.add(action);\r
-      }\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException("can't get article actions");\r
-    }\r
-  }\r
-\r
-  public List getArticleActions() {\r
-    try {\r
-      List result = new Vector();\r
-\r
-      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();\r
-      while (i.hasNext()) {\r
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-\r
-        Map action = new HashMap();\r
-        action.put("resource", operation.getName());\r
-        action.put("identifier", operation.getName());\r
-\r
-        result.add(action);\r
-      }\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException("can't get article actions");\r
-    }\r
-  }\r
-\r
-  public List getCommentActions() {\r
-    try {\r
-      List result = new Vector();\r
-\r
-      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();\r
-      while (i.hasNext()) {\r
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-\r
-        Map action = new HashMap();\r
-        action.put("resource", operation.getName());\r
-        action.put("identifier", operation.getName());\r
-\r
-        result.add(action);\r
-      }\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException("can't get comment actions");\r
-    }\r
-  }\r
-\r
-  public List getFilters() {\r
-    List result = new Vector();\r
-\r
-    synchronized (filterRules) {\r
-      Iterator i = filterRules.iterator();\r
-      while (i.hasNext()) {\r
-        FilterRule filter = (FilterRule) i.next();\r
-        result.add(filter.clone());\r
-      }\r
-      return result;\r
-    }\r
-  }\r
-\r
-  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
-    return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);\r
-  }\r
-\r
-  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {\r
-    return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);\r
-  }\r
-\r
-  public FilterRule getFilter(String anId) {\r
-    synchronized (filterRules) {\r
-      FilterRule result = (FilterRule) findFilter(filterRules, anId);\r
-      if (result == null)\r
-        return result;\r
-      else\r
-        return (FilterRule) result.clone();\r
-    }\r
-  }\r
-\r
-  public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
-    return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);\r
-  }\r
-\r
-  public void deleteFilter(String anIdentifier) {\r
-    deleteFilter(filterRules, anIdentifier);\r
-  }\r
-\r
-  public void moveFilterUp(String anIdentifier) {\r
-    moveFilter(filterRules, anIdentifier, -1);\r
-  }\r
-\r
-  public void moveFilterDown(String anIdentifier) {\r
-    moveFilter(filterRules, anIdentifier, 1);\r
-  }\r
-\r
-  private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {\r
-    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
-\r
-    if (type == null)\r
-      return "invalidtype";\r
-\r
-    if (!type.validate(anExpression)) {\r
-      return "invalidexpression";\r
-    }\r
-\r
-    FilterRule filter = new FilterRule();\r
-\r
-    filter.setId(generateId());\r
-    filter.setExpression(anExpression);\r
-    filter.setType(aType);\r
-    filter.setComments(aComments);\r
-    filter.setArticleAction(anArticleAction);\r
-    filter.setCommentAction(aCommentAction);\r
-    filter.setLastHit(aLastHit);\r
-\r
-    synchronized (aFilters) {\r
-      aFilters.add(filter);\r
-    }\r
-\r
-    return null;\r
-  }\r
-\r
-  private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
-    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
-\r
-    if (type == null)\r
-      return "invalidtype";\r
-\r
-    if (!type.validate(anExpression)) {\r
-      return "invalidexpression";\r
-    }\r
-\r
-    synchronized (aFilters) {\r
-      FilterRule filter = findFilter(aFilters, anIdentifier);\r
-\r
-      if (filter != null) {\r
-        filter.setExpression(anExpression);\r
-        filter.setType(aType);\r
-        filter.setCommentAction(aCommentAction);\r
-        filter.setArticleAction(anArticleAction);\r
-        filter.setComments(aComments);\r
-      }\r
-\r
-      return null;\r
-    }\r
-  }\r
-\r
-  private FilterRule findFilter(List aFilters, String anIdentifier) {\r
-    synchronized (aFilters) {\r
-      Iterator i = aFilters.iterator();\r
-      while (i.hasNext()) {\r
-        FilterRule filter = (FilterRule) i.next();\r
-\r
-        if (filter.getId().equals(anIdentifier)) {\r
-          return filter;\r
-        }\r
-      }\r
-    }\r
-\r
-    return null;\r
-  }\r
-\r
-  private void moveFilter(List aFilters, String anIdentifier, int aDirection) {\r
-    synchronized (aFilters) {\r
-      for (int i = 0; i < aFilters.size(); i++) {\r
-        FilterRule rule = (FilterRule) aFilters.get(i);\r
-\r
-        if (rule.getId().equals(anIdentifier) && (i + aDirection >= 0) && (i + aDirection < aFilters.size())) {\r
-          aFilters.remove(rule);\r
-          aFilters.add(i + aDirection, rule);\r
-          break;\r
-        }\r
-      }\r
-    }\r
-  }\r
-\r
-  private void deleteFilter(List aFilters, String anIdentifier) {\r
-    synchronized (aFilters) {\r
-      FilterRule filter = findFilter(aFilters, anIdentifier);\r
-\r
-      if (filter != null) {\r
-        aFilters.remove(filter);\r
-      }\r
-    }\r
-  }\r
-\r
-  private String generateId() {\r
-    synchronized (this) {\r
-      maxIdentifier = maxIdentifier + 1;\r
-\r
-      return Integer.toString(maxIdentifier);\r
-    }\r
-  }\r
-\r
-  public class FilterRule {\r
-    private String identifier;\r
-    private String expression;\r
-    private String type;\r
-    private String comments;\r
-    private String articleAction;\r
-    private String commentAction;\r
-    private Date lastHit;\r
-\r
-    public FilterRule() {\r
-      expression = "";\r
-      type = "";\r
-      identifier = "";\r
-      comments = "";\r
-      articleAction = articleBlockAction;\r
-      commentAction = commentBlockAction;\r
-      lastHit = null;\r
-    }\r
-\r
-    public Date getLastHit() {\r
-      return lastHit;\r
-    }\r
-\r
-    public void setLastHit(Date aDate) {\r
-      lastHit = aDate;\r
-    }\r
-\r
-    public String getId() {\r
-      return identifier;\r
-    }\r
-\r
-    public void setId(String anId) {\r
-      identifier = anId;\r
-    }\r
-\r
-    public String getExpression() {\r
-      return expression;\r
-    }\r
-\r
-    public void setExpression(String anExpression) {\r
-      expression = anExpression;\r
-    }\r
-\r
-    public String getType() {\r
-      return type;\r
-    }\r
-\r
-    public void setType(String aType) {\r
-      type = aType;\r
-    }\r
-\r
-    public void setComments(String aComments) {\r
-      comments = aComments;\r
-    }\r
-\r
-    public String getComments() {\r
-      return comments;\r
-    }\r
-\r
-    public String getArticleAction() {\r
-      return articleAction;\r
-    }\r
-\r
-    public void setArticleAction(String anArticleAction) {\r
-      articleAction = anArticleAction;\r
-    }\r
-\r
-    public String getCommentAction() {\r
-      return commentAction;\r
-    }\r
-\r
-    public void setCommentAction(String aCommentAction) {\r
-      commentAction = aCommentAction;\r
-    }\r
-\r
-    public boolean test(Entity anEntity, Request aRequest) {\r
-      MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);\r
-      try {\r
-        if (filterType != null)\r
-          return filterType.test(expression, anEntity, aRequest);\r
-      }\r
-      catch (Throwable t) {\r
-        logger.error("error while testing " + type + "-filter '" + expression + "'");\r
-      }\r
-\r
-      return false;\r
-    };\r
-\r
-    public Object clone() {\r
-      FilterRule result = new FilterRule();\r
-      result.setComments(getComments());\r
-      result.setExpression(getExpression());\r
-      result.setId(getId());\r
-      result.setType(getType());\r
-      result.setArticleAction(getArticleAction());\r
-      result.setCommentAction(getCommentAction());\r
-      result.setLastHit(getLastHit());\r
-\r
-      return result;\r
-    }\r
-  }\r
-\r
-  private String escapeFilterPart(String aFilterPart) {\r
-    return StringRoutines.replaceStringCharacters(aFilterPart,\r
-        new char[] {'\\', ':', '\n', '\r', '\t', ' '},\r
-        new String[] {"\\\\", "\\:", "\\n", "\\r", "\\t", "\\ "});\r
-  }\r
-\r
-  private String deescapeFilterPart(String aFilterPart) {\r
-    return StringRoutines.replaceEscapedStringCharacters(aFilterPart,\r
-        '\\',\r
-        new char[] {'\\', ':', 'n', 'r', 't', ' '},\r
-        new String[] {"\\", ":", "\n", "\r", "\t", " "});\r
-  }\r
-\r
-  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
-    synchronized (aFilters) {\r
-      Iterator i = aFilters.iterator();\r
-\r
-      while (i.hasNext()) {\r
-        FilterRule filter = (FilterRule) i.next();\r
-\r
-        String filterconfig =\r
-            escapeFilterPart(filter.getType()) + ":" +\r
-            escapeFilterPart(filter.getExpression()) + ":" +\r
-            escapeFilterPart(filter.getArticleAction()) + ":" +\r
-            escapeFilterPart(filter.getCommentAction()) + ":" +\r
-            escapeFilterPart(filter.getComments()) + ":";\r
-\r
-        if (filter.getLastHit() != null)\r
-          filterconfig = filterconfig + filter.getLastHit().getTime();\r
-\r
-        aConfiguration.addProperty(aConfigKey, filterconfig);\r
-      }\r
-    }\r
-  }\r
-\r
-  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
-    synchronized (aFilters) {\r
-      aFilters.clear();\r
-\r
-      if (aConfiguration.getStringArray(aConfigKey) != null) {\r
-\r
-        Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).\r
-            iterator();\r
-\r
-        while (i.hasNext()) {\r
-          String filter = (String) i.next();\r
-          List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');\r
-          if (parts.size() == 2) {\r
-            parts.add(articleBlockAction);\r
-            parts.add(commentBlockAction);\r
-            parts.add("");\r
-            parts.add("");\r
-          }\r
-\r
-          if (parts.size() >= 5) {\r
-            Date lastHit = null;\r
-\r
-            if (parts.size() >= 6) {\r
-              String lastHitString = (String) parts.get(5);\r
-\r
-              try {\r
-                lastHit = new Date(Long.parseLong(lastHitString));\r
-              }\r
-              catch (Throwable t) {\r
-              }\r
-            }\r
-\r
-            addFilter(deescapeFilterPart( (String) parts.get(0)),\r
-                      deescapeFilterPart( (String) parts.get(1)),\r
-                      deescapeFilterPart( (String) parts.get(4)),\r
-                      deescapeFilterPart( (String) parts.get(3)),\r
-                      deescapeFilterPart( (String) parts.get(2)), lastHit);\r
-          }\r
-        }\r
-      }\r
-    }\r
-  }\r
-\r
-  private static class LogEntry {\r
-    private String ipNumber;\r
-    private String browserString;\r
-    private String id;\r
-    private Date timeStamp;\r
-    private boolean isArticle;\r
-    private String hitFilterType;\r
-    private String hitFilterExpression;\r
-\r
-    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle, String aHitFilterType, String aHitFilterExpression) {\r
-      ipNumber = anIpNumber;\r
-      browserString = aBrowserString;\r
-      id = anId;\r
-      isArticle = anIsArticle;\r
-      timeStamp = aTimeStamp;\r
-      hitFilterType = aHitFilterType;\r
-      hitFilterExpression = aHitFilterExpression;\r
-    }\r
-\r
-    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {\r
-      this(aTimeStamp, anIpNumber, aBrowserString, anId, anIsArticle, null, null);\r
-    }\r
-\r
-    public String getIpNumber() {\r
-      return ipNumber;\r
-    }\r
-\r
-    public String getBrowserString() {\r
-      return browserString;\r
-    }\r
-\r
-    public String getId() {\r
-      return id;\r
-    }\r
-\r
-    public String getHitFilterType() {\r
-      return hitFilterType;\r
-    }\r
-\r
-    public String getHitFilterExpression() {\r
-      return hitFilterExpression;\r
-    }\r
-\r
-    public Date getTimeStamp() {\r
-      return timeStamp;\r
-    }\r
-\r
-    public boolean getIsArticle() {\r
-      return isArticle;\r
-    }\r
-  }\r
-\r
-  private void truncateLog() {\r
-    synchronized (log) {\r
-      if (!logEnabled)\r
-        log.clear();\r
-      else {\r
-        while (log.size() > 0 && log.size() > logSize) {\r
-          log.remove(0);\r
-        }\r
-      }\r
-    }\r
-  };\r
-\r
-  private void appendLog(LogEntry anEntry) {\r
-    synchronized (log) {\r
-      if (logEnabled) {\r
-        log.add(anEntry);\r
-        truncateLog();\r
-      }\r
-    }\r
-  }\r
-}\r
+/*
+ * 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 mircoders.global;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Vector;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.util.DateTimeFunctions;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.MirAntiAbuseFilterType;
+
+import org.apache.commons.collections.ExtendedProperties;
+
+
+public class Abuse {
+  private List filterRules;
+  private Map filterTypes;
+  private List filterTypeIds;
+  private int maxIdentifier;
+  private LoggerWrapper logger;
+  private int logSize;
+  private boolean logEnabled;
+  private boolean openPostingDisabled;
+  private boolean openPostingPassword;
+  private boolean cookieOnBlock;
+  private String articleBlockAction;
+  private String commentBlockAction;
+  private List log;
+  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
+
+  private MirPropertiesConfiguration configuration;
+
+  private static String cookieName = MirGlobal.config().getString("Abuse.CookieName");
+  private static int cookieMaxAge = 60 * 60 * MirGlobal.config().getInt("Abuse.CookieMaxAge");
+
+  public Abuse() {
+    logger = new LoggerWrapper("Global.Abuse");
+    filterRules = new Vector();
+    maxIdentifier = 0;
+    log = new Vector();
+
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (Throwable e) {
+      throw new RuntimeException("Can't get configuration: " + e.getMessage());
+    }
+
+    logSize = 100;
+    logEnabled = false;
+    articleBlockAction = "";
+    commentBlockAction = "";
+    openPostingPassword = false;
+    openPostingDisabled = false;
+    cookieOnBlock = false;
+
+    try {
+      filterTypes = new HashMap();
+      filterTypeIds = new Vector();
+
+      Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
+
+      while (i.hasNext()) {
+        MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();
+        filterTypes.put(filterType.getName(), filterType);
+        filterTypeIds.add(filterType.getName());
+      }
+    }
+    catch (Throwable t) {
+      throw new RuntimeException("Can't get filter types: " + t.getMessage());
+    }
+
+    load();
+  }
+
+  private void setCookie(HttpServletResponse aResponse) {
+    Random random = new Random();
+
+    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
+    cookie.setMaxAge(cookieMaxAge);
+    cookie.setPath("/");
+
+    if (aResponse != null)
+      aResponse.addCookie(cookie);
+  }
+
+  private boolean checkCookie(List aCookies) {
+    if (getCookieOnBlock()) {
+      Iterator i = aCookies.iterator();
+
+      while (i.hasNext()) {
+        Cookie cookie = (Cookie) i.next();
+
+        if (cookie.getName().equals(cookieName)) {
+          logger.debug("cookie match");
+          return true;
+        }
+      }
+    }
+
+    return false;
+  }
+
+  FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {
+    Iterator iterator = filterRules.iterator();
+
+    while (iterator.hasNext()) {
+      FilterRule rule = (FilterRule) iterator.next();
+
+      if (rule.test(anEntity, aRequest))
+        return rule;
+    }
+
+    return null;
+  }
+
+  public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
+    try {
+      long time = System.currentTimeMillis();
+
+      FilterRule filterRule = findMatchingFilter(aComment, aRequest);
+
+      if (filterRule != null) {
+        logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
+        filterRule.setLastHit(new GregorianCalendar().getTime());
+        MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());
+        setCookie(aResponse);
+        save();
+        logComment(aComment, aRequest, filterRule.getType(), filterRule.getExpression());
+      }
+      else
+        logComment(aComment, aRequest);
+
+
+      logger.info("checkComment: " + (System.currentTimeMillis() - time) + "ms");
+    }
+    catch (Throwable t) {
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      logger.error("Abuse.checkComment: " + t.toString());
+    }
+  }
+
+  public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
+    try {
+      long time = System.currentTimeMillis();
+
+      FilterRule filterRule = findMatchingFilter(anArticle, aRequest);
+
+      if (filterRule != null) {
+        logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
+        filterRule.setLastHit(new GregorianCalendar().getTime());
+
+        StringBuffer line = new StringBuffer();
+
+        line.append(DateTimeFunctions.advancedDateFormat(
+            configuration.getString("Mir.DefaultDateTimeFormat"),
+            (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));
+
+        line.append(" ");
+        line.append("filter");
+
+        line.append(" ");
+        line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");
+        anArticle.appendToComments(line.toString());
+
+        MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());
+        setCookie(aResponse);
+        save();
+        logArticle(anArticle, aRequest, filterRule.getType(), filterRule.getExpression());
+      }
+      else
+        logArticle(anArticle, aRequest);
+
+      logger.info("checkArticle: " + (System.currentTimeMillis() - time) + "ms");
+    }
+    catch (Throwable t) {
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      logger.error("Abuse.checkArticle: " + t.toString());
+    }
+  }
+
+  public boolean getLogEnabled() {
+    return logEnabled;
+  }
+
+  public void setLogEnabled(boolean anEnabled) {
+    if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))
+      logEnabled = anEnabled;
+    truncateLog();
+  }
+
+  public int getLogSize() {
+    return logSize;
+  }
+
+  public void setLogSize(int aSize) {
+    logSize = aSize;
+    truncateLog();
+  }
+
+  public boolean getOpenPostingDisabled() {
+    return openPostingDisabled;
+  }
+
+  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
+    openPostingDisabled = anOpenPostingDisabled;
+  }
+
+  public boolean getOpenPostingPassword() {
+    return openPostingPassword;
+  }
+
+  public void setOpenPostingPassword(boolean anOpenPostingPassword) {
+    openPostingPassword = anOpenPostingPassword;
+  }
+
+  public boolean getCookieOnBlock() {
+    return cookieOnBlock;
+  }
+
+  public void setCookieOnBlock(boolean aCookieOnBlock) {
+    cookieOnBlock = aCookieOnBlock;
+  }
+
+  public String getArticleBlockAction() {
+    return articleBlockAction;
+  }
+
+  public void setArticleBlockAction(String anAction) {
+    articleBlockAction = anAction;
+  }
+
+  public String getCommentBlockAction() {
+    return commentBlockAction;
+  }
+
+  public void setCommentBlockAction(String anAction) {
+    commentBlockAction = anAction;
+  }
+
+  public List getLog() {
+    synchronized (log) {
+      try {
+        List result = new Vector();
+
+        Iterator i = log.iterator();
+        while (i.hasNext()) {
+          LogEntry logEntry = (LogEntry) i.next();
+          Map entry = new HashMap();
+
+          entry.put("ip", logEntry.getIpNumber());
+          entry.put("id", logEntry.getId());
+          entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
+          if (logEntry.getIsArticle())
+            entry.put("type", "content");
+          else
+            entry.put("type", "comment");
+          entry.put("browser", logEntry.getBrowserString());
+          entry.put("hitfiltertype", logEntry.getHitFilterType());
+          entry.put("hitfilterexpression", logEntry.getHitFilterExpression());
+
+          result.add(entry);
+        }
+
+        return result;
+      }
+      catch (Throwable t) {
+        throw new RuntimeException(t.toString());
+      }
+    }
+  }
+
+  public void logComment(Entity aComment, Request aRequest) {
+    logComment(aComment, aRequest, null, null);
+  }
+
+  public void logComment(Entity aComment, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+    String ipAddress = aRequest.getHeader("ip");
+    String id = aComment.getId();
+    String browser = aRequest.getHeader("User-Agent");
+
+    logComment(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+  }
+
+  public void logArticle(Entity anArticle, Request aRequest) {
+    logArticle(anArticle, aRequest, null, null);
+  }
+
+  public void logArticle(Entity anArticle, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+    String ipAddress = aRequest.getHeader("ip");
+    String id = anArticle.getId();
+    String browser = aRequest.getHeader("User-Agent");
+
+    logArticle(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+  }
+
+  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false, aHitFilterType, aHitFilterExpression));
+  }
+
+  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true, aHitFilterType, aHitFilterExpression));
+  }
+
+  public void load() {
+    synchronized (filterRules) {
+      try {
+        ExtendedProperties configuration = new ExtendedProperties();
+
+        try {
+          configuration = new ExtendedProperties(configFile);
+        }
+        catch (FileNotFoundException e) {
+        }
+
+        getFilterConfig(filterRules, "abuse.filter", configuration);
+
+        setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
+        setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
+        setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
+        setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
+        setLogSize(configuration.getInt("abuse.logSize", 10));
+        setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
+        setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
+      }
+      catch (Throwable t) {
+        throw new RuntimeException(t.toString());
+      }
+    }
+  }
+
+  public void save() {
+    synchronized (filterRules) {
+      try {
+        ExtendedProperties configuration = new ExtendedProperties();
+
+        setFilterConfig(filterRules, "abuse.filter", configuration);
+
+        configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled() ? "1" : "0");
+        configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword() ? "1" : "0");
+        configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock() ? "1" : "0");
+        configuration.addProperty("abuse.logEnabled", getLogEnabled() ? "1" : "0");
+        configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
+        configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
+        configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
+
+        configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
+      }
+      catch (Throwable t) {
+        throw new RuntimeException(t.toString());
+      }
+    }
+  }
+
+  public List getFilterTypes() {
+    try {
+      List result = new Vector();
+
+      Iterator i = filterTypeIds.iterator();
+      while (i.hasNext()) {
+        String id = (String) i.next();
+
+        Map action = new HashMap();
+        action.put("resource", id);
+        action.put("identifier", id);
+
+        result.add(action);
+      }
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RuntimeException("can't get article actions");
+    }
+  }
+
+  public List getArticleActions() {
+    try {
+      List result = new Vector();
+
+      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
+      while (i.hasNext()) {
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+
+        Map action = new HashMap();
+        action.put("resource", operation.getName());
+        action.put("identifier", operation.getName());
+
+        result.add(action);
+      }
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RuntimeException("can't get article actions");
+    }
+  }
+
+  public List getCommentActions() {
+    try {
+      List result = new Vector();
+
+      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
+      while (i.hasNext()) {
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+
+        Map action = new HashMap();
+        action.put("resource", operation.getName());
+        action.put("identifier", operation.getName());
+
+        result.add(action);
+      }
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RuntimeException("can't get comment actions");
+    }
+  }
+
+  public List getFilters() {
+    List result = new Vector();
+
+    synchronized (filterRules) {
+      Iterator i = filterRules.iterator();
+      while (i.hasNext()) {
+        FilterRule filter = (FilterRule) i.next();
+        result.add(filter.clone());
+      }
+      return result;
+    }
+  }
+
+  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+    return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);
+  }
+
+  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {
+    return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);
+  }
+
+  public FilterRule getFilter(String anId) {
+    synchronized (filterRules) {
+      FilterRule result = (FilterRule) findFilter(filterRules, anId);
+      if (result == null)
+        return result;
+      else
+        return (FilterRule) result.clone();
+    }
+  }
+
+  public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+    return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);
+  }
+
+  public void deleteFilter(String anIdentifier) {
+    deleteFilter(filterRules, anIdentifier);
+  }
+
+  public void moveFilterUp(String anIdentifier) {
+    moveFilter(filterRules, anIdentifier, -1);
+  }
+
+  public void moveFilterDown(String anIdentifier) {
+    moveFilter(filterRules, anIdentifier, 1);
+  }
+
+  private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {
+    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
+
+    if (type == null)
+      return "invalidtype";
+
+    if (!type.validate(anExpression)) {
+      return "invalidexpression";
+    }
+
+    FilterRule filter = new FilterRule();
+
+    filter.setId(generateId());
+    filter.setExpression(anExpression);
+    filter.setType(aType);
+    filter.setComments(aComments);
+    filter.setArticleAction(anArticleAction);
+    filter.setCommentAction(aCommentAction);
+    filter.setLastHit(aLastHit);
+
+    synchronized (aFilters) {
+      aFilters.add(filter);
+    }
+
+    return null;
+  }
+
+  private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
+
+    if (type == null)
+      return "invalidtype";
+
+    if (!type.validate(anExpression)) {
+      return "invalidexpression";
+    }
+
+    synchronized (aFilters) {
+      FilterRule filter = findFilter(aFilters, anIdentifier);
+
+      if (filter != null) {
+        filter.setExpression(anExpression);
+        filter.setType(aType);
+        filter.setCommentAction(aCommentAction);
+        filter.setArticleAction(anArticleAction);
+        filter.setComments(aComments);
+      }
+
+      return null;
+    }
+  }
+
+  private FilterRule findFilter(List aFilters, String anIdentifier) {
+    synchronized (aFilters) {
+      Iterator i = aFilters.iterator();
+      while (i.hasNext()) {
+        FilterRule filter = (FilterRule) i.next();
+
+        if (filter.getId().equals(anIdentifier)) {
+          return filter;
+        }
+      }
+    }
+
+    return null;
+  }
+
+  private void moveFilter(List aFilters, String anIdentifier, int aDirection) {
+    synchronized (aFilters) {
+      for (int i = 0; i < aFilters.size(); i++) {
+        FilterRule rule = (FilterRule) aFilters.get(i);
+
+        if (rule.getId().equals(anIdentifier) && (i + aDirection >= 0) && (i + aDirection < aFilters.size())) {
+          aFilters.remove(rule);
+          aFilters.add(i + aDirection, rule);
+          break;
+        }
+      }
+    }
+  }
+
+  private void deleteFilter(List aFilters, String anIdentifier) {
+    synchronized (aFilters) {
+      FilterRule filter = findFilter(aFilters, anIdentifier);
+
+      if (filter != null) {
+        aFilters.remove(filter);
+      }
+    }
+  }
+
+  private String generateId() {
+    synchronized (this) {
+      maxIdentifier = maxIdentifier + 1;
+
+      return Integer.toString(maxIdentifier);
+    }
+  }
+
+  public class FilterRule {
+    private String identifier;
+    private String expression;
+    private String type;
+    private String comments;
+    private String articleAction;
+    private String commentAction;
+    private Date lastHit;
+
+    public FilterRule() {
+      expression = "";
+      type = "";
+      identifier = "";
+      comments = "";
+      articleAction = articleBlockAction;
+      commentAction = commentBlockAction;
+      lastHit = null;
+    }
+
+    public Date getLastHit() {
+      return lastHit;
+    }
+
+    public void setLastHit(Date aDate) {
+      lastHit = aDate;
+    }
+
+    public String getId() {
+      return identifier;
+    }
+
+    public void setId(String anId) {
+      identifier = anId;
+    }
+
+    public String getExpression() {
+      return expression;
+    }
+
+    public void setExpression(String anExpression) {
+      expression = anExpression;
+    }
+
+    public String getType() {
+      return type;
+    }
+
+    public void setType(String aType) {
+      type = aType;
+    }
+
+    public void setComments(String aComments) {
+      comments = aComments;
+    }
+
+    public String getComments() {
+      return comments;
+    }
+
+    public String getArticleAction() {
+      return articleAction;
+    }
+
+    public void setArticleAction(String anArticleAction) {
+      articleAction = anArticleAction;
+    }
+
+    public String getCommentAction() {
+      return commentAction;
+    }
+
+    public void setCommentAction(String aCommentAction) {
+      commentAction = aCommentAction;
+    }
+
+    public boolean test(Entity anEntity, Request aRequest) {
+      MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);
+      try {
+        if (filterType != null)
+          return filterType.test(expression, anEntity, aRequest);
+      }
+      catch (Throwable t) {
+        logger.error("error while testing " + type + "-filter '" + expression + "'");
+      }
+
+      return false;
+    };
+
+    public Object clone() {
+      FilterRule result = new FilterRule();
+      result.setComments(getComments());
+      result.setExpression(getExpression());
+      result.setId(getId());
+      result.setType(getType());
+      result.setArticleAction(getArticleAction());
+      result.setCommentAction(getCommentAction());
+      result.setLastHit(getLastHit());
+
+      return result;
+    }
+  }
+
+  private String escapeFilterPart(String aFilterPart) {
+    return StringRoutines.replaceStringCharacters(aFilterPart,
+        new char[] {'\\', ':', '\n', '\r', '\t', ' '},
+        new String[] {"\\\\", "\\:", "\\n", "\\r", "\\t", "\\ "});
+  }
+
+  private String deescapeFilterPart(String aFilterPart) {
+    return StringRoutines.replaceEscapedStringCharacters(aFilterPart,
+        '\\',
+        new char[] {'\\', ':', 'n', 'r', 't', ' '},
+        new String[] {"\\", ":", "\n", "\r", "\t", " "});
+  }
+
+  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
+    synchronized (aFilters) {
+      Iterator i = aFilters.iterator();
+
+      while (i.hasNext()) {
+        FilterRule filter = (FilterRule) i.next();
+
+        String filterconfig =
+            escapeFilterPart(filter.getType()) + ":" +
+            escapeFilterPart(filter.getExpression()) + ":" +
+            escapeFilterPart(filter.getArticleAction()) + ":" +
+            escapeFilterPart(filter.getCommentAction()) + ":" +
+            escapeFilterPart(filter.getComments()) + ":";
+
+        if (filter.getLastHit() != null)
+          filterconfig = filterconfig + filter.getLastHit().getTime();
+
+        aConfiguration.addProperty(aConfigKey, filterconfig);
+      }
+    }
+  }
+
+  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
+    synchronized (aFilters) {
+      aFilters.clear();
+
+      if (aConfiguration.getStringArray(aConfigKey) != null) {
+
+        Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).
+            iterator();
+
+        while (i.hasNext()) {
+          String filter = (String) i.next();
+          List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');
+          if (parts.size() == 2) {
+            parts.add(articleBlockAction);
+            parts.add(commentBlockAction);
+            parts.add("");
+            parts.add("");
+          }
+
+          if (parts.size() >= 5) {
+            Date lastHit = null;
+
+            if (parts.size() >= 6) {
+              String lastHitString = (String) parts.get(5);
+
+              try {
+                lastHit = new Date(Long.parseLong(lastHitString));
+              }
+              catch (Throwable t) {
+              }
+            }
+
+            addFilter(deescapeFilterPart( (String) parts.get(0)),
+                      deescapeFilterPart( (String) parts.get(1)),
+                      deescapeFilterPart( (String) parts.get(4)),
+                      deescapeFilterPart( (String) parts.get(3)),
+                      deescapeFilterPart( (String) parts.get(2)), lastHit);
+          }
+        }
+      }
+    }
+  }
+
+  private static class LogEntry {
+    private String ipNumber;
+    private String browserString;
+    private String id;
+    private Date timeStamp;
+    private boolean isArticle;
+    private String hitFilterType;
+    private String hitFilterExpression;
+
+    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle, String aHitFilterType, String aHitFilterExpression) {
+      ipNumber = anIpNumber;
+      browserString = aBrowserString;
+      id = anId;
+      isArticle = anIsArticle;
+      timeStamp = aTimeStamp;
+      hitFilterType = aHitFilterType;
+      hitFilterExpression = aHitFilterExpression;
+    }
+
+    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
+      this(aTimeStamp, anIpNumber, aBrowserString, anId, anIsArticle, null, null);
+    }
+
+    public String getIpNumber() {
+      return ipNumber;
+    }
+
+    public String getBrowserString() {
+      return browserString;
+    }
+
+    public String getId() {
+      return id;
+    }
+
+    public String getHitFilterType() {
+      return hitFilterType;
+    }
+
+    public String getHitFilterExpression() {
+      return hitFilterExpression;
+    }
+
+    public Date getTimeStamp() {
+      return timeStamp;
+    }
+
+    public boolean getIsArticle() {
+      return isArticle;
+    }
+  }
+
+  private void truncateLog() {
+    synchronized (log) {
+      if (!logEnabled)
+        log.clear();
+      else {
+        while (log.size() > 0 && log.size() > logSize) {
+          log.remove(0);
+        }
+      }
+    }
+  };
+
+  private void appendLog(LogEntry anEntry) {
+    synchronized (log) {
+      if (logEnabled) {
+        log.add(anEntry);
+        truncateLog();
+      }
+    }
+  }
+}
index 4eb40e6..ea8e599 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.global;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.ConfigException;\r
-import mircoders.accesscontrol.AccessControl;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirCachingLocalizerDecorator;\r
-import mircoders.localizer.MirLocalizer;\r
-\r
-public class MirGlobal {\r
-  static private MirPropertiesConfiguration configuration;\r
-  static private MirLocalizer localizer;\r
-  static private ProducerEngine producerEngine;\r
-  static private Abuse abuse;\r
-  static private MRUCache mruCache;\r
-  static private AccessControl accessControl;\r
-  static private Map articleOperations;\r
-  static private Map commentOperations;\r
-  static private Map loggedInUsers = new HashMap();\r
-  static private LoggerWrapper logger = new LoggerWrapper("Global");\r
-  static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");\r
-\r
-  public synchronized static MirLocalizer localizer() {\r
-    String localizerClassName;\r
-    Class localizerClass;\r
-\r
-    if (localizer == null ) {\r
-      localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");\r
-\r
-      try {\r
-        localizerClass = Class.forName(localizerClassName);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ConfigException("localizer class '" + localizerClassName + "' not found: " + t.toString());\r
-      }\r
-\r
-      if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))\r
-        throw new ConfigException("localizer class '" + localizerClassName + "' is not assignable from MirLocalizer");\r
-\r
-      try {\r
-        localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ConfigException("localizer class '" + localizerClassName + "' cannot be instantiated: " + t.toString());\r
-      }\r
-    }\r
-\r
-    return localizer;\r
-  }\r
-\r
-  public static Abuse abuse() {\r
-    if (abuse==null) {\r
-      synchronized(MirGlobal.class) {\r
-        if (abuse==null)\r
-          abuse = new Abuse();\r
-      }\r
-    }\r
-\r
-    return abuse;\r
-  }\r
-\r
-  public static MirPropertiesConfiguration config() {\r
-    try {\r
-      return MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (PropertiesConfigExc e) {\r
-      throw new RuntimeException(e.getMessage());\r
-    }\r
-  }\r
-\r
-  public static ProducerEngine producerEngine() {\r
-    if (producerEngine == null) {\r
-      producerEngine = new ProducerEngine();\r
-    }\r
-\r
-    return producerEngine;\r
-  }\r
-\r
-  public static MRUCache mruCache() {\r
-    synchronized(MirGlobal.class) {\r
-      if (mruCache == null) {\r
-        mruCache = new MRUCache();\r
-      }\r
-      return mruCache;\r
-    }\r
-  }\r
-\r
-  public static synchronized AccessControl accessControl() {\r
-    if (accessControl == null) {\r
-      accessControl=new AccessControl();\r
-    }\r
-\r
-    return accessControl;\r
-  }\r
-\r
-  public static void performArticleOperation(EntityUsers aUser, EntityContent  anArticle, String anOperation) {\r
-    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getArticleOperationForName(anOperation);\r
-\r
-    try {\r
-      EntityAdapter user = null;\r
-      if (aUser!=null)\r
-          user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
-\r
-      if (operation!=null)\r
-        operation.perform(\r
-            user,\r
-            localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));\r
-    }\r
-    catch (Throwable t) {\r
-      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
-\r
-      throw new RuntimeException(t.toString());\r
-    }\r
-  }\r
-\r
-  public static void performCommentOperation(EntityUsers aUser, EntityComment  aComment, String anOperation) {\r
-    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getCommentOperationForName(anOperation);\r
-\r
-    try {\r
-      EntityAdapter user = null;\r
-      if (aUser!=null)\r
-          user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
-\r
-      if (operation!=null)\r
-        operation.perform(\r
-            user,\r
-            localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException(t.toString());\r
-    }\r
-  }\r
-\r
-  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getArticleOperationForName(String aName) {\r
-    try {\r
-      if (articleOperations == null) {\r
-        articleOperations = new HashMap();\r
-        Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();\r
-        while (i.hasNext()) {\r
-          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-          articleOperations.put(operation.getName(), operation);\r
-        }\r
-      }\r
-\r
-      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) articleOperations.get(aName);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException(t.toString());\r
-    }\r
-  }\r
-\r
-  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getCommentOperationForName(String aName) {\r
-    try {\r
-      if (commentOperations == null) {\r
-        commentOperations = new HashMap();\r
-        Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();\r
-        while (i.hasNext()) {\r
-          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-          commentOperations.put(operation.getName(), operation);\r
-        }\r
-      }\r
-\r
-      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) commentOperations.get(aName);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new RuntimeException(t.toString());\r
-    }\r
-  }\r
-\r
-\r
-  public static List getLoggedInUsers() {\r
-    List result = new Vector();\r
-\r
-    synchronized (loggedInUsers) {\r
-      Iterator i = loggedInUsers.entrySet().iterator();\r
-\r
-      while (i.hasNext()) {\r
-        Map.Entry entry = (Map.Entry) i.next();\r
-\r
-        Map item = new HashMap();\r
-        item.put("name", entry.getKey());\r
-        item.put("count", entry.getValue());\r
-        result.add(item);\r
-      }\r
-    }\r
-\r
-    return result;\r
-  }\r
-\r
-  public static void registerLogin(String aName) {\r
-    modifyLoggedInCount(aName, 1);\r
-  }\r
-\r
-  public static void registerLogout(String aName) {\r
-    modifyLoggedInCount(aName, -1);\r
-  }\r
-\r
-  private static void modifyLoggedInCount(String aName, int aModifier) {\r
-    synchronized (loggedInUsers) {\r
-      Integer count = (Integer) loggedInUsers.get(aName);\r
-      if (count==null)\r
-        count = new Integer(0);\r
-\r
-      if (count.intValue()+aModifier<=0) {\r
-        loggedInUsers.remove(aName);\r
-      }\r
-      else {\r
-        loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));\r
-      }\r
-    }\r
-  }\r
-\r
-  public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {\r
-    try {\r
-      if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {\r
-        String user = "unknown (" + aUser.toString() + ")";\r
-        if (aUser != null)\r
-          user = aUser.getValue("login");\r
-        adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());\r
-    }\r
-  }\r
-}\r
-\r
-\r
+/*
+ * 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 mircoders.global;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.ConfigException;
+import mircoders.accesscontrol.AccessControl;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUsers;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.MirCachingLocalizerDecorator;
+import mircoders.localizer.MirLocalizer;
+
+public class MirGlobal {
+  static private MirPropertiesConfiguration configuration;
+  static private MirLocalizer localizer;
+  static private ProducerEngine producerEngine;
+  static private Abuse abuse;
+  static private MRUCache mruCache;
+  static private AccessControl accessControl;
+  static private Map articleOperations;
+  static private Map commentOperations;
+  static private Map loggedInUsers = new HashMap();
+  static private LoggerWrapper logger = new LoggerWrapper("Global");
+  static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");
+
+  public synchronized static MirLocalizer localizer() {
+    String localizerClassName;
+    Class localizerClass;
+
+    if (localizer == null ) {
+      localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");
+
+      try {
+        localizerClass = Class.forName(localizerClassName);
+      }
+      catch (Throwable t) {
+        throw new ConfigException("localizer class '" + localizerClassName + "' not found: " + t.toString());
+      }
+
+      if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))
+        throw new ConfigException("localizer class '" + localizerClassName + "' is not assignable from MirLocalizer");
+
+      try {
+        localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());
+      }
+      catch (Throwable t) {
+        throw new ConfigException("localizer class '" + localizerClassName + "' cannot be instantiated: " + t.toString());
+      }
+    }
+
+    return localizer;
+  }
+
+  public static Abuse abuse() {
+    if (abuse==null) {
+      synchronized(MirGlobal.class) {
+        if (abuse==null)
+          abuse = new Abuse();
+      }
+    }
+
+    return abuse;
+  }
+
+  public static MirPropertiesConfiguration config() {
+    try {
+      return MirPropertiesConfiguration.instance();
+    }
+    catch (PropertiesConfigExc e) {
+      throw new RuntimeException(e.getMessage());
+    }
+  }
+
+  public static ProducerEngine producerEngine() {
+    if (producerEngine == null) {
+      producerEngine = new ProducerEngine();
+    }
+
+    return producerEngine;
+  }
+
+  public static MRUCache mruCache() {
+    synchronized(MirGlobal.class) {
+      if (mruCache == null) {
+        mruCache = new MRUCache();
+      }
+      return mruCache;
+    }
+  }
+
+  public static synchronized AccessControl accessControl() {
+    if (accessControl == null) {
+      accessControl=new AccessControl();
+    }
+
+    return accessControl;
+  }
+
+  public static void performArticleOperation(EntityUsers aUser, EntityContent  anArticle, String anOperation) {
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getArticleOperationForName(anOperation);
+
+    try {
+      EntityAdapter user = null;
+      if (aUser!=null)
+          user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
+
+      if (operation!=null)
+        operation.perform(
+            user,
+            localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
+    }
+    catch (Throwable t) {
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+
+      throw new RuntimeException(t.toString());
+    }
+  }
+
+  public static void performCommentOperation(EntityUsers aUser, EntityComment  aComment, String anOperation) {
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getCommentOperationForName(anOperation);
+
+    try {
+      EntityAdapter user = null;
+      if (aUser!=null)
+          user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
+
+      if (operation!=null)
+        operation.perform(
+            user,
+            localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
+    }
+    catch (Throwable t) {
+      throw new RuntimeException(t.toString());
+    }
+  }
+
+  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getArticleOperationForName(String aName) {
+    try {
+      if (articleOperations == null) {
+        articleOperations = new HashMap();
+        Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();
+        while (i.hasNext()) {
+          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+          articleOperations.put(operation.getName(), operation);
+        }
+      }
+
+      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) articleOperations.get(aName);
+    }
+    catch (Throwable t) {
+      throw new RuntimeException(t.toString());
+    }
+  }
+
+  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getCommentOperationForName(String aName) {
+    try {
+      if (commentOperations == null) {
+        commentOperations = new HashMap();
+        Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();
+        while (i.hasNext()) {
+          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+          commentOperations.put(operation.getName(), operation);
+        }
+      }
+
+      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) commentOperations.get(aName);
+    }
+    catch (Throwable t) {
+      throw new RuntimeException(t.toString());
+    }
+  }
+
+
+  public static List getLoggedInUsers() {
+    List result = new Vector();
+
+    synchronized (loggedInUsers) {
+      Iterator i = loggedInUsers.entrySet().iterator();
+
+      while (i.hasNext()) {
+        Map.Entry entry = (Map.Entry) i.next();
+
+        Map item = new HashMap();
+        item.put("name", entry.getKey());
+        item.put("count", entry.getValue());
+        result.add(item);
+      }
+    }
+
+    return result;
+  }
+
+  public static void registerLogin(String aName) {
+    modifyLoggedInCount(aName, 1);
+  }
+
+  public static void registerLogout(String aName) {
+    modifyLoggedInCount(aName, -1);
+  }
+
+  private static void modifyLoggedInCount(String aName, int aModifier) {
+    synchronized (loggedInUsers) {
+      Integer count = (Integer) loggedInUsers.get(aName);
+      if (count==null)
+        count = new Integer(0);
+
+      if (count.intValue()+aModifier<=0) {
+        loggedInUsers.remove(aName);
+      }
+      else {
+        loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));
+      }
+    }
+  }
+
+  public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {
+    try {
+      if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {
+        String user = "unknown (" + aUser.toString() + ")";
+        if (aUser != null)
+          user = aUser.getValue("login");
+        adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);
+      }
+    }
+    catch (Throwable t) {
+      logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());
+    }
+  }
+}
+
+
index e4f7ddd..220797e 100755 (executable)
@@ -30,9 +30,9 @@
 
 package mircoders.localizer;
 
+import mir.entity.adapter.EntityAdapterModel;
 import mir.generator.Generator;
 import mir.generator.WriterEngine;
-import mir.entity.adapter.*;
 
 public class MirCachingLocalizerDecorator implements MirLocalizer {
   private MirLocalizer localizer;
index bec059e..c8830b3 100755 (executable)
@@ -1,90 +1,89 @@
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.localizer;\r
-\r
-import java.util.List;\r
-\r
-import mir.session.Request;\r
-import mir.session.Session;\r
-import mir.session.SessionHandler;\r
-\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-\r
-public interface MirOpenPostingLocalizer {\r
-\r
-  /**\r
-   * Class to encapsulate a validation error\r
-   *\r
-   * <p>Title: </p>\r
-   * <p>Description: </p>\r
-   * <p>Copyright: Copyright (c) 2003</p>\r
-   * <p>Company: </p>\r
-   * @author not attributable\r
-   * @version 1.0\r
-   */\r
-\r
-  /**\r
-   *\r
-   * @param aRequest\r
-   * @param aSession\r
-   * @return\r
-   * @throws MirLocalizerExc\r
-   * @throws MirLocalizerFailure\r
-   */\r
-  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
-  /**\r
-   *\r
-   * @param aComment\r
-   * @throws MirLocalizerExc\r
-   * @throws MirLocalizerFailure\r
-   */\r
-  public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
-  /**\r
-   * This method will be called after an article is posted via the open posting interface.\r
-   *\r
-   * @param aContent\r
-   * @throws MirLocalizerExc\r
-   * @throws MirLocalizerFailure\r
-   */\r
-  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
-  /**\r
-   *\r
-   *\r
-   * @return\r
-   * @throws MirLocalizerExc\r
-   * @throws MirLocalizerFailure\r
-   */\r
-\r
-  public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;\r
-}\r
+/*
+ * 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 mircoders.localizer;
+
+import java.util.List;
+
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionHandler;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+
+public interface MirOpenPostingLocalizer {
+
+  /**
+   * Class to encapsulate a validation error
+   *
+   * <p>Title: </p>
+   * <p>Description: </p>
+   * <p>Copyright: Copyright (c) 2003</p>
+   * <p>Company: </p>
+   * @author not attributable
+   * @version 1.0
+   */
+
+  /**
+   *
+   * @param aRequest
+   * @param aSession
+   * @return
+   * @throws MirLocalizerExc
+   * @throws MirLocalizerFailure
+   */
+  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;
+
+  /**
+   *
+   * @param aComment
+   * @throws MirLocalizerExc
+   * @throws MirLocalizerFailure
+   */
+  public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;
+
+  /**
+   * This method will be called after an article is posted via the open posting interface.
+   *
+   * @param aContent
+   * @throws MirLocalizerExc
+   * @throws MirLocalizerFailure
+   */
+  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;
+
+  /**
+   *
+   *
+   * @return
+   * @throws MirLocalizerExc
+   * @throws MirLocalizerFailure
+   */
+
+  public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;
+}
index 47516de..58f56a6 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.Arrays;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Set;\r
-import java.util.Vector;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.*;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.misc.StringUtil;\r
-import mir.storage.StorageObjectFailure;\r
-import mir.util.DateTimeFunctions;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer.MirSimpleEntityOperation;\r
-import mircoders.localizer.MirLocalizerExc;\r
-import mircoders.localizer.MirLocalizerFailure;\r
-import mircoders.storage.DatabaseContent;\r
-\r
-\r
-public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer {\r
-  private Vector simpleCommentOperations;\r
-  private Vector simpleArticleOperations;\r
-  private Map simpleCommentOperationsMap;\r
-  private Map simpleArticleOperationsMap;\r
-  protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");;\r
-\r
-  public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure, MirLocalizerExc {\r
-\r
-    simpleCommentOperations = new Vector();\r
-    simpleArticleOperations = new Vector();\r
-    simpleCommentOperationsMap = new HashMap();\r
-    simpleArticleOperationsMap = new HashMap();\r
-\r
-    addSimpleArticleOperation(new ChangeArticleFieldOperation("newswire", "to_article_type", "0", "1", false));\r
-    addSimpleArticleOperation(new ModifyArticleFieldOperation("unhide", "is_published", "1", false));\r
-    addSimpleArticleOperation(new ModifyArticleFieldOperation("hide", "is_published", "0", false));\r
-\r
-    addSimpleCommentOperation(new ModifyCommentFieldOperation("unhide", "is_published", "1"));\r
-    addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0"));\r
-  }\r
-\r
-  public String makePasswordDigest(String aPassword) {\r
-    return aPassword;\r
-  }\r
-\r
-  public void initializeArticle(Map anArticle) {\r
-    anArticle.put("is_published", "0");\r
-    anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
-  };\r
-\r
-  public List simpleCommentOperations() {\r
-    return simpleCommentOperations;\r
-  };\r
-\r
-  public List simpleArticleOperations() {\r
-    return simpleArticleOperations;\r
-  };\r
-\r
-  public MirSimpleEntityOperation simpleArticleOperationForName(String aName) {\r
-    return (MirSimpleEntityOperation) simpleArticleOperationsMap.get(aName);\r
-  };\r
-\r
-  public MirSimpleEntityOperation simpleCommentOperationForName(String aName) {\r
-    return (MirSimpleEntityOperation) simpleCommentOperationsMap.get(aName);\r
-  };\r
-\r
-  public void removeSimpleArticleOperation(String aName) {\r
-    simpleArticleOperations.remove(simpleArticleOperationsMap.get(aName));\r
-    simpleArticleOperationsMap.remove(aName);\r
-  }\r
-\r
-  public void addSimpleArticleOperation(MirSimpleEntityOperation anOperation) {\r
-    removeSimpleArticleOperation(anOperation.getName());\r
-    simpleArticleOperationsMap.put(anOperation.getName(), anOperation);\r
-    simpleArticleOperations.add(anOperation);\r
-  }\r
-\r
-  public void removeSimpleCommentOperation(String aName) {\r
-    simpleCommentOperations.remove(simpleCommentOperationsMap.get(aName));\r
-    simpleCommentOperationsMap.remove(aName);\r
-  }\r
-\r
-  public void addSimpleCommentOperation(MirSimpleEntityOperation anOperation) {\r
-    removeSimpleCommentOperation(anOperation.getName());\r
-    simpleCommentOperationsMap.put(anOperation.getName(), anOperation);\r
-    simpleCommentOperations.add(anOperation);\r
-  }\r
-\r
-  protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation {\r
-    private String name;\r
-\r
-    protected EntityModifyingOperation(String aName) {\r
-      name = aName;\r
-    }\r
-\r
-    public String getName() {\r
-      return name;\r
-    };\r
-\r
-    public boolean isAvailable(EntityAdapter anEntity) {\r
-      try {\r
-        Entity entity = anEntity.getEntity();\r
-        return isAvailable(entity);\r
-      }\r
-      catch (Throwable t) {\r
-        return false;\r
-      }\r
-    };\r
-\r
-    public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {\r
-      Entity entity = anEntity.getEntity();\r
-      try {\r
-        performModification(aUser, entity);\r
-        entity.update();\r
-      }\r
-      catch (Throwable t) {\r
-        throw new MirLocalizerFailure(t);\r
-      }\r
-    };\r
-\r
-    protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ;\r
-    protected abstract void performModification(EntityAdapter aUser, Entity anEntity)  throws MirLocalizerExc, MirLocalizerFailure ;\r
-  }\r
-\r
-  public static abstract class CommentModifyingOperation extends EntityModifyingOperation {\r
-    public CommentModifyingOperation(String aName) {\r
-      super(aName);\r
-    }\r
-\r
-    protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {\r
-      return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity);\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {\r
-      performModification(aUser, (EntityComment) anEntity);\r
-      DatabaseContent.getInstance().setUnproduced("id="+anEntity.getValue("to_media"));\r
-    };\r
-\r
-    protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ;\r
-    protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ;\r
-  }\r
-\r
-  public static abstract class ArticleModifyingOperation extends EntityModifyingOperation {\r
-    private boolean logOperation;\r
-\r
-    public ArticleModifyingOperation(String aName, boolean aLogOperation) {\r
-      super(aName);\r
-\r
-      logOperation = aLogOperation;\r
-    }\r
-\r
-    protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {\r
-      return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity);\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {\r
-      performModification(aUser, (EntityContent) anEntity);\r
-      anEntity.setValueForProperty("is_produced", "0");\r
-\r
-      if (logOperation) {\r
-        try {\r
-          StringBuffer line = new StringBuffer();\r
-\r
-          line.append(DateTimeFunctions.advancedDateFormat(\r
-              MirGlobal.config().getString("Mir.DefaultDateTimeFormat"),\r
-              (new GregorianCalendar()).getTime(),\r
-              MirGlobal.config().getString("Mir.DefaultTimezone")));\r
-          line.append(" ");\r
-          if (aUser != null)\r
-            line.append(aUser.get("login"));\r
-          else\r
-            line.append("unknown");\r
-\r
-          line.append(" ");\r
-          line.append(getName());\r
-          ( (EntityContent) anEntity).appendToComments(line.toString());\r
-        }\r
-        catch (Throwable t) {\r
-          logger.error("Error while trying to log an article operation: " + t.toString());\r
-        }\r
-      }\r
-    };\r
-\r
-    protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ;\r
-    protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ;\r
-  }\r
-\r
-  protected static class SetCommentFieldOperation extends CommentModifyingOperation {\r
-    private String field;\r
-    private String value;\r
-\r
-    public SetCommentFieldOperation(String aName, String aField, String aValue) {\r
-      super(aName);\r
-\r
-      field = aField;\r
-      value = aValue;\r
-    }\r
-\r
-    protected boolean isAvailable(EntityComment aComment) {\r
-      return true;\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {\r
-      aComment.setValueForProperty(field, value);\r
-    }\r
-  }\r
-\r
-  protected static class SetCommentFieldsOperation extends CommentModifyingOperation {\r
-    private Map values;\r
-\r
-    public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) throws MirLocalizerExc {\r
-      super(aName);\r
-\r
-      values = new HashMap();\r
-\r
-      for (int i=0; i<aFields.length; i++)\r
-        values.put(aFields[i], aValues[i]);\r
-    }\r
-\r
-    protected boolean isAvailable(EntityComment aComment) {\r
-      return true;\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {\r
-      Iterator i = values.entrySet().iterator();\r
-\r
-      while (i.hasNext()) {\r
-        Map.Entry entry = (Map.Entry) i.next();\r
-        aComment.setValueForProperty((String) entry.getKey(), (String) entry.getValue());\r
-      }\r
-    }\r
-  }\r
-\r
-\r
-  protected static class ModifyCommentFieldOperation extends CommentModifyingOperation {\r
-    private String field;\r
-    private String value;\r
-\r
-    public ModifyCommentFieldOperation(String aName, String aField, String aValue) {\r
-      super(aName);\r
-\r
-      field = aField;\r
-      value = aValue;\r
-    }\r
-\r
-    protected boolean isAvailable(EntityComment aComment) {\r
-      return aComment.getValue(field) == null || !aComment.getValue(field).equals(value);\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {\r
-      aComment.setValueForProperty(field, value);\r
-    }\r
-  }\r
-\r
-  protected static class SetArticleFieldOperation extends ArticleModifyingOperation {\r
-    private String field;\r
-    private String value;\r
-\r
-    public SetArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) {\r
-      super(aName, aLogOperation);\r
-\r
-      field = aField;\r
-      value = aValue;\r
-    }\r
-\r
-    protected boolean isAvailable(EntityContent anArticle) {\r
-      return true;\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {\r
-      anArticle.setValueForProperty(field, value);\r
-    }\r
-  }\r
-\r
-  protected static class ModifyArticleFieldOperation extends ArticleModifyingOperation {\r
-    private String field;\r
-    private String value;\r
-\r
-    public ModifyArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) {\r
-      super(aName, aLogOperation);\r
-\r
-      field = aField;\r
-      value = aValue;\r
-    }\r
-\r
-    protected boolean isAvailable(EntityContent anArticle) {\r
-      return anArticle.getValue(field) == null || !anArticle.getValue(field).equals(value);\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {\r
-      anArticle.setValueForProperty(field, value);\r
-    }\r
-  }\r
-\r
-  protected static class ChangeArticleFieldOperation extends ArticleModifyingOperation {\r
-    private String field;\r
-    private Set oldValues;\r
-    private String newValue;\r
-\r
-    public ChangeArticleFieldOperation(String aName, String aField, String anOldValues[], String aNewValue, boolean aLogOperation) {\r
-      super(aName, aLogOperation);\r
-\r
-      field = aField;\r
-      newValue = aNewValue;\r
-      oldValues = new HashSet(Arrays.asList(anOldValues));\r
-    }\r
-    public ChangeArticleFieldOperation(String aName, String aField, String anOldValue, String aNewValue, boolean aLogOperation) {\r
-      this(aName, aField, new String[] {anOldValue}, aNewValue, aLogOperation);\r
-    }\r
-\r
-    protected boolean isAvailable(EntityContent anArticle) {\r
-      return anArticle.getValue(field) != null && oldValues.contains(anArticle.getValue(field));\r
-    }\r
-\r
-    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {\r
-      anArticle.setValueForProperty(field, newValue);\r
-    }\r
-  }\r
-}\r
+/*
+ * 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 mircoders.localizer.basic;
+
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+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.util.Vector;
+
+import mir.entity.Entity;
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.storage.StorageObjectFailure;
+import mir.util.DateTimeFunctions;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.storage.DatabaseContent;
+
+
+public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer {
+  private Vector simpleCommentOperations;
+  private Vector simpleArticleOperations;
+  private Map simpleCommentOperationsMap;
+  private Map simpleArticleOperationsMap;
+  protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");;
+
+  public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure, MirLocalizerExc {
+
+    simpleCommentOperations = new Vector();
+    simpleArticleOperations = new Vector();
+    simpleCommentOperationsMap = new HashMap();
+    simpleArticleOperationsMap = new HashMap();
+
+    addSimpleArticleOperation(new ChangeArticleFieldOperation("newswire", "to_article_type", "0", "1", false));
+    addSimpleArticleOperation(new ModifyArticleFieldOperation("unhide", "is_published", "1", false));
+    addSimpleArticleOperation(new ModifyArticleFieldOperation("hide", "is_published", "0", false));
+
+    addSimpleCommentOperation(new ModifyCommentFieldOperation("unhide", "is_published", "1"));
+    addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0"));
+  }
+
+  public String makePasswordDigest(String aPassword) {
+    return aPassword;
+  }
+
+  public void initializeArticle(Map anArticle) {
+    anArticle.put("is_published", "0");
+    anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+  };
+
+  public List simpleCommentOperations() {
+    return simpleCommentOperations;
+  };
+
+  public List simpleArticleOperations() {
+    return simpleArticleOperations;
+  };
+
+  public MirSimpleEntityOperation simpleArticleOperationForName(String aName) {
+    return (MirSimpleEntityOperation) simpleArticleOperationsMap.get(aName);
+  };
+
+  public MirSimpleEntityOperation simpleCommentOperationForName(String aName) {
+    return (MirSimpleEntityOperation) simpleCommentOperationsMap.get(aName);
+  };
+
+  public void removeSimpleArticleOperation(String aName) {
+    simpleArticleOperations.remove(simpleArticleOperationsMap.get(aName));
+    simpleArticleOperationsMap.remove(aName);
+  }
+
+  public void addSimpleArticleOperation(MirSimpleEntityOperation anOperation) {
+    removeSimpleArticleOperation(anOperation.getName());
+    simpleArticleOperationsMap.put(anOperation.getName(), anOperation);
+    simpleArticleOperations.add(anOperation);
+  }
+
+  public void removeSimpleCommentOperation(String aName) {
+    simpleCommentOperations.remove(simpleCommentOperationsMap.get(aName));
+    simpleCommentOperationsMap.remove(aName);
+  }
+
+  public void addSimpleCommentOperation(MirSimpleEntityOperation anOperation) {
+    removeSimpleCommentOperation(anOperation.getName());
+    simpleCommentOperationsMap.put(anOperation.getName(), anOperation);
+    simpleCommentOperations.add(anOperation);
+  }
+
+  protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation {
+    private String name;
+
+    protected EntityModifyingOperation(String aName) {
+      name = aName;
+    }
+
+    public String getName() {
+      return name;
+    };
+
+    public boolean isAvailable(EntityAdapter anEntity) {
+      try {
+        Entity entity = anEntity.getEntity();
+        return isAvailable(entity);
+      }
+      catch (Throwable t) {
+        return false;
+      }
+    };
+
+    public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+      Entity entity = anEntity.getEntity();
+      try {
+        performModification(aUser, entity);
+        entity.update();
+      }
+      catch (Throwable t) {
+        throw new MirLocalizerFailure(t);
+      }
+    };
+
+    protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ;
+    protected abstract void performModification(EntityAdapter aUser, Entity anEntity)  throws MirLocalizerExc, MirLocalizerFailure ;
+  }
+
+  public static abstract class CommentModifyingOperation extends EntityModifyingOperation {
+    public CommentModifyingOperation(String aName) {
+      super(aName);
+    }
+
+    protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
+      return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity);
+    }
+
+    protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
+      performModification(aUser, (EntityComment) anEntity);
+      DatabaseContent.getInstance().setUnproduced("id="+anEntity.getValue("to_media"));
+    };
+
+    protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ;
+    protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ;
+  }
+
+  public static abstract class ArticleModifyingOperation extends EntityModifyingOperation {
+    private boolean logOperation;
+
+    public ArticleModifyingOperation(String aName, boolean aLogOperation) {
+      super(aName);
+
+      logOperation = aLogOperation;
+    }
+
+    protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
+      return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity);
+    }
+
+    protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
+      performModification(aUser, (EntityContent) anEntity);
+      anEntity.setValueForProperty("is_produced", "0");
+
+      if (logOperation) {
+        try {
+          StringBuffer line = new StringBuffer();
+
+          line.append(DateTimeFunctions.advancedDateFormat(
+              MirGlobal.config().getString("Mir.DefaultDateTimeFormat"),
+              (new GregorianCalendar()).getTime(),
+              MirGlobal.config().getString("Mir.DefaultTimezone")));
+          line.append(" ");
+          if (aUser != null)
+            line.append(aUser.get("login"));
+          else
+            line.append("unknown");
+
+          line.append(" ");
+          line.append(getName());
+          ( (EntityContent) anEntity).appendToComments(line.toString());
+        }
+        catch (Throwable t) {
+          logger.error("Error while trying to log an article operation: " + t.toString());
+        }
+      }
+    };
+
+    protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ;
+    protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ;
+  }
+
+  protected static class SetCommentFieldOperation extends CommentModifyingOperation {
+    private String field;
+    private String value;
+
+    public SetCommentFieldOperation(String aName, String aField, String aValue) {
+      super(aName);
+
+      field = aField;
+      value = aValue;
+    }
+
+    protected boolean isAvailable(EntityComment aComment) {
+      return true;
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+      aComment.setValueForProperty(field, value);
+    }
+  }
+
+  protected static class SetCommentFieldsOperation extends CommentModifyingOperation {
+    private Map values;
+
+    public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) throws MirLocalizerExc {
+      super(aName);
+
+      values = new HashMap();
+
+      for (int i=0; i<aFields.length; i++)
+        values.put(aFields[i], aValues[i]);
+    }
+
+    protected boolean isAvailable(EntityComment aComment) {
+      return true;
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+      Iterator i = values.entrySet().iterator();
+
+      while (i.hasNext()) {
+        Map.Entry entry = (Map.Entry) i.next();
+        aComment.setValueForProperty((String) entry.getKey(), (String) entry.getValue());
+      }
+    }
+  }
+
+
+  protected static class ModifyCommentFieldOperation extends CommentModifyingOperation {
+    private String field;
+    private String value;
+
+    public ModifyCommentFieldOperation(String aName, String aField, String aValue) {
+      super(aName);
+
+      field = aField;
+      value = aValue;
+    }
+
+    protected boolean isAvailable(EntityComment aComment) {
+      return aComment.getValue(field) == null || !aComment.getValue(field).equals(value);
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+      aComment.setValueForProperty(field, value);
+    }
+  }
+
+  protected static class SetArticleFieldOperation extends ArticleModifyingOperation {
+    private String field;
+    private String value;
+
+    public SetArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) {
+      super(aName, aLogOperation);
+
+      field = aField;
+      value = aValue;
+    }
+
+    protected boolean isAvailable(EntityContent anArticle) {
+      return true;
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+      anArticle.setValueForProperty(field, value);
+    }
+  }
+
+  protected static class ModifyArticleFieldOperation extends ArticleModifyingOperation {
+    private String field;
+    private String value;
+
+    public ModifyArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) {
+      super(aName, aLogOperation);
+
+      field = aField;
+      value = aValue;
+    }
+
+    protected boolean isAvailable(EntityContent anArticle) {
+      return anArticle.getValue(field) == null || !anArticle.getValue(field).equals(value);
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+      anArticle.setValueForProperty(field, value);
+    }
+  }
+
+  protected static class ChangeArticleFieldOperation extends ArticleModifyingOperation {
+    private String field;
+    private Set oldValues;
+    private String newValue;
+
+    public ChangeArticleFieldOperation(String aName, String aField, String anOldValues[], String aNewValue, boolean aLogOperation) {
+      super(aName, aLogOperation);
+
+      field = aField;
+      newValue = aNewValue;
+      oldValues = new HashSet(Arrays.asList(anOldValues));
+    }
+    public ChangeArticleFieldOperation(String aName, String aField, String anOldValue, String aNewValue, boolean aLogOperation) {
+      this(aName, aField, new String[] {anOldValue}, aNewValue, aLogOperation);
+    }
+
+    protected boolean isAvailable(EntityContent anArticle) {
+      return anArticle.getValue(field) != null && oldValues.contains(anArticle.getValue(field));
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+      anArticle.setValueForProperty(field, newValue);
+    }
+  }
+}
index e7ae73d..6b807b5 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.*;\r
-\r
-import gnu.regexp.*;\r
-\r
-import mir.entity.Entity;\r
-import mir.session.Request;\r
-import mir.util.InternetFunctions;\r
-import mircoders.localizer.MirAntiAbuseFilterType;\r
-\r
-\r
-/**\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public class MirBasicAntiAbuseFilterTypes {\r
-  private MirBasicAntiAbuseFilterTypes() {\r
-  }\r
-\r
-  public static abstract class BasicFilterType implements MirAntiAbuseFilterType {\r
-    private String name;\r
-\r
-    public BasicFilterType(String aName) {\r
-      name = aName;\r
-    }\r
-\r
-    public String getName() {\r
-      return name;\r
-    }\r
-  }\r
-\r
-  /**\r
-   * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.\r
-   *\r
-   * <p>Title: </p>\r
-   * <p>Description: </p>\r
-   * <p>Copyright: Copyright (c) 2003</p>\r
-   * <p>Company: </p>\r
-   * @author not attributable\r
-   * @version 1.0\r
-   */\r
-\r
-  public static class IPFilter extends BasicFilterType {\r
-    public IPFilter(String aName) {\r
-      super(aName);\r
-    }\r
-\r
-    public boolean validate(String anExpression) {\r
-      try {\r
-        InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);\r
-        return true;\r
-      }\r
-      catch (Throwable t) {\r
-        return false;\r
-      }\r
-    };\r
-\r
-    public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
-      try {\r
-        return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);\r
-      }\r
-      catch (Throwable t) {\r
-        return false;\r
-      }\r
-    };\r
-  }\r
-\r
-  /**\r
-   * A regular expression filter.\r
-   *\r
-   * <p>Title: </p>\r
-   * <p>Description: </p>\r
-   * <p>Copyright: Copyright (c) 2003</p>\r
-   * <p>Company: </p>\r
-   * @author not attributable\r
-   * @version 1.0\r
-   */\r
-\r
-  public static class RegularExpressionFilter extends BasicFilterType {\r
-    private boolean exactMatch;\r
-    private boolean caseSensitive;\r
-    private List selectedFields;\r
-\r
-    public RegularExpressionFilter(String aName) {\r
-      this(aName, false, false, null);\r
-    }\r
-\r
-    public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {\r
-      super(aName);\r
-\r
-      caseSensitive = aCaseSensitive;\r
-      exactMatch = anExactMatch;\r
-      if (aSelectedFields==null)\r
-        selectedFields = null;\r
-      else\r
-        selectedFields = Arrays.asList(aSelectedFields);\r
-    }\r
-\r
-    public boolean validate(String anExpression) {\r
-      try {\r
-        new RE(anExpression);\r
-        return true;\r
-      }\r
-      catch (Throwable t) {\r
-        return false;\r
-      }\r
-    };\r
-\r
-    public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
-      try {\r
-        Iterator j;\r
-        int flags = 0;\r
-\r
-        if (caseSensitive)\r
-          flags |= RE.REG_ICASE;\r
-\r
-        RE regularExpression = new RE(anExpression, RE.REG_ICASE);\r
-\r
-        if (selectedFields!=null)\r
-          j = selectedFields.iterator();\r
-        else\r
-          j = anEntity.getFields().iterator();\r
-\r
-        while (j.hasNext()) {\r
-          String field = anEntity.getValue( (String) j.next());\r
-\r
-          if (exactMatch) {\r
-            if (field != null && regularExpression.isMatch(field)) {\r
-              return true;\r
-            }\r
-          }\r
-          else {\r
-            if (field != null && regularExpression.getMatch(field) != null) {\r
-              return true;\r
-            }\r
-          }\r
-        }\r
-      }\r
-      catch (Throwable t) {\r
-      }\r
-      return false;\r
-    }\r
-  }\r
+/*
+ * 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 mircoders.localizer.basic;
+
+import gnu.regexp.RE;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+import mir.entity.Entity;
+import mir.session.Request;
+import mir.util.InternetFunctions;
+import mircoders.localizer.MirAntiAbuseFilterType;
+
+
+/**
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public class MirBasicAntiAbuseFilterTypes {
+  private MirBasicAntiAbuseFilterTypes() {
+  }
+
+  public static abstract class BasicFilterType implements MirAntiAbuseFilterType {
+    private String name;
+
+    public BasicFilterType(String aName) {
+      name = aName;
+    }
+
+    public String getName() {
+      return name;
+    }
+  }
+
+  /**
+   * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.
+   *
+   * <p>Title: </p>
+   * <p>Description: </p>
+   * <p>Copyright: Copyright (c) 2003</p>
+   * <p>Company: </p>
+   * @author not attributable
+   * @version 1.0
+   */
+
+  public static class IPFilter extends BasicFilterType {
+    public IPFilter(String aName) {
+      super(aName);
+    }
+
+    public boolean validate(String anExpression) {
+      try {
+        InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);
+        return true;
+      }
+      catch (Throwable t) {
+        return false;
+      }
+    };
+
+    public boolean test(String anExpression, Entity anEntity, Request aRequest) {
+      try {
+        return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);
+      }
+      catch (Throwable t) {
+        return false;
+      }
+    };
+  }
+
+  /**
+   * A regular expression filter.
+   *
+   * <p>Title: </p>
+   * <p>Description: </p>
+   * <p>Copyright: Copyright (c) 2003</p>
+   * <p>Company: </p>
+   * @author not attributable
+   * @version 1.0
+   */
+
+  public static class RegularExpressionFilter extends BasicFilterType {
+    private boolean exactMatch;
+    private boolean caseSensitive;
+    private List selectedFields;
+
+    public RegularExpressionFilter(String aName) {
+      this(aName, false, false, null);
+    }
+
+    public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {
+      super(aName);
+
+      caseSensitive = aCaseSensitive;
+      exactMatch = anExactMatch;
+      if (aSelectedFields==null)
+        selectedFields = null;
+      else
+        selectedFields = Arrays.asList(aSelectedFields);
+    }
+
+    public boolean validate(String anExpression) {
+      try {
+        new RE(anExpression);
+        return true;
+      }
+      catch (Throwable t) {
+        return false;
+      }
+    };
+
+    public boolean test(String anExpression, Entity anEntity, Request aRequest) {
+      try {
+        Iterator j;
+        int flags = 0;
+
+        if (caseSensitive)
+          flags |= RE.REG_ICASE;
+
+        RE regularExpression = new RE(anExpression, RE.REG_ICASE);
+
+        if (selectedFields!=null)
+          j = selectedFields.iterator();
+        else
+          j = anEntity.getFields().iterator();
+
+        while (j.hasNext()) {
+          String field = anEntity.getValue( (String) j.next());
+
+          if (exactMatch) {
+            if (field != null && regularExpression.isMatch(field)) {
+              return true;
+            }
+          }
+          else {
+            if (field != null && regularExpression.getMatch(field) != null) {
+              return true;
+            }
+          }
+        }
+      }
+      catch (Throwable t) {
+      }
+      return false;
+    }
+  }
 }
\ No newline at end of file
index fbfcf31..0e0c391 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import mir.entity.Entity;\r
-import mir.misc.StringUtil;\r
-import mir.session.Request;\r
-import mir.session.Response;\r
-import mir.session.Session;\r
-import mir.session.SessionExc;\r
-import mir.session.SessionFailure;\r
-import mir.session.UploadedFile;\r
-import mir.session.ValidationHelper;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.media.MediaUploadProcessor;\r
-import mircoders.module.ModuleArticleType;\r
-import mircoders.module.*;\r
-import mircoders.storage.DatabaseArticleType;\r
-import mircoders.storage.*;\r
-import mircoders.storage.DatabaseContentToMedia;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-\r
-/**\r
- *\r
- * <p>Title: Experimental session handler for article postings </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author Zapata\r
- * @version 1.0\r
- */\r
-\r
-public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {\r
-  protected ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());\r
-  protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();\r
-  protected DatabaseContent contentDatabase = DatabaseContent.getInstance();\r
-\r
-  public MirBasicArticlePostingHandler() {\r
-    super();\r
-\r
-    setResponseGenerators(\r
-      configuration.getString("Localizer.OpenSession.article.EditTemplate"),\r
-      configuration.getString("Localizer.OpenSession.article.DupeTemplate"),\r
-      configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),\r
-      configuration.getString("Localizer.OpenSession.article.DoneTemplate"));\r
-  }\r
-\r
-  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    super.initializeResponseData(aRequest, aSession, aResponse);\r
-\r
-    Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
-    while (i.hasNext()) {\r
-      String field = (String) i.next();\r
-      aResponse.setResponseValue(field, aRequest.getParameter(field));\r
-    }\r
-    aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));\r
-  }\r
-\r
-  public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-    super.validate(aResults, aRequest, aSession);\r
-\r
-    ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);\r
-    ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);\r
-    ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);\r
-    ValidationHelper.testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);\r
-  }\r
-\r
-  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {\r
-    try {\r
-      anArticle.setValueForProperty("is_published", "1");\r
-      anArticle.setValueForProperty("is_produced", "0");\r
-      anArticle.setValueForProperty("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
-      anArticle.setValueForProperty("is_html", "0");\r
-      anArticle.setValueForProperty("publish_path", StringUtil.webdbDate2path(anArticle. getValue("date")));\r
-\r
-      ModuleArticleType module = new ModuleArticleType(DatabaseArticleType.getInstance());\r
-      anArticle.setValueForProperty("to_article_type", module.articleTypeIdForName(configuration.getString("Localizer.OpenSession.article.DefaultArticleType")));\r
-      anArticle.setValueForProperty("to_publisher", "1");\r
-    }\r
-    catch (Throwable t) {\r
-      throw new SessionFailure(t);\r
-    }\r
-  }\r
-\r
-  public void setArticleTopics(Request aRequest, Session aSession, EntityContent aContent) throws SessionExc, SessionFailure {\r
-    // topics:\r
-    List topics = aRequest.getParameters("to_topic");\r
-    if (topics.size() > 0) {\r
-      try {\r
-        DatabaseContentToTopics.getInstance().setTopics(aContent.getId(), topics);\r
-      }\r
-      catch (Throwable e) {\r
-        logger.error("setting content_x_topic failed");\r
-        throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);\r
-      }\r
-    }\r
-  }\r
-\r
-  public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-    try {\r
-      String id;\r
-      Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
-\r
-      EntityContent article = (EntityContent) contentModule.createNew();\r
-      article.setValues(values);\r
-\r
-      finalizeArticle(aRequest, aSession, article);\r
-      id = article.insert();\r
-      if (id == null) {\r
-        logger.info("Duplicate article rejected");\r
-        throw new DuplicatePostingExc("Duplicate article rejected");\r
-      }\r
-      aSession.setAttribute("content", article);\r
-\r
-\r
-      setArticleTopics(aRequest, aSession, article);\r
-\r
-    }\r
-    catch (Throwable t) {\r
-      throw new SessionFailure(t);\r
-    }\r
-  }\r
-\r
-  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {\r
-    try {\r
-      Map values = new HashMap();\r
-      values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));\r
-      values.put("creator", aRequest.getParameter("creator"));\r
-      values.put("to_publisher", "0");\r
-      values.put("is_published", "1");\r
-      values.put("is_produced", "1");\r
-      ModuleMediafolder module = new ModuleMediafolder(DatabaseMediafolder.getInstance());\r
-      values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.article.DefaultMediaFolder")));\r
-\r
-      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);\r
-      mediaItem.update();\r
-      contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());\r
-    }\r
-    catch (Throwable t) {\r
-      throw new SessionFailure(t);\r
-    }\r
-  }\r
-\r
-  public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-    EntityContent article = (EntityContent) aSession.getAttribute("content");\r
-\r
-    MirGlobal.abuse().checkArticle(article, aRequest, null);\r
-    try {\r
-      MirGlobal.localizer().openPostings().afterContentPosting(article);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new SessionFailure(t);\r
-    }\r
-    logger.info("article posted");\r
-  };\r
-\r
-}\r
+/*
+ * 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 mircoders.localizer.basic;
+
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import mir.entity.Entity;
+import mir.misc.StringUtil;
+import mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mir.session.UploadedFile;
+import mir.session.ValidationHelper;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.media.MediaUploadProcessor;
+import mircoders.module.ModuleArticleType;
+import mircoders.module.ModuleContent;
+import mircoders.module.ModuleMediafolder;
+import mircoders.storage.DatabaseArticleType;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseContentToMedia;
+import mircoders.storage.DatabaseContentToTopics;
+import mircoders.storage.DatabaseMediafolder;
+
+/**
+ *
+ * <p>Title: Experimental session handler for article postings </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author Zapata
+ * @version 1.0
+ */
+
+public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {
+  protected ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());
+  protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();
+  protected DatabaseContent contentDatabase = DatabaseContent.getInstance();
+
+  public MirBasicArticlePostingHandler() {
+    super();
+
+    setResponseGenerators(
+      configuration.getString("Localizer.OpenSession.article.EditTemplate"),
+      configuration.getString("Localizer.OpenSession.article.DupeTemplate"),
+      configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),
+      configuration.getString("Localizer.OpenSession.article.DoneTemplate"));
+  }
+
+  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    super.initializeResponseData(aRequest, aSession, aResponse);
+
+    Iterator i = DatabaseContent.getInstance().getFields().iterator();
+    while (i.hasNext()) {
+      String field = (String) i.next();
+      aResponse.setResponseValue(field, aRequest.getParameter(field));
+    }
+    aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));
+  }
+
+  public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+    super.validate(aResults, aRequest, aSession);
+
+    ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);
+  }
+
+  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
+    try {
+      anArticle.setValueForProperty("is_published", "1");
+      anArticle.setValueForProperty("is_produced", "0");
+      anArticle.setValueForProperty("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+      anArticle.setValueForProperty("is_html", "0");
+      anArticle.setValueForProperty("publish_path", StringUtil.webdbDate2path(anArticle. getValue("date")));
+
+      ModuleArticleType module = new ModuleArticleType(DatabaseArticleType.getInstance());
+      anArticle.setValueForProperty("to_article_type", module.articleTypeIdForName(configuration.getString("Localizer.OpenSession.article.DefaultArticleType")));
+      anArticle.setValueForProperty("to_publisher", "1");
+    }
+    catch (Throwable t) {
+      throw new SessionFailure(t);
+    }
+  }
+
+  public void setArticleTopics(Request aRequest, Session aSession, EntityContent aContent) throws SessionExc, SessionFailure {
+    // topics:
+    List topics = aRequest.getParameters("to_topic");
+    if (topics.size() > 0) {
+      try {
+        DatabaseContentToTopics.getInstance().setTopics(aContent.getId(), topics);
+      }
+      catch (Throwable e) {
+        logger.error("setting content_x_topic failed");
+        throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);
+      }
+    }
+  }
+
+  public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+    try {
+      String id;
+      Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());
+
+      EntityContent article = (EntityContent) contentModule.createNew();
+      article.setValues(values);
+
+      finalizeArticle(aRequest, aSession, article);
+      id = article.insert();
+      if (id == null) {
+        logger.info("Duplicate article rejected");
+        throw new DuplicatePostingExc("Duplicate article rejected");
+      }
+      aSession.setAttribute("content", article);
+
+
+      setArticleTopics(aRequest, aSession, article);
+
+    }
+    catch (Throwable t) {
+      throw new SessionFailure(t);
+    }
+  }
+
+  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
+    try {
+      Map values = new HashMap();
+      values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));
+      values.put("creator", aRequest.getParameter("creator"));
+      values.put("to_publisher", "0");
+      values.put("is_published", "1");
+      values.put("is_produced", "1");
+      ModuleMediafolder module = new ModuleMediafolder(DatabaseMediafolder.getInstance());
+      values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.article.DefaultMediaFolder")));
+
+      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);
+      mediaItem.update();
+      contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());
+    }
+    catch (Throwable t) {
+      throw new SessionFailure(t);
+    }
+  }
+
+  public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+    EntityContent article = (EntityContent) aSession.getAttribute("content");
+
+    MirGlobal.abuse().checkArticle(article, aRequest, null);
+    try {
+      MirGlobal.localizer().openPostings().afterContentPosting(article);
+    }
+    catch (Throwable t) {
+      throw new SessionFailure(t);
+    }
+    logger.info("article posted");
+  };
+
+}
index fc1c540..73bea17 100755 (executable)
@@ -38,32 +38,29 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Vector;
 
-
-import org.apache.commons.net.smtp.SMTPClient;
-import org.apache.commons.net.smtp.SMTPReply;
-import org.apache.struts.util.MessageResources;
-
 import mir.config.MirPropertiesConfiguration;
 import mir.generator.Generator;
 import mir.generator.GeneratorHelper;
 import mir.log.LoggerWrapper;
-import mir.session.HTTPAdapters.HTTPRequestAdapter;
 import mir.session.Request;
 import mir.session.Response;
 import mir.session.Session;
 import mir.session.SessionExc;
 import mir.session.SessionFailure;
 import mir.session.SessionHandler;
-import mir.session.ValidationError;
 import mir.session.ValidationHelper;
+import mir.session.HTTPAdapters.HTTPRequestAdapter;
 import mir.util.StringRoutines;
-
 import mircoders.entity.EntityContent;
 import mircoders.global.CacheKey;
 import mircoders.global.MirGlobal;
 import mircoders.module.ModuleContent;
 import mircoders.storage.DatabaseContent;
 
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+import org.apache.struts.util.MessageResources;
+
 
 /**
  *
index f6fe4a2..088d96f 100755 (executable)
  */
 package mircoders.localizer.basic;
 
-import java.util.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.Random;
+import java.util.Vector;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.log.LoggerWrapper;
@@ -41,7 +44,8 @@ import mircoders.entity.EntityComment;
 import mircoders.entity.EntityContent;
 import mircoders.global.MirGlobal;
 import mircoders.global.ProducerEngine;
-import mircoders.localizer.*;
+import mircoders.localizer.MirAntiAbuseFilterType;
+import mircoders.localizer.MirLocalizerExc;
 import mircoders.localizer.MirLocalizerFailure;
 import mircoders.localizer.MirOpenPostingLocalizer;
 
index 86c24f2..786fd62 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.localizer.basic;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Random;\r
-import java.util.Vector;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.log.LoggerWrapper;\r
-import mir.session.Request;\r
-import mir.session.Response;\r
-import mir.session.Session;\r
-import mir.session.SessionExc;\r
-import mir.session.SessionFailure;\r
-import mir.session.SessionHandler;\r
-import mir.session.UploadedFile;\r
-import mir.session.ValidationError;\r
-import mir.session.ValidationHelper;\r
-import mir.storage.StorageObject;\r
-import mir.util.ExceptionFunctions;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleMediaType;\r
-\r
-/**\r
- *\r
- * <p>Title: Experimental session handler for comment postings </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public abstract class MirBasicPostingSessionHandler implements SessionHandler {\r
-  protected LoggerWrapper logger;\r
-  protected MirPropertiesConfiguration configuration;\r
-\r
-  private String normalResponseGenerator;\r
-  private String dupeResponseGenerator;\r
-  private String unsupportedMediaTypeResponseGenerator;\r
-  private String finalResponseGenerator;\r
-\r
-\r
-  public MirBasicPostingSessionHandler() {\r
-    logger = new LoggerWrapper("Localizer.OpenPosting");\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (Throwable t) {\r
-      logger.fatal("Cannot load configuration: " + t.toString());\r
-\r
-      throw new RuntimeException("Cannot load configuration: " + t.toString());\r
-    }\r
-  }\r
-\r
-  protected void setNormalResponseGenerator(String aGenerator) {\r
-    normalResponseGenerator = aGenerator;\r
-  }\r
-\r
-  protected void setResponseGenerators(String aNormalResponseGenerator, String aDupeResponseGenerator,\r
-        String anUnsupportedMediaTypeResponseGenerator, String aFinalResponseGenerator) {\r
-    setNormalResponseGenerator(aNormalResponseGenerator);\r
-    dupeResponseGenerator = aDupeResponseGenerator;\r
-    unsupportedMediaTypeResponseGenerator = anUnsupportedMediaTypeResponseGenerator;\r
-    finalResponseGenerator = aFinalResponseGenerator;\r
-  }\r
-\r
-  public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
-      makeOpenPostingDisabledResponse(aRequest, aSession, aResponse);\r
-      aSession.terminate();\r
-    }\r
-    else {\r
-      if (aSession.getAttribute("initialRequest") == null) {\r
-        initialRequest(aRequest, aSession, aResponse);\r
-        aSession.setAttribute("initialRequest", "no");\r
-      }\r
-      else {\r
-        subsequentRequest(aRequest, aSession, aResponse);\r
-      }\r
-    }\r
-  };\r
-\r
-  protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    initializeSession(aRequest, aSession);\r
-    initializeResponseData(aRequest, aSession, aResponse);\r
-    makeInitialResponse(aRequest, aSession, aResponse);\r
-  }\r
-\r
-  public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    try {\r
-      try {\r
-        List validationErrors = new Vector();\r
-\r
-        if (!shouldProcessRequest(aRequest, aSession, validationErrors)) {\r
-          initializeResponseData(aRequest, aSession, aResponse);\r
-          makeResponse(aRequest, aSession, aResponse, validationErrors);\r
-        }\r
-        else {\r
-          preProcessRequest(aRequest, aSession);\r
-          Iterator i = aRequest.getUploadedFiles().iterator();\r
-          while (i.hasNext()) {\r
-            processUploadedFile(aRequest, aSession, (UploadedFile) i.next());\r
-          }\r
-          postProcessRequest(aRequest, aSession);\r
-          initializeResponseData(aRequest, aSession, aResponse);\r
-          makeFinalResponse(aRequest, aSession, aResponse);\r
-          aSession.terminate();\r
-        }\r
-      }\r
-      catch (Throwable t) {\r
-        initializeResponseData(aRequest, aSession, aResponse);\r
-        makeErrorResponse(aRequest, aSession, aResponse, t);\r
-        aSession.terminate();\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      aSession.terminate();\r
-\r
-      throw new SessionFailure(t);\r
-    }\r
-  }\r
-\r
-  protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-    if (MirGlobal.abuse().getOpenPostingPassword()) {\r
-      String password = (String) aSession.getAttribute("password");\r
-      if (password==null) {\r
-        password = generateOnetimePassword();\r
-        aSession.setAttribute("password", password);\r
-      }\r
-    }\r
-    else {\r
-      aSession.deleteAttribute("password");\r
-    }\r
-\r
-    logger.debug("referrer = " + aRequest.getHeader("Referer"));\r
-\r
-    aSession.setAttribute("referer", aRequest.getHeader("Referer"));\r
-  }\r
-\r
-  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    int nrMediaItems = configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems", 5);\r
-\r
-    if (aSession.getAttribute("nrmediaitems")!=null) {\r
-      nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();\r
-    }\r
-    try {\r
-      nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));\r
-    }\r
-    catch (Throwable t) {\r
-    }\r
-    aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));\r
-\r
-    List mediaItems = new Vector();\r
-    int i=0;\r
-\r
-    while (i<nrMediaItems) {\r
-      i++;\r
-      mediaItems.add(new Integer(i));\r
-    }\r
-\r
-    aResponse.setResponseValue("nrmediaitems", new Integer(nrMediaItems));\r
-    aResponse.setResponseValue("mediaitems", mediaItems);\r
-    aResponse.setResponseValue("password", aSession.getAttribute("password"));\r
-    aResponse.setResponseValue("referer", aSession.getAttribute("referer"));\r
-    aResponse.setResponseValue("errors", null);\r
-  }\r
-\r
-  protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    aResponse.setResponseGenerator(normalResponseGenerator);\r
-  };\r
-\r
-  protected void makeResponse(Request aRequest, Session aSession, Response aResponse, List anErrors) throws SessionExc, SessionFailure {\r
-    aResponse.setResponseValue("errors", anErrors);\r
-    aResponse.setResponseGenerator(normalResponseGenerator);\r
-  };\r
-\r
-  protected void makeFinalResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
-    aResponse.setResponseGenerator(finalResponseGenerator);\r
-  };\r
-\r
-  protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {\r
-    anError.printStackTrace();\r
-    Throwable rootCause = ExceptionFunctions.traceCauseException(anError);\r
-\r
-    if (rootCause instanceof DuplicatePostingExc)\r
-      aResponse.setResponseGenerator(dupeResponseGenerator);\r
-    if (rootCause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {\r
-      aResponse.setResponseValue("mimetype", ((ModuleMediaType.UnsupportedMimeTypeExc) rootCause).getMimeType());\r
-      aResponse.setResponseGenerator(unsupportedMediaTypeResponseGenerator);\r
-    }\r
-    else {\r
-      aResponse.setResponseValue("errorstring", anError.getMessage());\r
-      aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.ErrorTemplate"));\r
-    }\r
-  };\r
-\r
-  protected void makeOpenPostingDisabledResponse(Request aRequest, Session aSession, Response aResponse) {\r
-    aResponse.setResponseGenerator(configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));\r
-  }\r
-\r
-  protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-  };\r
-  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {\r
-  };\r
-  protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-  };\r
-\r
-  protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {\r
-    if (aRequest.getParameter("post")==null)\r
-      return false;\r
-    else {\r
-      validate(aValidationErrors, aRequest, aSession);\r
-      return (aValidationErrors == null || aValidationErrors.size() == 0);\r
-    }\r
-  }\r
-\r
-  protected void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
-    String password = (String) aSession.getAttribute("password");\r
-\r
-    if (password!=null) {\r
-      String submittedPassword= aRequest.getParameter("password").trim();\r
-\r
-      if (!password.equals(submittedPassword)) {\r
-        aResults.add(new ValidationError("password", "passwordmismatch"));\r
-      }\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   * Method to generate a one-time password\r
-   *\r
-   * @return a password, to be used once\r
-   */\r
-\r
-  protected String generateOnetimePassword() {\r
-    Random r = new Random();\r
-    int random = r.nextInt();\r
-\r
-    long l = System.currentTimeMillis();\r
-\r
-    l = (l*l*l*l)/random;\r
-    if (l<0)\r
-      l = l * -1;\r
-\r
-    String returnString = ""+l;\r
-\r
-    return returnString.substring(5);\r
-  }\r
-\r
-\r
-  /**\r
-   *\r
-   * @param aRequest\r
-   * @param aStorage\r
-   * @return\r
-   * @throws SessionExc\r
-   * @throws SessionFailure\r
-   */\r
-\r
-  protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {\r
-    Map result = new HashMap();\r
-\r
-    Iterator i = aStorage.getFields().iterator();\r
-\r
-    while (i.hasNext()) {\r
-      String fieldName = (String) i.next();\r
-      Object value = aRequest.getParameter(fieldName);\r
-      if (value != null)\r
-        result.put(fieldName, value);\r
-    }\r
-\r
-    return result;\r
-  }\r
-\r
-  protected static class DuplicatePostingExc extends SessionExc {\r
-    public DuplicatePostingExc(String aMessage) {\r
-      super(aMessage);\r
-    }\r
-  }\r
-\r
-}\r
+/*
+ * 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 mircoders.localizer.basic;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Vector;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mir.session.SessionHandler;
+import mir.session.UploadedFile;
+import mir.session.ValidationError;
+import mir.storage.StorageObject;
+import mir.util.ExceptionFunctions;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleMediaType;
+
+/**
+ *
+ * <p>Title: Experimental session handler for comment postings </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public abstract class MirBasicPostingSessionHandler implements SessionHandler {
+  protected LoggerWrapper logger;
+  protected MirPropertiesConfiguration configuration;
+
+  private String normalResponseGenerator;
+  private String dupeResponseGenerator;
+  private String unsupportedMediaTypeResponseGenerator;
+  private String finalResponseGenerator;
+
+
+  public MirBasicPostingSessionHandler() {
+    logger = new LoggerWrapper("Localizer.OpenPosting");
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (Throwable t) {
+      logger.fatal("Cannot load configuration: " + t.toString());
+
+      throw new RuntimeException("Cannot load configuration: " + t.toString());
+    }
+  }
+
+  protected void setNormalResponseGenerator(String aGenerator) {
+    normalResponseGenerator = aGenerator;
+  }
+
+  protected void setResponseGenerators(String aNormalResponseGenerator, String aDupeResponseGenerator,
+        String anUnsupportedMediaTypeResponseGenerator, String aFinalResponseGenerator) {
+    setNormalResponseGenerator(aNormalResponseGenerator);
+    dupeResponseGenerator = aDupeResponseGenerator;
+    unsupportedMediaTypeResponseGenerator = anUnsupportedMediaTypeResponseGenerator;
+    finalResponseGenerator = aFinalResponseGenerator;
+  }
+
+  public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    if (MirGlobal.abuse().getOpenPostingDisabled()) {
+      makeOpenPostingDisabledResponse(aRequest, aSession, aResponse);
+      aSession.terminate();
+    }
+    else {
+      if (aSession.getAttribute("initialRequest") == null) {
+        initialRequest(aRequest, aSession, aResponse);
+        aSession.setAttribute("initialRequest", "no");
+      }
+      else {
+        subsequentRequest(aRequest, aSession, aResponse);
+      }
+    }
+  };
+
+  protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    initializeSession(aRequest, aSession);
+    initializeResponseData(aRequest, aSession, aResponse);
+    makeInitialResponse(aRequest, aSession, aResponse);
+  }
+
+  public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    try {
+      try {
+        List validationErrors = new Vector();
+
+        if (!shouldProcessRequest(aRequest, aSession, validationErrors)) {
+          initializeResponseData(aRequest, aSession, aResponse);
+          makeResponse(aRequest, aSession, aResponse, validationErrors);
+        }
+        else {
+          preProcessRequest(aRequest, aSession);
+          Iterator i = aRequest.getUploadedFiles().iterator();
+          while (i.hasNext()) {
+            processUploadedFile(aRequest, aSession, (UploadedFile) i.next());
+          }
+          postProcessRequest(aRequest, aSession);
+          initializeResponseData(aRequest, aSession, aResponse);
+          makeFinalResponse(aRequest, aSession, aResponse);
+          aSession.terminate();
+        }
+      }
+      catch (Throwable t) {
+        initializeResponseData(aRequest, aSession, aResponse);
+        makeErrorResponse(aRequest, aSession, aResponse, t);
+        aSession.terminate();
+      }
+    }
+    catch (Throwable t) {
+      aSession.terminate();
+
+      throw new SessionFailure(t);
+    }
+  }
+
+  protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+    if (MirGlobal.abuse().getOpenPostingPassword()) {
+      String password = (String) aSession.getAttribute("password");
+      if (password==null) {
+        password = generateOnetimePassword();
+        aSession.setAttribute("password", password);
+      }
+    }
+    else {
+      aSession.deleteAttribute("password");
+    }
+
+    logger.debug("referrer = " + aRequest.getHeader("Referer"));
+
+    aSession.setAttribute("referer", aRequest.getHeader("Referer"));
+  }
+
+  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    int nrMediaItems = configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems", 5);
+
+    if (aSession.getAttribute("nrmediaitems")!=null) {
+      nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
+    }
+    try {
+      nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));
+    }
+    catch (Throwable t) {
+    }
+    aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));
+
+    List mediaItems = new Vector();
+    int i=0;
+
+    while (i<nrMediaItems) {
+      i++;
+      mediaItems.add(new Integer(i));
+    }
+
+    aResponse.setResponseValue("nrmediaitems", new Integer(nrMediaItems));
+    aResponse.setResponseValue("mediaitems", mediaItems);
+    aResponse.setResponseValue("password", aSession.getAttribute("password"));
+    aResponse.setResponseValue("referer", aSession.getAttribute("referer"));
+    aResponse.setResponseValue("errors", null);
+  }
+
+  protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    aResponse.setResponseGenerator(normalResponseGenerator);
+  };
+
+  protected void makeResponse(Request aRequest, Session aSession, Response aResponse, List anErrors) throws SessionExc, SessionFailure {
+    aResponse.setResponseValue("errors", anErrors);
+    aResponse.setResponseGenerator(normalResponseGenerator);
+  };
+
+  protected void makeFinalResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    aResponse.setResponseGenerator(finalResponseGenerator);
+  };
+
+  protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {
+    anError.printStackTrace();
+    Throwable rootCause = ExceptionFunctions.traceCauseException(anError);
+
+    if (rootCause instanceof DuplicatePostingExc)
+      aResponse.setResponseGenerator(dupeResponseGenerator);
+    if (rootCause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
+      aResponse.setResponseValue("mimetype", ((ModuleMediaType.UnsupportedMimeTypeExc) rootCause).getMimeType());
+      aResponse.setResponseGenerator(unsupportedMediaTypeResponseGenerator);
+    }
+    else {
+      aResponse.setResponseValue("errorstring", anError.getMessage());
+      aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.ErrorTemplate"));
+    }
+  };
+
+  protected void makeOpenPostingDisabledResponse(Request aRequest, Session aSession, Response aResponse) {
+    aResponse.setResponseGenerator(configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
+  }
+
+  protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+  };
+  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
+  };
+  protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+  };
+
+  protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {
+    if (aRequest.getParameter("post")==null)
+      return false;
+    else {
+      validate(aValidationErrors, aRequest, aSession);
+      return (aValidationErrors == null || aValidationErrors.size() == 0);
+    }
+  }
+
+  protected void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+    String password = (String) aSession.getAttribute("password");
+
+    if (password!=null) {
+      String submittedPassword= aRequest.getParameter("password").trim();
+
+      if (!password.equals(submittedPassword)) {
+        aResults.add(new ValidationError("password", "passwordmismatch"));
+      }
+    }
+  }
+
+
+  /**
+   * Method to generate a one-time password
+   *
+   * @return a password, to be used once
+   */
+
+  protected String generateOnetimePassword() {
+    Random r = new Random();
+    int random = r.nextInt();
+
+    long l = System.currentTimeMillis();
+
+    l = (l*l*l*l)/random;
+    if (l<0)
+      l = l * -1;
+
+    String returnString = ""+l;
+
+    return returnString.substring(5);
+  }
+
+
+  /**
+   *
+   * @param aRequest
+   * @param aStorage
+   * @return
+   * @throws SessionExc
+   * @throws SessionFailure
+   */
+
+  protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
+    Map result = new HashMap();
+
+    Iterator i = aStorage.getFields().iterator();
+
+    while (i.hasNext()) {
+      String fieldName = (String) i.next();
+      Object value = aRequest.getParameter(fieldName);
+      if (value != null)
+        result.put(fieldName, value);
+    }
+
+    return result;
+  }
+
+  protected static class DuplicatePostingExc extends SessionExc {
+    public DuplicatePostingExc(String aMessage) {
+      super(aMessage);
+    }
+  }
+
+}
index 7515714..819b5b3 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.localizer.basic;\r
-\r
-import java.io.File;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.generator.Generator;\r
-import mir.generator.WriterEngine;\r
-import mir.log.LoggerWrapper;\r
-import mir.producer.ProducerFactory;\r
-import mir.producer.reader.DefaultProducerNodeBuilders;\r
-import mir.producer.reader.ProducerConfigReader;\r
-import mir.producer.reader.ProducerNodeBuilderLibrary;\r
-import mir.util.*;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.global.ProducerEngine;\r
-import mircoders.localizer.MirLocalizerExc;\r
-import mircoders.localizer.MirLocalizerFailure;\r
-import mircoders.localizer.MirProducerLocalizer;\r
-import mircoders.producer.reader.SupplementalProducerNodeBuilders;\r
-\r
-public class MirBasicProducerLocalizer implements MirProducerLocalizer {\r
-  private List producerFactories;\r
-  private Map nameToFactory;\r
-\r
-  private Map producerRecipes;\r
-  private List producerRecipeNames;\r
-\r
-  protected FileMonitor fileMonitor;\r
-  protected EntityAdapterModel model;\r
-  protected Generator.GeneratorLibrary generatorLibrary;\r
-  protected WriterEngine writerEngine;\r
-\r
-  protected LoggerWrapper logger;\r
-\r
-  public MirBasicProducerLocalizer() {\r
-    try {\r
-      logger = new LoggerWrapper("Localizer.Basic.Producer");\r
-\r
-      producerRecipes = new HashMap();\r
-      producerRecipeNames = new Vector();\r
-\r
-      String[] recipes = MirGlobal.config().getStringArray("Mir.Localizer.Producer.ProducerRecipes");\r
-      for (int i = 0; i<recipes.length; i++) {\r
-        try {\r
-          List parts = StringRoutines.separateString(recipes[i], "=");\r
-          if (parts.size() == 2) {\r
-            producerRecipes.put(parts.get(0), ProducerEngine.ProducerTask.parseProducerTaskList( (String) parts.get(1)));\r
-            producerRecipeNames.add(parts.get(0));\r
-          }\r
-          else {\r
-            throw new Exception("'=' expected");\r
-          }\r
-        }\r
-        catch (Throwable t) {\r
-          logger.error("Error while processing producer recipe '" + recipes[i] + "': " + t.toString());\r
-        }\r
-      }\r
-\r
-      // for backward compatibility:\r
-      String allNewProducers = MirGlobal.config().getString("Mir.Localizer.Producer.AllNewProducers");\r
-      if (allNewProducers!=null && allNewProducers.length()>0) {\r
-        producerRecipes.put("allnew", ProducerEngine.ProducerTask.parseProducerTaskList(allNewProducers));\r
-        producerRecipeNames.add("allnew");\r
-      }\r
-\r
-      producerFactories = new Vector();\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-      generatorLibrary = MirGlobal.localizer().generators().makeProducerGeneratorLibrary();\r
-      writerEngine = MirGlobal.localizer().generators().makeWriterEngine();\r
-      nameToFactory = new HashMap();\r
-    }\r
-    catch (Throwable t) {\r
-      logger.error("MirBasicProducerLocalizer(): Exception "+t.getMessage());\r
-      model = new EntityAdapterModel();\r
-    }\r
-  }\r
-\r
-  public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure {\r
-    return producerRecipeNames;\r
-  }\r
-\r
-  public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure {\r
-    if (producerRecipes.containsKey(aName))\r
-      MirGlobal.producerEngine().addTasks((List) producerRecipes.get(aName));\r
-    else\r
-      throw new MirLocalizerExc("Unknown recipe name: " + aName);\r
-  }\r
-\r
-  public List factories() throws MirLocalizerExc {\r
-    if (fileMonitor==null || producerFactories == null || fileMonitor.hasChanged()) {\r
-      try {\r
-        List newProducers = new Vector();\r
-        FileMonitor newFileMonitor = new FileMonitor();\r
-        setupFactories(newProducers, newFileMonitor);\r
-\r
-        producerFactories = newProducers;\r
-        fileMonitor = newFileMonitor;\r
-        logger.info("MirBasicProducerLocalizer.factories(): successfully setup factories");\r
-\r
-        nameToFactory.clear();\r
-        Iterator i = producerFactories.iterator();\r
-        while (i.hasNext()) {\r
-          ProducerFactory factory = (ProducerFactory) i.next();\r
-          nameToFactory.put(factory.getName(), factory);\r
-        }\r
-      }\r
-      catch (Throwable t) {\r
-        logger.error("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage());\r
-        t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      }\r
-    }\r
-\r
-    return producerFactories;\r
-  };\r
-\r
-  protected void setupProducerNodeBuilderLibrary(ProducerNodeBuilderLibrary aLibrary) throws MirLocalizerFailure {\r
-    try {\r
-      DefaultProducerNodeBuilders.registerBuilders(\r
-          aLibrary, model, generatorLibrary, writerEngine,\r
-          MirGlobal.config().getString("Home"), MirGlobal.config().getString("Producer.StorageRoot"));\r
-      SupplementalProducerNodeBuilders.registerBuilders(aLibrary, model);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new MirLocalizerFailure(t.getMessage(), t);\r
-    }\r
-  }\r
-\r
-  protected void setupFactories(List aFactories, FileMonitor aFileMonitor) throws MirLocalizerExc, MirLocalizerFailure {\r
-    ProducerConfigReader reader;\r
-    ProducerNodeBuilderLibrary library = new ProducerNodeBuilderLibrary();\r
-    setupProducerNodeBuilderLibrary(library);\r
-    List usedFiles = new Vector();\r
-    Iterator i;\r
-\r
-    aFileMonitor.clear();\r
-    reader = new ProducerConfigReader();\r
-    reader.parseFile(MirGlobal.config().getString("Home") + File.separatorChar + MirGlobal.config().getString("Mir.Localizer.ProducerConfigFile"), library, aFactories, usedFiles);\r
-\r
-    i = usedFiles.iterator();\r
-    while (i.hasNext())\r
-      aFileMonitor.addFile((File) i.next());\r
-  }\r
-\r
-  public ProducerFactory getFactoryForName(String aName) {\r
-    try {\r
-      factories();\r
-    }\r
-    catch (Throwable t) {\r
-    }\r
-\r
-    return (ProducerFactory) nameToFactory.get(aName);\r
-  }\r
-}\r
+/*
+ * 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 mircoders.localizer.basic;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.adapter.EntityAdapterModel;
+import mir.generator.Generator;
+import mir.generator.WriterEngine;
+import mir.log.LoggerWrapper;
+import mir.producer.ProducerFactory;
+import mir.producer.reader.DefaultProducerNodeBuilders;
+import mir.producer.reader.ProducerConfigReader;
+import mir.producer.reader.ProducerNodeBuilderLibrary;
+import mir.util.FileMonitor;
+import mir.util.StringRoutines;
+import mircoders.global.MirGlobal;
+import mircoders.global.ProducerEngine;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.localizer.MirProducerLocalizer;
+import mircoders.producer.reader.SupplementalProducerNodeBuilders;
+
+public class MirBasicProducerLocalizer implements MirProducerLocalizer {
+  private List producerFactories;
+  private Map nameToFactory;
+
+  private Map producerRecipes;
+  private List producerRecipeNames;
+
+  protected FileMonitor fileMonitor;
+  protected EntityAdapterModel model;
+  protected Generator.GeneratorLibrary generatorLibrary;
+  protected WriterEngine writerEngine;
+
+  protected LoggerWrapper logger;
+
+  public MirBasicProducerLocalizer() {
+    try {
+      logger = new LoggerWrapper("Localizer.Basic.Producer");
+
+      producerRecipes = new HashMap();
+      producerRecipeNames = new Vector();
+
+      String[] recipes = MirGlobal.config().getStringArray("Mir.Localizer.Producer.ProducerRecipes");
+      for (int i = 0; i<recipes.length; i++) {
+        try {
+          List parts = StringRoutines.separateString(recipes[i], "=");
+          if (parts.size() == 2) {
+            producerRecipes.put(parts.get(0), ProducerEngine.ProducerTask.parseProducerTaskList( (String) parts.get(1)));
+            producerRecipeNames.add(parts.get(0));
+          }
+          else {
+            throw new Exception("'=' expected");
+          }
+        }
+        catch (Throwable t) {
+          logger.error("Error while processing producer recipe '" + recipes[i] + "': " + t.toString());
+        }
+      }
+
+      // for backward compatibility:
+      String allNewProducers = MirGlobal.config().getString("Mir.Localizer.Producer.AllNewProducers");
+      if (allNewProducers!=null && allNewProducers.length()>0) {
+        producerRecipes.put("allnew", ProducerEngine.ProducerTask.parseProducerTaskList(allNewProducers));
+        producerRecipeNames.add("allnew");
+      }
+
+      producerFactories = new Vector();
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      generatorLibrary = MirGlobal.localizer().generators().makeProducerGeneratorLibrary();
+      writerEngine = MirGlobal.localizer().generators().makeWriterEngine();
+      nameToFactory = new HashMap();
+    }
+    catch (Throwable t) {
+      logger.error("MirBasicProducerLocalizer(): Exception "+t.getMessage());
+      model = new EntityAdapterModel();
+    }
+  }
+
+  public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure {
+    return producerRecipeNames;
+  }
+
+  public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure {
+    if (producerRecipes.containsKey(aName))
+      MirGlobal.producerEngine().addTasks((List) producerRecipes.get(aName));
+    else
+      throw new MirLocalizerExc("Unknown recipe name: " + aName);
+  }
+
+  public List factories() throws MirLocalizerExc {
+    if (fileMonitor==null || producerFactories == null || fileMonitor.hasChanged()) {
+      try {
+        List newProducers = new Vector();
+        FileMonitor newFileMonitor = new FileMonitor();
+        setupFactories(newProducers, newFileMonitor);
+
+        producerFactories = newProducers;
+        fileMonitor = newFileMonitor;
+        logger.info("MirBasicProducerLocalizer.factories(): successfully setup factories");
+
+        nameToFactory.clear();
+        Iterator i = producerFactories.iterator();
+        while (i.hasNext()) {
+          ProducerFactory factory = (ProducerFactory) i.next();
+          nameToFactory.put(factory.getName(), factory);
+        }
+      }
+      catch (Throwable t) {
+        logger.error("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage());
+        t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      }
+    }
+
+    return producerFactories;
+  };
+
+  protected void setupProducerNodeBuilderLibrary(ProducerNodeBuilderLibrary aLibrary) throws MirLocalizerFailure {
+    try {
+      DefaultProducerNodeBuilders.registerBuilders(
+          aLibrary, model, generatorLibrary, writerEngine,
+          MirGlobal.config().getString("Home"), MirGlobal.config().getString("Producer.StorageRoot"));
+      SupplementalProducerNodeBuilders.registerBuilders(aLibrary, model);
+    }
+    catch (Throwable t) {
+      throw new MirLocalizerFailure(t.getMessage(), t);
+    }
+  }
+
+  protected void setupFactories(List aFactories, FileMonitor aFileMonitor) throws MirLocalizerExc, MirLocalizerFailure {
+    ProducerConfigReader reader;
+    ProducerNodeBuilderLibrary library = new ProducerNodeBuilderLibrary();
+    setupProducerNodeBuilderLibrary(library);
+    List usedFiles = new Vector();
+    Iterator i;
+
+    aFileMonitor.clear();
+    reader = new ProducerConfigReader();
+    reader.parseFile(MirGlobal.config().getString("Home") + File.separatorChar + MirGlobal.config().getString("Mir.Localizer.ProducerConfigFile"), library, aFactories, usedFiles);
+
+    i = usedFiles.iterator();
+    while (i.hasNext())
+      aFileMonitor.addFile((File) i.next());
+  }
+
+  public ProducerFactory getFactoryForName(String aName) {
+    try {
+      factories();
+    }
+    catch (Throwable t) {
+    }
+
+    return (ProducerFactory) nameToFactory.get(aName);
+  }
+}
index 40f152e..db1146a 100755 (executable)
 
 package mircoders.media;
 
+import java.awt.RenderingHints;
+import java.awt.image.ColorModel;
+import java.awt.image.DataBuffer;
+import java.awt.image.PixelInterleavedSampleModel;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+
 import javax.media.jai.ImageLayout;
 import javax.media.jai.InterpolationBilinear;
 import javax.media.jai.JAI;
 import javax.media.jai.ParameterBlockJAI;
 import javax.media.jai.PlanarImage;
 
-import java.awt.RenderingHints;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-import java.awt.image.PixelInterleavedSampleModel;
+import mir.log.LoggerWrapper;
 
 import com.sun.media.jai.codec.ByteArraySeekableStream;
 import com.sun.media.jai.codec.FileSeekableStream;
 import com.sun.media.jai.codec.SeekableStream;
 
-import mir.log.LoggerWrapper;
-
 /**
  *
  * <p>Title: Image processor</p>
index 3d531ab..7bc0b9b 100755 (executable)
  */
 package  mircoders.media;
 
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.InputStream;\r
-import java.util.List;\r
-import java.util.Vector;\r
-import javax.servlet.ServletContext;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaExc;\r
-import mir.media.MediaFailure;\r
-import mir.media.MirMedia;\r
-import mir.misc.FileUtil;\r
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Vector;
+
+import javax.servlet.ServletContext;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MirMedia;
+import mir.misc.FileUtil;
 import mir.misc.StringUtil;
 
 
@@ -63,7 +64,7 @@ import mir.misc.StringUtil;
  *
  * @see mir.media.MirMedia
  * @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerGeneric.java,v 1.20.2.2 2003/09/03 17:49:39 zapata Exp $
+ * @version $Id: MediaHandlerGeneric.java,v 1.20.2.3 2003/10/23 14:55:26 rk Exp $
  */
 
 public class MediaHandlerGeneric implements MirMedia
index 18b3532..e3f8cb8 100755 (executable)
@@ -31,7 +31,8 @@ package mircoders.media;
 
 import java.io.File;
 import java.io.InputStream;
-import java.util.*;
+import java.util.List;
+import java.util.Vector;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
@@ -58,7 +59,7 @@ import mircoders.entity.EntityImages;
  *
  * @see mir.media.MirMedia
  * @author mh
- * @version $Id: MediaHandlerImages.java,v 1.23.2.1 2003/09/03 17:49:39 zapata Exp $
+ * @version $Id: MediaHandlerImages.java,v 1.23.2.2 2003/10/23 14:55:26 rk Exp $
  */
 
 
index 4d15ba9..9e7baa3 100755 (executable)
@@ -40,8 +40,6 @@ import mir.log.LoggerWrapper;
 import mir.media.MediaExc;
 import mir.media.MediaFailure;
 import mir.misc.StringUtil;
-import mircoders.storage.DatabaseUploadedMedia;
-import mircoders.module.*;
 
 
 /**
index d868ab6..e52a7c6 100755 (executable)
@@ -38,7 +38,6 @@ import mir.module.AbstractModule;
 import mir.module.ModuleExc;
 import mir.module.ModuleFailure;
 import mir.storage.StorageObject;
-import mircoders.storage.DatabaseTopics;
 
 public class ModuleTopics extends AbstractModule {
 
index b3d5f62..9fcd4a1 100755 (executable)
  */
 package mircoders.pdf;
 
+import gnu.regexp.RE;
+import gnu.regexp.REException;
+import gnu.regexp.REMatch;
+import gnu.regexp.REMatchEnumeration;
+
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.net.MalformedURLException;
-import java.util.*;
+import java.util.Iterator;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.EntityBrowser;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.util.DateTimeFunctions;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityImages;
+import mircoders.storage.DatabaseImages;
 
 import com.lowagie.text.BadElementException;
 import com.lowagie.text.Document;
@@ -48,19 +62,6 @@ 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 gnu.regexp.RE;
-import gnu.regexp.REException;
-import gnu.regexp.REMatch;
-import gnu.regexp.REMatchEnumeration;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.*;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.util.DateTimeFunctions;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityImages;
-import mircoders.storage.*;
 
 public class PDFGenerator{
 
index b4208a7..22b3a19 100755 (executable)
@@ -31,8 +31,8 @@ package mircoders.producer;
 
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
-import java.util.GregorianCalendar;
 import java.util.Date;
+import java.util.GregorianCalendar;
 import java.util.Map;
 
 import mir.entity.Entity;
index 77fd4c6..4b7e9eb 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.producer;\r
-\r
-import java.io.PrintWriter;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.*;\r
-\r
-import mir.entity.*;\r
-import mir.entity.EntityList;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.log.LoggerToWriterAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.producer.ProducerFailure;\r
-import mir.producer.ProducerNode;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTMLRoutines;\r
-import mir.util.ParameterExpander;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityImages;\r
-import mircoders.storage.*;\r
-\r
-\r
-public class PDFPreFormattingProducerNode implements ProducerNode {\r
-  private String contentKey;\r
-  private int numLinesBetweenImages;\r
-  private float contentAreaWidthCM;\r
-  private float characterWidthCM;\r
-  private float pixelWidthCM;\r
-  private float lineHeightCM;\r
-\r
-  public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {\r
-    contentKey = aContentKey;\r
-    numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();\r
-    contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();\r
-    characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();\r
-    pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();\r
-    lineHeightCM=(new Float(aLineHeightCM)).floatValue();\r
-\r
-    //    float characterWidthCM = 0.17F;\r
-    //float contentAreaWidthCM = 16;\r
-    //float pixelWidthCM = .03F;\r
-    //float lineHeightCM = .5F;\r
-  }\r
-\r
-  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {\r
-    Object data;\r
-    Entity entity;\r
-\r
-    try {\r
-      data = ParameterExpander.findValueForKey( aValueMap, contentKey );\r
-\r
-      if (! (data instanceof EntityAdapter)) {\r
-        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);\r
-      }\r
-\r
-      entity = ((EntityAdapter) data).getEntity();\r
-      if (! (entity instanceof EntityContent)) {\r
-        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);\r
-      }\r
-\r
-      int currentPosition = 0;\r
-\r
-      //int numLinesBetweenImages=3;\r
-\r
-\r
-\r
-\r
-      int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();\r
-\r
-      boolean outOfText = false;\r
-\r
-      ArrayList brokenUpContent = new ArrayList();\r
-\r
-      Iterator images = new EntityBrowser(\r
-         DatabaseImages.getInstance(),\r
-          "exists (select * from content_x_media where content_id=" + entity.getId() + " and media_id=id)",\r
-          "id desc", 30, -1, 0);\r
-\r
-      String theContent = ((EntityContent) entity).getValue("content_data");\r
-      //remove pesky characters\r
-      theContent = HTMLRoutines.encodeXML(theContent);\r
-      //put in the <BR> tags so we can turn them to empty blocks\r
-      theContent = StringUtil.convertNewline2Break(theContent);\r
-\r
-      if (images == null){\r
-          Map row = new HashMap();\r
-          row.put("text",theContent);\r
-          row.put("hasImage","0");\r
-          brokenUpContent.add(row);\r
-      }\r
-      if (images != null){\r
-          //need to add checks for out of content!\r
-          Map row0 = new HashMap();\r
-          if (numCharsInAnImagelessRow>(theContent).length()){\r
-              row0.put("text",theContent);\r
-              outOfText = true;\r
-          }\r
-          else {\r
-              //break on words so we don't split html entities\r
-              int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);\r
-              row0.put("text",theContent.substring(0,lastSpaceAt));\r
-              currentPosition=lastSpaceAt;\r
-          }\r
-          row0.put("hasImage","0");\r
-          brokenUpContent.add(row0);\r
-          aLogger.debug("CP1 is "+ currentPosition);\r
-          while(images.hasNext()){\r
-              Map row1 = new HashMap();\r
-              Map row2 = new HashMap();\r
-              EntityImages currentImage=(EntityImages) images.next();\r
-              float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();\r
-              float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();\r
-\r
-              //oversize images must be shrunk\r
-              if (img_width>250){\r
-                  img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();\r
-                  img_width=250.0F;\r
-              }\r
-\r
-\r
-              //calculate how much text goes in the column(use 8 pixels to pad the column)\r
-              float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);\r
-              float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int\r
-              //add one line for image description\r
-              int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();\r
-\r
-              row1.put("text_widthCM",Float.toString(text_widthCM));\r
-\r
-              row1.put("img_title",currentImage.getValue("title"));\r
-\r
-              row1.put("img_width",Float.toString(img_width));\r
-              row1.put("img_height",Float.toString(img_height));\r
-\r
-              aLogger.debug("img_width " +Float.toString(img_width));\r
-              aLogger.debug("img_height "+Float.toString(img_height));\r
-\r
-              row1.put("img_src",currentImage.getValue("publish_path"));\r
-              row1.put("hasImage","1");\r
-              if (! outOfText){\r
-                  try {\r
-                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);\r
-                      row1.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
-                      currentPosition=lastSpaceAt;\r
-                  }\r
-                  catch (IndexOutOfBoundsException e){\r
-                      row1.put("text",theContent.substring(currentPosition));\r
-                      outOfText = true;\r
-                          }\r
-              }\r
-              aLogger.debug("CP2 is "+ currentPosition);\r
-              brokenUpContent.add(row1);\r
-\r
-              if (! outOfText){\r
-                  try {\r
-                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);\r
-                      row2.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
-                      currentPosition=lastSpaceAt;\r
-                  }\r
-                  catch (IndexOutOfBoundsException e){\r
-                      row2.put("text",theContent.substring(currentPosition));\r
-                      outOfText = true;\r
-                          }\r
-              }\r
-              row2.put("hasImage","0");\r
-              brokenUpContent.add(row2);\r
-\r
-              aLogger.debug("CP3 is "+ currentPosition);\r
-          }\r
-          Map row3 = new HashMap();\r
-          if (! outOfText){\r
-              row3.put("text",theContent.substring(currentPosition));\r
-              row3.put("hasImage","0");\r
-              brokenUpContent.add(row3);\r
-          }\r
-\r
-      }\r
-\r
-\r
-\r
-\r
-\r
-      ParameterExpander.setValueForKey(\r
-                                       aValueMap,\r
-                                       "data.formatted_content",\r
-                                       new CachingRewindableIterator(brokenUpContent.iterator())\r
-                                       );\r
-\r
-\r
-    }\r
-    catch (Throwable t) {\r
-      aLogger.error("Error while formatting content for PDF: " + t.getMessage());\r
-      t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));\r
-    }\r
-  }\r
-}\r
-\r
-\r
-\r
-\r
+/*
+ * 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 mircoders.producer;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import mir.entity.Entity;
+import mir.entity.EntityBrowser;
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerToWriterAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.producer.ProducerFailure;
+import mir.producer.ProducerNode;
+import mir.util.CachingRewindableIterator;
+import mir.util.HTMLRoutines;
+import mir.util.ParameterExpander;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityImages;
+import mircoders.storage.DatabaseImages;
+
+
+public class PDFPreFormattingProducerNode implements ProducerNode {
+  private String contentKey;
+  private int numLinesBetweenImages;
+  private float contentAreaWidthCM;
+  private float characterWidthCM;
+  private float pixelWidthCM;
+  private float lineHeightCM;
+
+  public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {
+    contentKey = aContentKey;
+    numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();
+    contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();
+    characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();
+    pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();
+    lineHeightCM=(new Float(aLineHeightCM)).floatValue();
+
+    //    float characterWidthCM = 0.17F;
+    //float contentAreaWidthCM = 16;
+    //float pixelWidthCM = .03F;
+    //float lineHeightCM = .5F;
+  }
+
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+    Object data;
+    Entity entity;
+
+    try {
+      data = ParameterExpander.findValueForKey( aValueMap, contentKey );
+
+      if (! (data instanceof EntityAdapter)) {
+        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);
+      }
+
+      entity = ((EntityAdapter) data).getEntity();
+      if (! (entity instanceof EntityContent)) {
+        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
+      }
+
+      int currentPosition = 0;
+
+      //int numLinesBetweenImages=3;
+
+
+
+
+      int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();
+
+      boolean outOfText = false;
+
+      ArrayList brokenUpContent = new ArrayList();
+
+      Iterator images = new EntityBrowser(
+         DatabaseImages.getInstance(),
+          "exists (select * from content_x_media where content_id=" + entity.getId() + " and media_id=id)",
+          "id desc", 30, -1, 0);
+
+      String theContent = ((EntityContent) entity).getValue("content_data");
+      //remove pesky characters
+      theContent = HTMLRoutines.encodeXML(theContent);
+      //put in the <BR> tags so we can turn them to empty blocks
+      theContent = StringUtil.convertNewline2Break(theContent);
+
+      if (images == null){
+          Map row = new HashMap();
+          row.put("text",theContent);
+          row.put("hasImage","0");
+          brokenUpContent.add(row);
+      }
+      if (images != null){
+          //need to add checks for out of content!
+          Map row0 = new HashMap();
+          if (numCharsInAnImagelessRow>(theContent).length()){
+              row0.put("text",theContent);
+              outOfText = true;
+          }
+          else {
+              //break on words so we don't split html entities
+              int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);
+              row0.put("text",theContent.substring(0,lastSpaceAt));
+              currentPosition=lastSpaceAt;
+          }
+          row0.put("hasImage","0");
+          brokenUpContent.add(row0);
+          aLogger.debug("CP1 is "+ currentPosition);
+          while(images.hasNext()){
+              Map row1 = new HashMap();
+              Map row2 = new HashMap();
+              EntityImages currentImage=(EntityImages) images.next();
+              float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();
+              float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();
+
+              //oversize images must be shrunk
+              if (img_width>250){
+                  img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();
+                  img_width=250.0F;
+              }
+
+
+              //calculate how much text goes in the column(use 8 pixels to pad the column)
+              float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);
+              float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int
+              //add one line for image description
+              int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();
+
+              row1.put("text_widthCM",Float.toString(text_widthCM));
+
+              row1.put("img_title",currentImage.getValue("title"));
+
+              row1.put("img_width",Float.toString(img_width));
+              row1.put("img_height",Float.toString(img_height));
+
+              aLogger.debug("img_width " +Float.toString(img_width));
+              aLogger.debug("img_height "+Float.toString(img_height));
+
+              row1.put("img_src",currentImage.getValue("publish_path"));
+              row1.put("hasImage","1");
+              if (! outOfText){
+                  try {
+                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);
+                      row1.put("text",theContent.substring(currentPosition,lastSpaceAt));
+                      currentPosition=lastSpaceAt;
+                  }
+                  catch (IndexOutOfBoundsException e){
+                      row1.put("text",theContent.substring(currentPosition));
+                      outOfText = true;
+                          }
+              }
+              aLogger.debug("CP2 is "+ currentPosition);
+              brokenUpContent.add(row1);
+
+              if (! outOfText){
+                  try {
+                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);
+                      row2.put("text",theContent.substring(currentPosition,lastSpaceAt));
+                      currentPosition=lastSpaceAt;
+                  }
+                  catch (IndexOutOfBoundsException e){
+                      row2.put("text",theContent.substring(currentPosition));
+                      outOfText = true;
+                          }
+              }
+              row2.put("hasImage","0");
+              brokenUpContent.add(row2);
+
+              aLogger.debug("CP3 is "+ currentPosition);
+          }
+          Map row3 = new HashMap();
+          if (! outOfText){
+              row3.put("text",theContent.substring(currentPosition));
+              row3.put("hasImage","0");
+              brokenUpContent.add(row3);
+          }
+
+      }
+
+
+
+
+
+      ParameterExpander.setValueForKey(
+                                       aValueMap,
+                                       "data.formatted_content",
+                                       new CachingRewindableIterator(brokenUpContent.iterator())
+                                       );
+
+
+    }
+    catch (Throwable t) {
+      aLogger.error("Error while formatting content for PDF: " + t.getMessage());
+      t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));
+    }
+  }
+}
+
+
+
+
index 613b831..0d6d7df 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-import java.io.PrintWriter;\r
-import java.util.HashMap;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.adapter.*;\r
-import mir.generator.Generator;\r
-import mir.generator.GeneratorHelper;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-\r
-\r
-public class ServletHelper {\r
-  private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");\r
-\r
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {\r
-    return makeGenerationData(aRequest, aResponse, aLocales, "bundles.adminlocal", "bundles.admin");\r
-  }\r
-\r
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {\r
-    return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);\r
-  }\r
-\r
-  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {\r
-    try {\r
-      MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
-      Map result=GeneratorHelper.makeBasicGenerationData(aLocales,aBundle,aDefaultBundle);\r
-      if (configuration.getString("Mir.Admin.ShowLoggedinUsers").equals("1")) {\r
-       result.put("loggedinusers", MirGlobal.getLoggedInUsers());\r
-      }\r
-      else\r
-       result.put("loggedinusers", null);\r
-\r
-      // ML: hackish\r
-      ((Map) result.get("config")).put("actionRoot",\r
-             aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));\r
-\r
-      result.put("returnurl", null);\r
-      result.put("login_user", getUserAdapter(aRequest));\r
-\r
-      return result;\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
-    logger.debug("generator used: " + aGenerator);\r
-\r
-    Generator generator;\r
-\r
-    try {\r
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);\r
-\r
-      generator.generate(aWriter, aGenerationData, logger);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
-    Generator generator;\r
-\r
-    try {\r
-      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);\r
-\r
-      generator.generate(aWriter, aGenerationData, logger);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);\r
-    }\r
-  }\r
-\r
-  public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure {\r
-    redirect(aResponse, "module="+aModule+"&do="+aMethod);\r
-  }\r
-\r
-  public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {\r
-    if (aUser!=null)\r
-      aRequest.getSession().setAttribute("login.uid", aUser);\r
-    else\r
-      aRequest.getSession().removeAttribute("login.uid");\r
-  }\r
-\r
-  public static EntityUsers getUser(HttpServletRequest aRequest) {\r
-    return (EntityUsers) aRequest.getSession().getAttribute("login.uid");\r
-  }\r
-\r
-  public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {\r
-    try {\r
-      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid"));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure (t);\r
-    }\r
-  }\r
-\r
-  public static String getUserName(HttpServletRequest aRequest) {\r
-    EntityUsers user = getUser(aRequest);\r
-\r
-    if (user!=null)\r
-      return user.getValue("login");\r
-    else\r
-      return "nobody";\r
-  }\r
-}\r
+/*
+ * 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 mircoders.servlet;
+
+import java.io.PrintWriter;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityAdapter;
+import mir.generator.Generator;
+import mir.generator.GeneratorHelper;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+
+
+public class ServletHelper {
+  private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");
+
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {
+    return makeGenerationData(aRequest, aResponse, aLocales, "bundles.adminlocal", "bundles.admin");
+  }
+
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {
+    return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);
+  }
+
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {
+    try {
+      MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+      Map result=GeneratorHelper.makeBasicGenerationData(aLocales,aBundle,aDefaultBundle);
+      if (configuration.getString("Mir.Admin.ShowLoggedinUsers").equals("1")) {
+       result.put("loggedinusers", MirGlobal.getLoggedInUsers());
+      }
+      else
+       result.put("loggedinusers", null);
+
+      // ML: hackish
+      ((Map) result.get("config")).put("actionRoot",
+             aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));
+
+      result.put("returnurl", null);
+      result.put("login_user", getUserAdapter(aRequest));
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
+    logger.debug("generator used: " + aGenerator);
+
+    Generator generator;
+
+    try {
+      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);
+
+      generator.generate(aWriter, aGenerationData, logger);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
+    Generator generator;
+
+    try {
+      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
+
+      generator.generate(aWriter, aGenerationData, logger);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {
+    try {
+      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);
+    }
+  }
+
+  public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure {
+    redirect(aResponse, "module="+aModule+"&do="+aMethod);
+  }
+
+  public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {
+    if (aUser!=null)
+      aRequest.getSession().setAttribute("login.uid", aUser);
+    else
+      aRequest.getSession().removeAttribute("login.uid");
+  }
+
+  public static EntityUsers getUser(HttpServletRequest aRequest) {
+    return (EntityUsers) aRequest.getSession().getAttribute("login.uid");
+  }
+
+  public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {
+    try {
+      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid"));
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure (t);
+    }
+  }
+
+  public static String getUserName(HttpServletRequest aRequest) {
+    EntityUsers user = getUser(aRequest);
+
+    if (user!=null)
+      return user.getValue("login");
+    else
+      return "nobody";
+  }
+}
index 836a377..0f046e6 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.servlet;\r
-\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.URLBuilder;\r
-import mircoders.global.Abuse;\r
-import mircoders.global.MirGlobal;\r
-\r
-public class ServletModuleAbuse extends ServletModule {\r
-  private static ServletModuleAbuse instance = new ServletModuleAbuse();\r
-  private String editFilterTemplate;\r
-  private String listFiltersTemplate;\r
-  private String mainTemplate;\r
-  private String viewLogTemplate;\r
-\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleAbuse() {\r
-    logger = new LoggerWrapper("ServletModule.Abuse");\r
-    defaultAction = "showsettings";\r
-\r
-    editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template");\r
-    listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template");\r
-    viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template");\r
-    mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template");\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    String id=requestParser.getParameterWithDefault("id", "");\r
-\r
-    if (id.equals("")) {\r
-      editfilter(aRequest, aResponse, "", "", "", "", "", "", "");\r
-    }\r
-    else {\r
-      Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id);\r
-      if (filter==null)\r
-        throw new ServletModuleExc("Filter not found");\r
-\r
-      editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), "");\r
-    }\r
-  }\r
-\r
-  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-        String anId, String aType, String anExpression, String aComments,\r
-        String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc {\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      responseData.put("id", anId);\r
-      responseData.put("type", aType);\r
-      responseData.put("expression", anExpression);\r
-      responseData.put("comments", aComments);\r
-      responseData.put("articleaction", anArticleAction);\r
-      responseData.put("commentaction", aCommentAction);\r
-      responseData.put("errormessage", anErrorMessage);\r
-\r
-      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());\r
-      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());\r
-      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void updatefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String type=requestParser.getParameterWithDefault("type", "");\r
-    String id=requestParser.getParameterWithDefault("id", "");\r
-    String expression=requestParser.getParameterWithDefault("expression", "");\r
-    String commentaction=requestParser.getParameterWithDefault("commentaction", "");\r
-    String articleaction=requestParser.getParameterWithDefault("articleaction", "");\r
-    String comments=requestParser.getParameterWithDefault("comments", "");\r
-\r
-    String errorMessage;\r
-\r
-    String userName = ServletHelper.getUserName(aRequest);\r
-\r
-    if (id.equals("")) {\r
-      errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction);\r
-      logAdminUsage(aRequest, "?", "object added");\r
-    }\r
-    else {\r
-      errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction);\r
-      logAdminUsage(aRequest, id, "object modified");\r
-    }\r
-\r
-    if (errorMessage!=null) {\r
-      editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage);\r
-    }\r
-    else {\r
-      MirGlobal.abuse().save();\r
-      showfilters(aRequest, aResponse);\r
-    }\r
-  }\r
-\r
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String id=requestParser.getParameterWithDefault("id", "");\r
-    MirGlobal.abuse().deleteFilter(id);\r
-    logAdminUsage(aRequest, id, "object deleted");\r
-\r
-    MirGlobal.abuse().save();\r
-\r
-    showfilters(aRequest, aResponse);\r
-  }\r
-\r
-  public void moveup(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String id=requestParser.getParameterWithDefault("id", "");\r
-    MirGlobal.abuse().moveFilterUp(id);\r
-\r
-    MirGlobal.abuse().save();\r
-    logAdminUsage(aRequest, id, "object moved upwards");\r
-\r
-    showfilters(aRequest, aResponse);\r
-  }\r
-\r
-  public void movedown(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String id=requestParser.getParameterWithDefault("id", "");\r
-    MirGlobal.abuse().moveFilterDown(id);\r
-    logAdminUsage(aRequest, id, "object moved downwards");\r
-\r
-    MirGlobal.abuse().save();\r
-\r
-    showfilters(aRequest, aResponse);\r
-  }\r
-\r
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    editfilter(aRequest, aResponse, "", "", "", "", "", "", "");\r
-  }\r
-\r
-  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      urlBuilder.setValue("module", "Abuse");\r
-      urlBuilder.setValue("do", "showfilters");\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      responseData.put("filters", MirGlobal.abuse().getFilters());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      urlBuilder.setValue("module", "Abuse");\r
-      urlBuilder.setValue("do", "showsettings");\r
-\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());\r
-      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());\r
-\r
-      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));\r
-      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));\r
-      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));\r
-      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));\r
-      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));\r
-      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());\r
-      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, mainTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      HTTPRequestParser parser = new HTTPRequestParser(aRequest);\r
-\r
-      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));\r
-      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));\r
-      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));\r
-\r
-      try {\r
-        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));\r
-      }\r
-      catch (Throwable t) {\r
-      }\r
-\r
-      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));\r
-\r
-      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));\r
-      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));\r
-\r
-      MirGlobal.abuse().save();\r
-      logAdminUsage(aRequest, "settings", "object modified");\r
-\r
-      showsettings(aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      urlBuilder.setValue("module", "Abuse");\r
-      urlBuilder.setValue("do", "showlog");\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      responseData.put("log", MirGlobal.abuse().getLog());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, viewLogTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
+/*
+ * 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 mircoders.servlet;
+
+import java.util.Locale;
+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.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.util.HTTPRequestParser;
+import mir.util.URLBuilder;
+import mircoders.global.Abuse;
+import mircoders.global.MirGlobal;
+
+public class ServletModuleAbuse extends ServletModule {
+  private static ServletModuleAbuse instance = new ServletModuleAbuse();
+  private String editFilterTemplate;
+  private String listFiltersTemplate;
+  private String mainTemplate;
+  private String viewLogTemplate;
+
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleAbuse() {
+    logger = new LoggerWrapper("ServletModule.Abuse");
+    defaultAction = "showsettings";
+
+    editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template");
+    listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template");
+    viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template");
+    mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template");
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    String id=requestParser.getParameterWithDefault("id", "");
+
+    if (id.equals("")) {
+      editfilter(aRequest, aResponse, "", "", "", "", "", "", "");
+    }
+    else {
+      Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id);
+      if (filter==null)
+        throw new ServletModuleExc("Filter not found");
+
+      editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), "");
+    }
+  }
+
+  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse,
+        String anId, String aType, String anExpression, String aComments,
+        String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc {
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+
+      responseData.put("id", anId);
+      responseData.put("type", aType);
+      responseData.put("expression", anExpression);
+      responseData.put("comments", aComments);
+      responseData.put("articleaction", anArticleAction);
+      responseData.put("commentaction", aCommentAction);
+      responseData.put("errormessage", anErrorMessage);
+
+      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());
+      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());
+      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void updatefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String type=requestParser.getParameterWithDefault("type", "");
+    String id=requestParser.getParameterWithDefault("id", "");
+    String expression=requestParser.getParameterWithDefault("expression", "");
+    String commentaction=requestParser.getParameterWithDefault("commentaction", "");
+    String articleaction=requestParser.getParameterWithDefault("articleaction", "");
+    String comments=requestParser.getParameterWithDefault("comments", "");
+
+    String errorMessage;
+
+    String userName = ServletHelper.getUserName(aRequest);
+
+    if (id.equals("")) {
+      errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction);
+      logAdminUsage(aRequest, "?", "object added");
+    }
+    else {
+      errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction);
+      logAdminUsage(aRequest, id, "object modified");
+    }
+
+    if (errorMessage!=null) {
+      editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage);
+    }
+    else {
+      MirGlobal.abuse().save();
+      showfilters(aRequest, aResponse);
+    }
+  }
+
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String id=requestParser.getParameterWithDefault("id", "");
+    MirGlobal.abuse().deleteFilter(id);
+    logAdminUsage(aRequest, id, "object deleted");
+
+    MirGlobal.abuse().save();
+
+    showfilters(aRequest, aResponse);
+  }
+
+  public void moveup(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String id=requestParser.getParameterWithDefault("id", "");
+    MirGlobal.abuse().moveFilterUp(id);
+
+    MirGlobal.abuse().save();
+    logAdminUsage(aRequest, id, "object moved upwards");
+
+    showfilters(aRequest, aResponse);
+  }
+
+  public void movedown(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String id=requestParser.getParameterWithDefault("id", "");
+    MirGlobal.abuse().moveFilterDown(id);
+    logAdminUsage(aRequest, id, "object moved downwards");
+
+    MirGlobal.abuse().save();
+
+    showfilters(aRequest, aResponse);
+  }
+
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    editfilter(aRequest, aResponse, "", "", "", "", "", "", "");
+  }
+
+  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    URLBuilder urlBuilder = new URLBuilder();
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+
+      urlBuilder.setValue("module", "Abuse");
+      urlBuilder.setValue("do", "showfilters");
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      responseData.put("filters", MirGlobal.abuse().getFilters());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    URLBuilder urlBuilder = new URLBuilder();
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+
+      urlBuilder.setValue("module", "Abuse");
+      urlBuilder.setValue("do", "showsettings");
+
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());
+      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());
+
+      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));
+      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));
+      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));
+      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));
+      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));
+      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());
+      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, mainTemplate);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      HTTPRequestParser parser = new HTTPRequestParser(aRequest);
+
+      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));
+      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));
+      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));
+
+      try {
+        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));
+      }
+      catch (Throwable t) {
+      }
+
+      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));
+
+      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));
+      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));
+
+      MirGlobal.abuse().save();
+      logAdminUsage(aRequest, "settings", "object modified");
+
+      showsettings(aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    URLBuilder urlBuilder = new URLBuilder();
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      urlBuilder.setValue("module", "Abuse");
+      urlBuilder.setValue("do", "showlog");
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      responseData.put("log", MirGlobal.abuse().getLog());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, viewLogTemplate);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
 }
\ No newline at end of file
index db2cdf1..ac41a31 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.URLBuilder;\r
-import mircoders.global.MirGlobal;\r
-\r
-public class ServletModuleAdmin extends ServletModule\r
-{\r
-  private static ServletModuleAdmin instance = new ServletModuleAdmin();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleAdmin() {\r
-    logger = new LoggerWrapper("ServletModule.Admin");\r
-    defaultAction = "start";\r
-  }\r
-\r
-  public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      urlBuilder.setValue("module", "Admin");\r
-      urlBuilder.setValue("do", "superusermenu");\r
-\r
-      responseData.put("thisurl" , urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template");\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    String startTemplate = configuration.getString("Mir.StartTemplate");\r
-    String sessionUrl = aResponse.encodeURL("");\r
-\r
-    try {\r
-      Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}\r
-          , "bundles.admin", "bundles.adminlocal");\r
-      mergeData.put("messages",\r
-                    new CachingRewindableIterator(\r
-          new EntityIteratorAdapter("", "webdb_create desc", 10,\r
-                                    MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));\r
-\r
-      mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());\r
-      mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());\r
-\r
-      mergeData.put("searchvalue", null);\r
-      mergeData.put("searchfield", null);\r
-      mergeData.put("searchispublished", null);\r
-      mergeData.put("searcharticletype", null);\r
-      mergeData.put("searchorder", null);\r
-      mergeData.put("selectarticleurl", null);\r
-      mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate);\r
-    }\r
-    catch (Exception e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-}\r
+/*
+ * 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 mircoders.servlet;
+
+import java.util.Locale;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModule;
+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; }
+
+  private ServletModuleAdmin() {
+    logger = new LoggerWrapper("ServletModule.Admin");
+    defaultAction = "start";
+  }
+
+  public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    URLBuilder urlBuilder = new URLBuilder();
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      urlBuilder.setValue("module", "Admin");
+      urlBuilder.setValue("do", "superusermenu");
+
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template");
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    String startTemplate = configuration.getString("Mir.StartTemplate");
+    String sessionUrl = aResponse.encodeURL("");
+
+    try {
+      Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}
+          , "bundles.admin", "bundles.adminlocal");
+      mergeData.put("messages",
+                    new CachingRewindableIterator(
+          new EntityIteratorAdapter("", "webdb_create desc", 10,
+                                    MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
+
+      mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
+      mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
+
+      mergeData.put("searchvalue", null);
+      mergeData.put("searchfield", null);
+      mergeData.put("searchispublished", null);
+      mergeData.put("searcharticletype", null);
+      mergeData.put("searchorder", null);
+      mergeData.put("selectarticleurl", null);
+      mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate);
+    }
+    catch (Exception e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+}
index a35f177..fe04cb1 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.config.MirPropertiesConfiguration;
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseAudio;
-import mircoders.global.*;
 
 /*
  *
index 4629911..de606b0 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.servlet;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.JDBCStringRoutines;\r
-import mir.util.SQLQueryBuilder;\r
-import mir.util.URLBuilder;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleComment;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseContent;\r
-\r
-/*\r
- *  ServletModuleComment - controls navigation for Comments\r
- *\r
- *\r
- *  @author the mir-coders\r
- */\r
-\r
-public class ServletModuleComment extends ServletModule\r
-{\r
-  private ModuleContent  moduleContent;\r
-\r
-  private static ServletModuleComment instance = new ServletModuleComment();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleComment() {\r
-    logger = new LoggerWrapper("ServletModule.Comment");\r
-    try {\r
-      mainModule = new ModuleComment(DatabaseComment.getInstance());\r
-      moduleContent = new ModuleContent(DatabaseContent.getInstance());\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("servletmodule comment could not be initialized:" + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
-    try {\r
-      MirGlobal.accessControl().general().assertMayDeleteComments(ServletHelper.getUser(aRequest));\r
-\r
-      super.delete(aRequest, aResponse);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("Invalid call: id not supplied ");\r
-\r
-    editObject(aRequest, aResponse, idParam);\r
-  }\r
-\r
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
-      Map comment;\r
-      URLBuilder urlBuilder = new URLBuilder();\r
-\r
-      urlBuilder.setValue("module", "Comment");\r
-      urlBuilder.setValue("do", "edit");\r
-      urlBuilder.setValue("id", anId);\r
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
-\r
-      if (anId != null) {\r
-        responseData.put("new", Boolean.FALSE);\r
-        comment = model.makeEntityAdapter("comment", mainModule.getById(anId));\r
-      }\r
-      else {\r
-        List fields = DatabaseComment.getInstance().getFields();\r
-        responseData.put("new", Boolean.TRUE);\r
-        comment = new HashMap();\r
-        Iterator i = fields.iterator();\r
-        while (i.hasNext()) {\r
-          comment.put(i.next(), null);\r
-        }\r
-      }\r
-      responseData.put("comment", comment);\r
-\r
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String  mediaIdParam = aRequest.getParameter("mid");\r
-    String  commentId = aRequest.getParameter("commentid");\r
-\r
-    if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");\r
-\r
-    try {\r
-      EntityComment comment = (EntityComment) mainModule.getById(commentId);\r
-      comment.attach(mediaIdParam);\r
-    }\r
-    catch(Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    logAdminUsage(aRequest, commentId, "media " + mediaIdParam + " attached");\r
-\r
-    editObject(aRequest, aResponse, commentId);\r
-  }\r
-\r
-  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String  commentId = aRequest.getParameter("commentid");\r
-    String  midParam = aRequest.getParameter("mid");\r
-    if (commentId == null)\r
-      throw new ServletModuleExc("smod comment :: dettach :: commentid missing");\r
-    if (midParam == null)\r
-      throw new ServletModuleExc("smod comment :: dettach :: mid missing");\r
-\r
-    try {\r
-      EntityComment comment = (EntityComment)mainModule.getById(commentId);\r
-      comment.dettach(commentId, midParam);\r
-    }\r
-    catch(Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    logAdminUsage(aRequest, commentId, "media " + midParam + " deattached");\r
-\r
-    editObject(aRequest, aResponse, commentId);\r
-  }\r
-\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String where = requestParser.getParameter("where");\r
-    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");\r
-    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
-\r
-    returnList(aRequest, aResponse, where, order, offset);\r
-  }\r
-\r
-  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
-\r
-    String queryField = "";\r
-    String searchField = requestParser.getParameter("searchfield");\r
-    String searchText = requestParser.getParameter("searchtext");\r
-    String searchIsPublished = requestParser.getParameter("searchispublished");\r
-    String searchStatus = requestParser.getParameter("searchstatus");\r
-    String searchOrder = requestParser.getParameter("searchorder");\r
-\r
-    if (searchIsPublished.equals("0")) {\r
-      queryBuilder.appendAndCondition("is_published='f'");\r
-    }\r
-    else if (searchIsPublished.equals("1")) {\r
-      queryBuilder.appendAndCondition("is_published='t'");\r
-    }\r
-\r
-    if (searchText.length()>0) {\r
-        queryBuilder.appendAndCondition(\r
-          "lower("+ searchField + ") like " +\r
-          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");\r
-    }\r
-\r
-    if (searchStatus.length()>0) {\r
-      queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus));\r
-    }\r
-\r
-    if (searchOrder.length()>0) {\r
-      if (searchOrder.equals("datedesc"))\r
-        queryBuilder.appendDescendingOrder("webdb_create");\r
-      else if (searchOrder.equals("dateasc"))\r
-        queryBuilder.appendAscendingOrder("webdb_create");\r
-      else if (searchOrder.equals("articletitle"))\r
-        queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");\r
-      else if (searchOrder.equals("creator"))\r
-        queryBuilder.appendDescendingOrder("creator");\r
-    }\r
-\r
-    returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);\r
-  }\r
-\r
-  public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String articleIdString = aRequest.getParameter("articleid");\r
-    int articleId;\r
-\r
-    try {\r
-      articleId  = Integer.parseInt(articleIdString);\r
-\r
-      returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
-\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    EntityAdapterModel model;\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-\r
-      Object commentList =\r
-          new CachingRewindableIterator(\r
-            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
-              MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset)\r
-      );\r
-\r
-      responseData.put("nexturl", null);\r
-      responseData.put("prevurl", null);\r
-\r
-      count=mainModule.getSize(aWhereClause);\r
-\r
-      urlBuilder.setValue("module", "Comment");\r
-      urlBuilder.setValue("do", "list");\r
-      urlBuilder.setValue("where", aWhereClause);\r
-      urlBuilder.setValue("order", anOrderByClause);\r
-\r
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
-      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
-      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));\r
-      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
-\r
-      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
-      responseData.put("searchtext", requestParser.getParameter("searchtext"));\r
-      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
-      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));\r
-      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
-\r
-      urlBuilder.setValue("offset", anOffset);\r
-      responseData.put("offset" , new Integer(anOffset).toString());\r
-      responseData.put("thisurl" , urlBuilder.getQuery());\r
-\r
-      if (count>=anOffset+nrEntitiesPerListPage) {\r
-        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
-        responseData.put("nexturl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      if (anOffset>0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
-        responseData.put("prevurl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      responseData.put("comments", commentList);\r
-      responseData.put("from" , Integer.toString(anOffset+1));\r
-      responseData.put("count", Integer.toString(count));\r
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-      String returnUrl = requestParser.getParameter("returnurl");\r
-\r
-      String idParam = aRequest.getParameter("id");\r
-      if (idParam == null)\r
-        throw new ServletModuleExc("Wrong call: (id) is missing");\r
-\r
-      Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance());\r
-\r
-      String content_id = aRequest.getParameter("id");\r
-\r
-      if (!withValues.containsKey("is_published"))\r
-        withValues.put("is_published","0");\r
-      if (!withValues.containsKey("is_html"))\r
-        withValues.put("is_html","0");\r
-\r
-      String webdbCreate = (String) withValues.get("webdb_create");\r
-      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
-        withValues.remove("webdb_create");\r
-\r
-      String id = mainModule.set(withValues);\r
-\r
-      logAdminUsage(aRequest, id, "object modified");\r
-\r
-      if (returnUrl!=null){\r
-        redirect(aResponse, returnUrl);\r
-      }\r
-      else\r
-        editObject(aRequest, aResponse, idParam);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
+/*
+ * 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 mircoders.servlet;
+
+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 mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.CachingRewindableIterator;
+import mir.util.HTTPRequestParser;
+import mir.util.JDBCStringRoutines;
+import mir.util.SQLQueryBuilder;
+import mir.util.URLBuilder;
+import mircoders.entity.EntityComment;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleComment;
+import mircoders.module.ModuleContent;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseContent;
+
+/*
+ *  ServletModuleComment - controls navigation for Comments
+ *
+ *
+ *  @author the mir-coders
+ */
+
+public class ServletModuleComment extends ServletModule
+{
+  private ModuleContent  moduleContent;
+
+  private static ServletModuleComment instance = new ServletModuleComment();
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleComment() {
+    logger = new LoggerWrapper("ServletModule.Comment");
+    try {
+      mainModule = new ModuleComment(DatabaseComment.getInstance());
+      moduleContent = new ModuleContent(DatabaseContent.getInstance());
+    }
+    catch (Exception e) {
+      logger.error("servletmodule comment could not be initialized:" + e.getMessage());
+    }
+  }
+
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+    try {
+      MirGlobal.accessControl().general().assertMayDeleteComments(ServletHelper.getUser(aRequest));
+
+      super.delete(aRequest, aResponse);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+
+    if (idParam == null)
+      throw new ServletModuleExc("Invalid call: id not supplied ");
+
+    editObject(aRequest, aResponse, idParam);
+  }
+
+  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)});
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
+      Map comment;
+      URLBuilder urlBuilder = new URLBuilder();
+
+      urlBuilder.setValue("module", "Comment");
+      urlBuilder.setValue("do", "edit");
+      urlBuilder.setValue("id", anId);
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+
+      if (anId != null) {
+        responseData.put("new", Boolean.FALSE);
+        comment = model.makeEntityAdapter("comment", mainModule.getById(anId));
+      }
+      else {
+        List fields = DatabaseComment.getInstance().getFields();
+        responseData.put("new", Boolean.TRUE);
+        comment = new HashMap();
+        Iterator i = fields.iterator();
+        while (i.hasNext()) {
+          comment.put(i.next(), null);
+        }
+      }
+      responseData.put("comment", comment);
+
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String  mediaIdParam = aRequest.getParameter("mid");
+    String  commentId = aRequest.getParameter("commentid");
+
+    if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
+
+    try {
+      EntityComment comment = (EntityComment) mainModule.getById(commentId);
+      comment.attach(mediaIdParam);
+    }
+    catch(Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+
+    logAdminUsage(aRequest, commentId, "media " + mediaIdParam + " attached");
+
+    editObject(aRequest, aResponse, commentId);
+  }
+
+  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String  commentId = aRequest.getParameter("commentid");
+    String  midParam = aRequest.getParameter("mid");
+    if (commentId == null)
+      throw new ServletModuleExc("smod comment :: dettach :: commentid missing");
+    if (midParam == null)
+      throw new ServletModuleExc("smod comment :: dettach :: mid missing");
+
+    try {
+      EntityComment comment = (EntityComment)mainModule.getById(commentId);
+      comment.dettach(commentId, midParam);
+    }
+    catch(Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+
+    logAdminUsage(aRequest, commentId, "media " + midParam + " deattached");
+
+    editObject(aRequest, aResponse, commentId);
+  }
+
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String where = requestParser.getParameter("where");
+    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
+    int offset = requestParser.getIntegerWithDefault("offset", 0);
+
+    returnList(aRequest, aResponse, where, order, offset);
+  }
+
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
+
+    String queryField = "";
+    String searchField = requestParser.getParameter("searchfield");
+    String searchText = requestParser.getParameter("searchtext");
+    String searchIsPublished = requestParser.getParameter("searchispublished");
+    String searchStatus = requestParser.getParameter("searchstatus");
+    String searchOrder = requestParser.getParameter("searchorder");
+
+    if (searchIsPublished.equals("0")) {
+      queryBuilder.appendAndCondition("is_published='f'");
+    }
+    else if (searchIsPublished.equals("1")) {
+      queryBuilder.appendAndCondition("is_published='t'");
+    }
+
+    if (searchText.length()>0) {
+        queryBuilder.appendAndCondition(
+          "lower("+ searchField + ") like " +
+          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");
+    }
+
+    if (searchStatus.length()>0) {
+      queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus));
+    }
+
+    if (searchOrder.length()>0) {
+      if (searchOrder.equals("datedesc"))
+        queryBuilder.appendDescendingOrder("webdb_create");
+      else if (searchOrder.equals("dateasc"))
+        queryBuilder.appendAscendingOrder("webdb_create");
+      else if (searchOrder.equals("articletitle"))
+        queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");
+      else if (searchOrder.equals("creator"))
+        queryBuilder.appendDescendingOrder("creator");
+    }
+
+    returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
+  }
+
+  public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String articleIdString = aRequest.getParameter("articleid");
+    int articleId;
+
+    try {
+      articleId  = Integer.parseInt(articleIdString);
+
+      returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
+
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+    EntityAdapterModel model;
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      model = MirGlobal.localizer().dataModel().adapterModel();
+
+      Object commentList =
+          new CachingRewindableIterator(
+            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,
+              MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset)
+      );
+
+      responseData.put("nexturl", null);
+      responseData.put("prevurl", null);
+
+      count=mainModule.getSize(aWhereClause);
+
+      urlBuilder.setValue("module", "Comment");
+      urlBuilder.setValue("do", "list");
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
+      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
+
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));
+      responseData.put("searchtext", requestParser.getParameter("searchtext"));
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
+      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));
+
+      urlBuilder.setValue("offset", anOffset);
+      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      if (count>=anOffset+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("comments", commentList);
+      responseData.put("from" , Integer.toString(anOffset+1));
+      responseData.put("count", Integer.toString(count));
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      String returnUrl = requestParser.getParameter("returnurl");
+
+      String idParam = aRequest.getParameter("id");
+      if (idParam == null)
+        throw new ServletModuleExc("Wrong call: (id) is missing");
+
+      Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance());
+
+      String content_id = aRequest.getParameter("id");
+
+      if (!withValues.containsKey("is_published"))
+        withValues.put("is_published","0");
+      if (!withValues.containsKey("is_html"))
+        withValues.put("is_html","0");
+
+      String webdbCreate = (String) withValues.get("webdb_create");
+      if (webdbCreate==null || webdbCreate.trim().length()==0)
+        withValues.remove("webdb_create");
+
+      String id = mainModule.set(withValues);
+
+      logAdminUsage(aRequest, id, "object modified");
+
+      if (returnUrl!=null){
+        redirect(aResponse, returnUrl);
+      }
+      else
+        editObject(aRequest, aResponse, idParam);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
 }
\ No newline at end of file
index 7696fee..0ed1df2 100755 (executable)
  */
 package mircoders.servlet;
 
-import mir.config.MirPropertiesConfiguration;
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleCommentStatus;
 import mircoders.storage.DatabaseCommentStatus;
-import mircoders.global.*;
 
 
 public class ServletModuleCommentStatus extends ServletModule
index c9ef69f..7e8684a 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.servlet;\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.*;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.JDBCStringRoutines;\r
-import mir.util.SQLQueryBuilder;\r
-import mir.util.*;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-\r
-/*\r
- *  ServletModuleContent -\r
- *  deliver html for the article admin form.\r
- *\r
- * @version $Id: ServletModuleContent.java,v 1.52.2.11 2003/09/24 02:08:04 zapata Exp $\r
- * @author rk, mir-coders\r
- *\r
- */\r
-\r
-public class ServletModuleContent extends ServletModule\r
-{\r
-  private static ServletModuleContent instance = new ServletModuleContent();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleContent() {\r
-    super();\r
-\r
-    logger = new LoggerWrapper("ServletModule.Content");\r
-\r
-    try {\r
-      mainModule = new ModuleContent(DatabaseContent.getInstance());\r
-    }\r
-    catch (Throwable e) {\r
-      logger.fatal("ServletModuleContent could not be initialized: " + e.toString());\r
-    }\r
-  }\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    String where = requestParser.getParameter("where");\r
-    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");\r
-    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
-    String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
-\r
-    returnList(aRequest, aResponse, where, order, offset, selectArticleUrl);\r
-  }\r
-\r
-  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
-      String searchField = requestParser.getParameterWithDefault("searchfield", "");\r
-      String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();\r
-      String searchOrder = requestParser.getParameterWithDefault("searchorder", "");\r
-      String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");\r
-      String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");\r
-      String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
-\r
-      if (searchValue.length()>0) {\r
-        if (searchField.equals("id"))\r
-          queryBuilder.appendAndCondition(\r
-            "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");\r
-        else if (searchField.equals("contents"))\r
-          queryBuilder.appendAndCondition(\r
-            "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+\r
-            " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");\r
-        else\r
-          queryBuilder.appendAndCondition(\r
-            "lower("+ searchField + ") like " +\r
-            "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");\r
-      }\r
-\r
-      if (searchispublished.length()>0) {\r
-        if (searchispublished.equals("0"))\r
-          queryBuilder.appendAndCondition("is_published='f'");\r
-        else\r
-          queryBuilder.appendAndCondition("is_published='t'");\r
-      }\r
-\r
-      if (searchArticleType.length()>0) {\r
-        queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));\r
-      }\r
-\r
-      if (searchOrder.length()>0) {\r
-        if (searchOrder.equals("datedesc"))\r
-          queryBuilder.appendDescendingOrder("webdb_create");\r
-        else if (searchOrder.equals("dateasc"))\r
-          queryBuilder.appendAscendingOrder("webdb_create");\r
-        else if (searchOrder.equals("title"))\r
-          queryBuilder.appendAscendingOrder("title");\r
-        else if (searchOrder.equals("creator"))\r
-          queryBuilder.appendAscendingOrder("creator");\r
-      }\r
-\r
-      returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    editObject(aRequest, aResponse, null);\r
-  }\r
-\r
-\r
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-//theLog.printDebugInfo(":: content :: trying to insert");\r
-    try {\r
-      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
-\r
-      String now = StringUtil.date2webdbDate(new GregorianCalendar());\r
-      withValues.put("date", now);\r
-      withValues.put("publish_path", StringUtil.webdbDate2path(now));\r
-      withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
-      withValues.put("is_produced", "0");\r
-      if (!withValues.containsKey("is_published"))\r
-        withValues.put("is_published","0");\r
-      if (!withValues.containsKey("is_html"))\r
-        withValues.put("is_html","0");\r
-\r
-      String webdbCreate = (String) withValues.get("webdb_create");\r
-      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
-        withValues.remove("webdb_create");\r
-\r
-      String id = mainModule.add(withValues);\r
-      logAdminUsage(aRequest, id, "object added");\r
-\r
-      List topics;\r
-\r
-      DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic"));\r
-\r
-      editObject(aRequest, aResponse, id);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("Invalid call: id not supplied ");\r
-    editObject(aRequest, aResponse, idParam);\r
-  }\r
-\r
-// methods for attaching media file\r
-  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String  mediaIdParam = aRequest.getParameter("mid");\r
-    String  articleId = aRequest.getParameter("articleid");\r
-\r
-    if (articleId == null || mediaIdParam==null)\r
-      throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");\r
-\r
-    try {\r
-      EntityContent entContent = (EntityContent) mainModule.getById(articleId);\r
-      entContent.attach(mediaIdParam);\r
-    }\r
-    catch(Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    logAdminUsage(aRequest, articleId, "media " + mediaIdParam + " attached");\r
-\r
-    editObject(aRequest, aResponse, articleId);\r
-  }\r
-\r
-  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String  articleId = aRequest.getParameter("articleid");\r
-    String  midParam = aRequest.getParameter("mid");\r
-    if (articleId == null)\r
-      throw new ServletModuleExc("smod content :: dettach :: articleid missing");\r
-    if (midParam == null)\r
-      throw new ServletModuleExc("smod content :: dettach :: mid missing");\r
-\r
-    try {\r
-      EntityContent entContent = (EntityContent)mainModule.getById(articleId);\r
-      entContent.dettach(articleId, midParam);\r
-    }\r
-    catch(Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    logAdminUsage(aRequest, articleId, "media " + midParam + " deattached");\r
-\r
-    editObject(aRequest, aResponse, articleId);\r
-  }\r
-\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-      String returnUrl = requestParser.getParameter("returnurl");\r
-\r
-      String idParam = aRequest.getParameter("id");\r
-      if (idParam == null)\r
-        throw new ServletModuleExc("Wrong call: (id) is missing");\r
-\r
-      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
-\r
-      String content_id = aRequest.getParameter("id");\r
-\r
-      withValues.put("is_produced", "0");\r
-      if (!withValues.containsKey("is_published"))\r
-        withValues.put("is_published","0");\r
-      if (!withValues.containsKey("is_html"))\r
-        withValues.put("is_html","0");\r
-\r
-      String webdbCreate = (String) withValues.get("webdb_create");\r
-      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
-        withValues.remove("webdb_create");\r
-\r
-      String id = mainModule.set(withValues);\r
-\r
-      logAdminUsage(aRequest, id, "object modified");\r
-\r
-      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));\r
-\r
-      if (returnUrl!=null && !returnUrl.equals("")){\r
-        redirect(aResponse, returnUrl);\r
-      }\r
-      else\r
-        editObject(aRequest, aResponse, idParam);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   * HelperMethod shows the basic article editing form.\r
-   *\r
-   * if the "id" parameter is null, it means show an empty form to add a new\r
-   * article.\r
-   *\r
-   * @param id\r
-   * @param aRequest\r
-   * @param aResponse\r
-   * @throws ServletModuleExc\r
-   */\r
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)\r
-      throws ServletModuleExc {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
-      Map article;\r
-      URLBuilder urlBuilder = new URLBuilder();\r
-\r
-      urlBuilder.setValue("module", "Content");\r
-      urlBuilder.setValue("do", "edit");\r
-      urlBuilder.setValue("id", id);\r
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
-\r
-      if (id!=null) {\r
-        responseData.put("new", Boolean.FALSE);\r
-        article = model.makeEntityAdapter("content", mainModule.getById(id));\r
-      }\r
-      else {\r
-        List fields = DatabaseContent.getInstance().getFields();\r
-        responseData.put("new", Boolean.TRUE);\r
-        article = new HashMap();\r
-        Iterator i = fields.iterator();\r
-        while (i.hasNext()) {\r
-          article.put(i.next(), null);\r
-        }\r
-\r
-        article.put("to_topics", null);\r
-\r
-        MirGlobal.localizer().adminInterface().initializeArticle(article);\r
-      }\r
-      responseData.put("article", article);\r
-\r
-      List topicsList = new Vector();\r
-\r
-      String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");\r
-\r
-      if (topicCategories.length==0 ) {\r
-        Map categoryMap = new HashMap();\r
-        categoryMap.put("key", "topic");\r
-        categoryMap.put("listtype", "0");\r
-        categoryMap.put("listparameter", "3");\r
-        categoryMap.put("items",\r
-                        new EntityIteratorAdapter("", "title",\r
-            20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
-        topicsList.add(categoryMap);\r
-      }\r
-      else\r
-      {\r
-\r
-        for (int i = 0; i < topicCategories.length; i++) {\r
-          try {\r
-            Map categoryMap = new HashMap();\r
-            List parts = StringRoutines.splitString(topicCategories[i], ":");\r
-            String key = null;\r
-            String listtype = "0";\r
-            String listparameter = "5";\r
-            String where = "";\r
-            String order = "";\r
-\r
-            if (parts.size() > 0)\r
-              key = (String) parts.get(0);\r
-            if (parts.size() > 1)\r
-              listtype = (String) parts.get(1);\r
-            if (parts.size() > 2)\r
-              listparameter = (String) parts.get(2);\r
-            if (parts.size() > 3)\r
-              where = (String) parts.get(3);\r
-            if (parts.size() > 4)\r
-              order = (String) parts.get(4);\r
-\r
-            if (key != null) {\r
-              categoryMap.put("key", key);\r
-              categoryMap.put("listtype", listtype);\r
-              categoryMap.put("listparameter", listparameter);\r
-              categoryMap.put("items",\r
-                              new EntityIteratorAdapter(where, order,\r
-                  20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
-              topicsList.add(categoryMap);\r
-            }\r
-          }\r
-          catch (Throwable t) {\r
-            logger.error("error while preparing topics: " + t.toString());\r
-          }\r
-        }\r
-      }\r
-\r
-      responseData.put("topics", topicsList);\r
-\r
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
-    this.returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, null);\r
-  }\r
-\r
-  public void returnList(\r
-       HttpServletRequest aRequest,\r
-       HttpServletResponse aResponse,\r
-       String aWhereClause,\r
-       String anOrderByClause,\r
-       int anOffset,\r
-       String aSelectArticleUrl) throws ServletModuleExc {\r
-\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    EntityAdapterModel model;\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-\r
-      Object articleList =\r
-          new CachingRewindableIterator(\r
-            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
-               MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset)\r
-      );\r
-\r
-      responseData.put("nexturl", null);\r
-      responseData.put("prevurl", null);\r
-\r
-      count=mainModule.getSize(aWhereClause);\r
-\r
-      urlBuilder.setValue("module", "Content");\r
-      urlBuilder.setValue("do", "list");\r
-      urlBuilder.setValue("where", aWhereClause);\r
-      urlBuilder.setValue("order", anOrderByClause);\r
-\r
-\r
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
-      urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));\r
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
-      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
-      urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));\r
-      urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);\r
-\r
-      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
-      responseData.put("searchvalue", requestParser.getParameter("searchvalue"));\r
-      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
-      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
-      responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));\r
-      responseData.put("selectarticleurl", aSelectArticleUrl);\r
-\r
-      urlBuilder.setValue("offset", anOffset);\r
-      responseData.put("offset" , new Integer(anOffset).toString());\r
-      responseData.put("thisurl" , urlBuilder.getQuery());\r
-\r
-      if (count>=anOffset+nrEntitiesPerListPage) {\r
-        urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));\r
-        responseData.put("nexturl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      if (anOffset>0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
-        responseData.put("prevurl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      responseData.put("articles", articleList);\r
-\r
-      responseData.put("from" , Integer.toString(anOffset+1));\r
-      responseData.put("count", Integer.toString(count));\r
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
-      responseData.put("offset" , Integer.toString(anOffset));\r
-      responseData.put("order", anOrderByClause);\r
-      responseData.put("where" , aWhereClause);\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      URLBuilder urlBuilder = new URLBuilder();\r
-\r
-      urlBuilder.setValue("module", "Content");\r
-      urlBuilder.setValue("do", "setparent");\r
-      urlBuilder.setValue("childid", requestParser.getParameter("id"));\r
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
-\r
-      returnList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      String articleId = requestParser.getParameter("article_id");\r
-\r
-      if (articleId == null)\r
-        throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");\r
-\r
-      returnList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    String articleId = aRequest.getParameter("childid");\r
-    String parentId  = aRequest.getParameter("id");\r
-    String returnUrl = aRequest.getParameter("returnurl");\r
-\r
-    try {\r
-      EntityContent article = (EntityContent) mainModule.getById(articleId);\r
-      article.setValueForProperty("to_content", parentId);\r
-      article.setProduced(false);\r
-      article.update();\r
-      logAdminUsage(aRequest, articleId, "parent set to " + parentId);\r
-    }\r
-    catch(Throwable e) {\r
-      logger.error("ServletModuleContent.setparent: " + e.getMessage());\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    redirect(aResponse, returnUrl);\r
-  }\r
-\r
-  public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    String articleId = requestParser.getParameter("id");\r
-    String returnUrl = requestParser.getParameter("returnurl");\r
-\r
-    try {\r
-      EntityContent article = (EntityContent) mainModule.getById(articleId);\r
-      article.setValueForProperty("to_content", "");\r
-      article.setProduced(false);\r
-      article.update();\r
-      logAdminUsage(aRequest, articleId, "parent cleared");\r
-    }\r
-    catch(Throwable e) {\r
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      logger.error("ServletModuleContent.clearparent: " + e.getMessage());\r
-\r
-      throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);\r
-    }\r
-\r
-    redirect(aResponse, returnUrl);\r
-  }\r
-}\r
+/*
+ * 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 mircoders.servlet;
+
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.util.CachingRewindableIterator;
+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.global.MirGlobal;
+import mircoders.module.ModuleContent;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseContentToTopics;
+
+/*
+ *  ServletModuleContent -
+ *  deliver html for the article admin form.
+ *
+ * @version $Id: ServletModuleContent.java,v 1.52.2.12 2003/10/23 14:55:25 rk Exp $
+ * @author rk, mir-coders
+ *
+ */
+
+public class ServletModuleContent extends ServletModule
+{
+  private static ServletModuleContent instance = new ServletModuleContent();
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleContent() {
+    super();
+
+    logger = new LoggerWrapper("ServletModule.Content");
+
+    try {
+      mainModule = new ModuleContent(DatabaseContent.getInstance());
+    }
+    catch (Throwable e) {
+      logger.fatal("ServletModuleContent could not be initialized: " + e.toString());
+    }
+  }
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    String where = requestParser.getParameter("where");
+    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
+    int offset = requestParser.getIntegerWithDefault("offset", 0);
+    String selectArticleUrl = requestParser.getParameter("selectarticleurl");
+
+    returnList(aRequest, aResponse, where, order, offset, selectArticleUrl);
+  }
+
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
+      String searchField = requestParser.getParameterWithDefault("searchfield", "");
+      String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
+      String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
+      String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
+      String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
+      String selectArticleUrl = requestParser.getParameter("selectarticleurl");
+
+      if (searchValue.length()>0) {
+        if (searchField.equals("id"))
+          queryBuilder.appendAndCondition(
+            "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
+        else if (searchField.equals("contents"))
+          queryBuilder.appendAndCondition(
+            "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
+            " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
+        else
+          queryBuilder.appendAndCondition(
+            "lower("+ searchField + ") like " +
+            "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
+      }
+
+      if (searchispublished.length()>0) {
+        if (searchispublished.equals("0"))
+          queryBuilder.appendAndCondition("is_published='f'");
+        else
+          queryBuilder.appendAndCondition("is_published='t'");
+      }
+
+      if (searchArticleType.length()>0) {
+        queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
+      }
+
+      if (searchOrder.length()>0) {
+        if (searchOrder.equals("datedesc"))
+          queryBuilder.appendDescendingOrder("webdb_create");
+        else if (searchOrder.equals("dateasc"))
+          queryBuilder.appendAscendingOrder("webdb_create");
+        else if (searchOrder.equals("title"))
+          queryBuilder.appendAscendingOrder("title");
+        else if (searchOrder.equals("creator"))
+          queryBuilder.appendAscendingOrder("creator");
+      }
+
+      returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    editObject(aRequest, aResponse, null);
+  }
+
+
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+//theLog.printDebugInfo(":: content :: trying to insert");
+    try {
+      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
+
+      String now = StringUtil.date2webdbDate(new GregorianCalendar());
+      withValues.put("date", now);
+      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"))
+        withValues.put("is_published","0");
+      if (!withValues.containsKey("is_html"))
+        withValues.put("is_html","0");
+
+      String webdbCreate = (String) withValues.get("webdb_create");
+      if (webdbCreate==null || webdbCreate.trim().length()==0)
+        withValues.remove("webdb_create");
+
+      String id = mainModule.add(withValues);
+      logAdminUsage(aRequest, id, "object added");
+
+      List topics;
+
+      DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic"));
+
+      editObject(aRequest, aResponse, id);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+    if (idParam == null)
+      throw new ServletModuleExc("Invalid call: id not supplied ");
+    editObject(aRequest, aResponse, idParam);
+  }
+
+// methods for attaching media file
+  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String  mediaIdParam = aRequest.getParameter("mid");
+    String  articleId = aRequest.getParameter("articleid");
+
+    if (articleId == null || mediaIdParam==null)
+      throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
+
+    try {
+      EntityContent entContent = (EntityContent) mainModule.getById(articleId);
+      entContent.attach(mediaIdParam);
+    }
+    catch(Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+
+    logAdminUsage(aRequest, articleId, "media " + mediaIdParam + " attached");
+
+    editObject(aRequest, aResponse, articleId);
+  }
+
+  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String  articleId = aRequest.getParameter("articleid");
+    String  midParam = aRequest.getParameter("mid");
+    if (articleId == null)
+      throw new ServletModuleExc("smod content :: dettach :: articleid missing");
+    if (midParam == null)
+      throw new ServletModuleExc("smod content :: dettach :: mid missing");
+
+    try {
+      EntityContent entContent = (EntityContent)mainModule.getById(articleId);
+      entContent.dettach(articleId, midParam);
+    }
+    catch(Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+
+    logAdminUsage(aRequest, articleId, "media " + midParam + " deattached");
+
+    editObject(aRequest, aResponse, articleId);
+  }
+
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      String returnUrl = requestParser.getParameter("returnurl");
+
+      String idParam = aRequest.getParameter("id");
+      if (idParam == null)
+        throw new ServletModuleExc("Wrong call: (id) is missing");
+
+      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
+
+      String content_id = aRequest.getParameter("id");
+
+      withValues.put("is_produced", "0");
+      if (!withValues.containsKey("is_published"))
+        withValues.put("is_published","0");
+      if (!withValues.containsKey("is_html"))
+        withValues.put("is_html","0");
+
+      String webdbCreate = (String) withValues.get("webdb_create");
+      if (webdbCreate==null || webdbCreate.trim().length()==0)
+        withValues.remove("webdb_create");
+
+      String id = mainModule.set(withValues);
+
+      logAdminUsage(aRequest, id, "object modified");
+
+      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
+
+      if (returnUrl!=null && !returnUrl.equals("")){
+        redirect(aResponse, returnUrl);
+      }
+      else
+        editObject(aRequest, aResponse, idParam);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+
+  /**
+   * HelperMethod shows the basic article editing form.
+   *
+   * if the "id" parameter is null, it means show an empty form to add a new
+   * article.
+   *
+   * @param id
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   */
+  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)
+      throws ServletModuleExc {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
+      Map article;
+      URLBuilder urlBuilder = new URLBuilder();
+
+      urlBuilder.setValue("module", "Content");
+      urlBuilder.setValue("do", "edit");
+      urlBuilder.setValue("id", id);
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+
+      if (id!=null) {
+        responseData.put("new", Boolean.FALSE);
+        article = model.makeEntityAdapter("content", mainModule.getById(id));
+      }
+      else {
+        List fields = DatabaseContent.getInstance().getFields();
+        responseData.put("new", Boolean.TRUE);
+        article = new HashMap();
+        Iterator i = fields.iterator();
+        while (i.hasNext()) {
+          article.put(i.next(), null);
+        }
+
+        article.put("to_topics", null);
+
+        MirGlobal.localizer().adminInterface().initializeArticle(article);
+      }
+      responseData.put("article", article);
+
+      List topicsList = new Vector();
+
+      String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");
+
+      if (topicCategories.length==0 ) {
+        Map categoryMap = new HashMap();
+        categoryMap.put("key", "topic");
+        categoryMap.put("listtype", "0");
+        categoryMap.put("listparameter", "3");
+        categoryMap.put("items",
+                        new EntityIteratorAdapter("", "title",
+            20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+        topicsList.add(categoryMap);
+      }
+      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",
+                              new EntityIteratorAdapter(where, order,
+                  20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+              topicsList.add(categoryMap);
+            }
+          }
+          catch (Throwable t) {
+            logger.error("error while preparing topics: " + t.toString());
+          }
+        }
+      }
+
+      responseData.put("topics", topicsList);
+
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
+    this.returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, null);
+  }
+
+  public void returnList(
+       HttpServletRequest aRequest,
+       HttpServletResponse aResponse,
+       String aWhereClause,
+       String anOrderByClause,
+       int anOffset,
+       String aSelectArticleUrl) throws ServletModuleExc {
+
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+    EntityAdapterModel model;
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      model = MirGlobal.localizer().dataModel().adapterModel();
+
+      Object articleList =
+          new CachingRewindableIterator(
+            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,
+               MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset)
+      );
+
+      responseData.put("nexturl", null);
+      responseData.put("prevurl", null);
+
+      count=mainModule.getSize(aWhereClause);
+
+      urlBuilder.setValue("module", "Content");
+      urlBuilder.setValue("do", "list");
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
+      urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
+      urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
+      urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
+
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));
+      responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));
+      responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
+      responseData.put("selectarticleurl", aSelectArticleUrl);
+
+      urlBuilder.setValue("offset", anOffset);
+      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      if (count>=anOffset+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("articles", articleList);
+
+      responseData.put("from" , Integer.toString(anOffset+1));
+      responseData.put("count", Integer.toString(count));
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+      responseData.put("offset" , Integer.toString(anOffset));
+      responseData.put("order", anOrderByClause);
+      responseData.put("where" , aWhereClause);
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      URLBuilder urlBuilder = new URLBuilder();
+
+      urlBuilder.setValue("module", "Content");
+      urlBuilder.setValue("do", "setparent");
+      urlBuilder.setValue("childid", requestParser.getParameter("id"));
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+
+      returnList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      String articleId = requestParser.getParameter("article_id");
+
+      if (articleId == null)
+        throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+
+      returnList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    String articleId = aRequest.getParameter("childid");
+    String parentId  = aRequest.getParameter("id");
+    String returnUrl = aRequest.getParameter("returnurl");
+
+    try {
+      EntityContent article = (EntityContent) mainModule.getById(articleId);
+      article.setValueForProperty("to_content", parentId);
+      article.setProduced(false);
+      article.update();
+      logAdminUsage(aRequest, articleId, "parent set to " + parentId);
+    }
+    catch(Throwable e) {
+      logger.error("ServletModuleContent.setparent: " + e.getMessage());
+      throw new ServletModuleFailure(e);
+    }
+
+    redirect(aResponse, returnUrl);
+  }
+
+  public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    String articleId = requestParser.getParameter("id");
+    String returnUrl = requestParser.getParameter("returnurl");
+
+    try {
+      EntityContent article = (EntityContent) mainModule.getById(articleId);
+      article.setValueForProperty("to_content", "");
+      article.setProduced(false);
+      article.update();
+      logAdminUsage(aRequest, articleId, "parent cleared");
+    }
+    catch(Throwable e) {
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      logger.error("ServletModuleContent.clearparent: " + e.getMessage());
+
+      throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
+    }
+
+    redirect(aResponse, returnUrl);
+  }
+}
index 2b805b8..0ae7bb6 100755 (executable)
@@ -41,6 +41,7 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Vector;
+
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
@@ -58,8 +59,8 @@ import mir.util.URLBuilder;
  *  Allows one to do a basic edit of a file in a directory specified
  *  in the config file.
  *
- * @author $Author: zapata $
- * @version $Revision: 1.13.2.3 $ $Date: 2003/09/19 02:54:51 $
+ * @author $Author: rk $
+ * @version $Revision: 1.13.2.4 $ $Date: 2003/10/23 14:55:25 $
  *
  */
 
index 6ae6d20..d5d32ae 100755 (executable)
  */
 package mircoders.servlet;
 
-import java.util.Iterator;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.storage.StorageObjectFailure;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.JDBCStringRoutines;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleContent;\r
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.storage.StorageObjectFailure;
+import mir.util.CachingRewindableIterator;
+import mir.util.HTTPRequestParser;
+import mir.util.JDBCStringRoutines;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleContent;
 import mircoders.storage.DatabaseContent;
 
 /*
index 2364264..bfc301e 100755 (executable)
@@ -31,15 +31,14 @@ package mircoders.servlet;
 
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleImages;
 import mircoders.storage.DatabaseImages;
-import mircoders.global.*;
 
 /*
  *  ServletModuleImages -
  *
- * @version $Id: ServletModuleImages.java,v 1.26.2.2 2003/09/03 17:49:40 zapata Exp $
+ * @version $Id: ServletModuleImages.java,v 1.26.2.3 2003/10/23 14:55:25 rk Exp $
  * @author RK, the mir-coders group
  */
 
index d6526cd..235a160 100755 (executable)
@@ -31,10 +31,9 @@ package mircoders.servlet;
 
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleLanguage;
 import mircoders.storage.DatabaseLanguage;
-import mircoders.global.*;
 
 /*
  *  ServletModuleLanguage -
index e4badfa..c880b12 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.util.StringRoutines;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.module.ModuleComment;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseContent;\r
-\r
-public class ServletModuleLocalizer extends ServletModule {\r
-  private static ServletModuleLocalizer instance = new ServletModuleLocalizer();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ModuleContent contentModule;\r
-  private ModuleComment commentModule;\r
-  private List administerOperations;\r
-\r
-  private ServletModuleLocalizer() {\r
-    try {\r
-      logger = new LoggerWrapper("ServletModule.Localizer");\r
-\r
-      contentModule = new ModuleContent(DatabaseContent.getInstance());\r
-      commentModule = new ModuleComment(DatabaseComment.getInstance());\r
-\r
-      administerOperations = new Vector();\r
-\r
-      String settings[] = configuration.getStringArray("Mir.Localizer.Admin.AdministerOperations");\r
-\r
-      if (settings!=null) {\r
-        for (int i = 0; i < settings.length; i++) {\r
-          String setting = settings[i].trim();\r
-\r
-          if (setting.length() > 0) {\r
-            List parts = StringRoutines.splitString(setting, ":");\r
-            if (parts.size() != 2) {\r
-              logger.error("config error: " + settings[i] + ", 2 parts expected");\r
-            }\r
-            else {\r
-              Map entry = new HashMap();\r
-              entry.put("name", (String) parts.get(0));\r
-              entry.put("url", (String) parts.get(1));\r
-              administerOperations.add(entry);\r
-            }\r
-          }\r
-        }\r
-      }\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage());\r
-    }\r
-\r
-\r
-  }\r
-\r
-  public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) {\r
-    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;\r
-    EntityAdapter comment;\r
-    EntityComment entity;\r
-\r
-    try {\r
-      entity = (EntityComment) commentModule.getById(anId);\r
-\r
-      if (entity != null) {\r
-        MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation);\r
-        logger.info("Operation " + anOperation + " successfully performed on comment " + anId);\r
-        logAdminUsage(aRequest, "comment."+anId, "operation " + anOperation + " performed");\r
-      }\r
-      else {\r
-        logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public void commentoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    String commentIdString = aRequest.getParameter("id");\r
-    String operationString = aRequest.getParameter("operation");\r
-    String returnUrlString = aRequest.getParameter("returnurl");\r
-\r
-    performCommentOperation(aRequest, commentIdString, operationString);\r
-\r
-    redirect(aResponse, returnUrlString);\r
-  }\r
-\r
-  public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    String returnUrlString = aRequest.getParameter("returnurl");\r
-\r
-    String[] operations = aRequest.getParameterValues("operation");\r
-\r
-    if (operations!=null) {\r
-      for (int i = 0; i < operations.length; i++) {\r
-        if (operations[i].length() > 0) {\r
-          List parts = StringRoutines.splitString(operations[i], ";");\r
-\r
-          if (parts.size() != 2) {\r
-            logger.error("commentoperationbatch: operation string invalid: " +\r
-                         operations[i]);\r
-          }\r
-          else {\r
-            String commentIdString = (String) parts.get(0);\r
-            String operationString = (String) parts.get(1);\r
-\r
-            performCommentOperation(aRequest, commentIdString, operationString);\r
-          }\r
-        }\r
-      }\r
-    }\r
-\r
-    redirect(aResponse, returnUrlString);\r
-  }\r
-\r
-  public void performArticleOperation(HttpServletRequest aRequest, String anId, String anOperation) {\r
-    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;\r
-    EntityAdapter article;\r
-    EntityContent entity;\r
-\r
-    try {\r
-      entity = (EntityContent) contentModule.getById(anId);\r
-\r
-      if (entity != null) {\r
-        MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation);\r
-        logger.info("Operation " + anOperation + " successfully performed on article " + anId);\r
-        logAdminUsage(aRequest, "article."+anId, "operation " + anOperation + " performed");\r
-      }\r
-      else {\r
-        logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null");\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public void articleoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    String articleIdString = aRequest.getParameter("articleid");\r
-    String operationString = aRequest.getParameter("operation");\r
-    String returnUrlString = aRequest.getParameter("returnurl");\r
-\r
-    performArticleOperation(aRequest, articleIdString, operationString);\r
-    redirect(aResponse, returnUrlString);\r
-  }\r
-\r
-  public void articleoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    String returnUrlString = aRequest.getParameter("returnurl");\r
-\r
-    String[] operations = aRequest.getParameterValues("operation");\r
-\r
-    if (operations!=null) {\r
-\r
-      for (int i = 0; i < operations.length; i++) {\r
-        if (operations[i].length() > 0) {\r
-          List parts = StringRoutines.splitString(operations[i], ";");\r
-\r
-          if (parts.size() != 2) {\r
-            logger.error("articleoperationbatch: operation string invalid: " + operations[i]);\r
-          }\r
-          else {\r
-            String articleIdString = (String) parts.get(0);\r
-            String operationString = (String) parts.get(1);\r
-\r
-            performArticleOperation(aRequest, articleIdString, operationString);\r
-          }\r
-        }\r
-      }\r
-    }\r
-\r
-    redirect(aResponse, returnUrlString);\r
-  }\r
-\r
-  public List getAdministerOperations() throws ServletModuleExc {\r
-    return administerOperations;\r
-  }\r
+/*
+ * 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 mircoders.servlet;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.module.ModuleComment;
+import mircoders.module.ModuleContent;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseContent;
+
+public class ServletModuleLocalizer extends ServletModule {
+  private static ServletModuleLocalizer instance = new ServletModuleLocalizer();
+  public static ServletModule getInstance() { return instance; }
+
+  private ModuleContent contentModule;
+  private ModuleComment commentModule;
+  private List administerOperations;
+
+  private ServletModuleLocalizer() {
+    try {
+      logger = new LoggerWrapper("ServletModule.Localizer");
+
+      contentModule = new ModuleContent(DatabaseContent.getInstance());
+      commentModule = new ModuleComment(DatabaseComment.getInstance());
+
+      administerOperations = new Vector();
+
+      String settings[] = configuration.getStringArray("Mir.Localizer.Admin.AdministerOperations");
+
+      if (settings!=null) {
+        for (int i = 0; i < settings.length; i++) {
+          String setting = settings[i].trim();
+
+          if (setting.length() > 0) {
+            List parts = StringRoutines.splitString(setting, ":");
+            if (parts.size() != 2) {
+              logger.error("config error: " + settings[i] + ", 2 parts expected");
+            }
+            else {
+              Map entry = new HashMap();
+              entry.put("name", (String) parts.get(0));
+              entry.put("url", (String) parts.get(1));
+              administerOperations.add(entry);
+            }
+          }
+        }
+      }
+    }
+    catch (Exception e) {
+      logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage());
+    }
+
+
+  }
+
+  public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) {
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;
+    EntityAdapter comment;
+    EntityComment entity;
+
+    try {
+      entity = (EntityComment) commentModule.getById(anId);
+
+      if (entity != null) {
+        MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation);
+        logger.info("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");
+      }
+    }
+    catch (Throwable e) {
+      logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage());
+    }
+  }
+
+  public void commentoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    String commentIdString = aRequest.getParameter("id");
+    String operationString = aRequest.getParameter("operation");
+    String returnUrlString = aRequest.getParameter("returnurl");
+
+    performCommentOperation(aRequest, commentIdString, operationString);
+
+    redirect(aResponse, returnUrlString);
+  }
+
+  public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    String returnUrlString = aRequest.getParameter("returnurl");
+
+    String[] operations = aRequest.getParameterValues("operation");
+
+    if (operations!=null) {
+      for (int i = 0; i < operations.length; i++) {
+        if (operations[i].length() > 0) {
+          List parts = StringRoutines.splitString(operations[i], ";");
+
+          if (parts.size() != 2) {
+            logger.error("commentoperationbatch: operation string invalid: " +
+                         operations[i]);
+          }
+          else {
+            String commentIdString = (String) parts.get(0);
+            String operationString = (String) parts.get(1);
+
+            performCommentOperation(aRequest, commentIdString, operationString);
+          }
+        }
+      }
+    }
+
+    redirect(aResponse, returnUrlString);
+  }
+
+  public void performArticleOperation(HttpServletRequest aRequest, String anId, String anOperation) {
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;
+    EntityAdapter article;
+    EntityContent entity;
+
+    try {
+      entity = (EntityContent) contentModule.getById(anId);
+
+      if (entity != null) {
+        MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation);
+        logger.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");
+      }
+    }
+    catch (Throwable e) {
+      logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
+    }
+  }
+
+  public void articleoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    String articleIdString = aRequest.getParameter("articleid");
+    String operationString = aRequest.getParameter("operation");
+    String returnUrlString = aRequest.getParameter("returnurl");
+
+    performArticleOperation(aRequest, articleIdString, operationString);
+    redirect(aResponse, returnUrlString);
+  }
+
+  public void articleoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    String returnUrlString = aRequest.getParameter("returnurl");
+
+    String[] operations = aRequest.getParameterValues("operation");
+
+    if (operations!=null) {
+
+      for (int i = 0; i < operations.length; i++) {
+        if (operations[i].length() > 0) {
+          List parts = StringRoutines.splitString(operations[i], ";");
+
+          if (parts.size() != 2) {
+            logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
+          }
+          else {
+            String articleIdString = (String) parts.get(0);
+            String operationString = (String) parts.get(1);
+
+            performArticleOperation(aRequest, articleIdString, operationString);
+          }
+        }
+      }
+    }
+
+    redirect(aResponse, returnUrlString);
+  }
+
+  public List getAdministerOperations() throws ServletModuleExc {
+    return administerOperations;
+  }
 }
\ No newline at end of file
index 68408d5..d0195e6 100755 (executable)
@@ -1,71 +1,71 @@
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-/**\r
- *\r
- */\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.servlet.ServletModule;\r
-import mir.storage.StorageObjectFailure;\r
-import mircoders.module.ModuleMediafolder;\r
-import mircoders.storage.DatabaseMediafolder;\r
-import mircoders.global.*;\r
-\r
-public class ServletModuleMediafolder extends ServletModule\r
-{\r
-  public static ServletModule getInstance() { return instance; }\r
-  private static ServletModuleMediafolder instance = new ServletModuleMediafolder();\r
-\r
-  private ServletModuleMediafolder() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Mediafolder");\r
-\r
-    try {\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-      definition = "mediaFolder";\r
-      mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance());\r
-    }\r
-    catch (Throwable t) {\r
-      logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString());\r
-    }\r
-  }\r
-\r
-  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    aNewObject.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
-  }\r
+/*
+ * 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 mircoders.servlet;
+
+/**
+ *
+ */
+
+import java.util.GregorianCalendar;
+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 mircoders.global.MirGlobal;
+import mircoders.module.ModuleMediafolder;
+import mircoders.storage.DatabaseMediafolder;
+
+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 {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "mediaFolder";
+      mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance());
+    }
+    catch (Throwable t) {
+      logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString());
+    }
+  }
+
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    aNewObject.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+  }
 }
\ No newline at end of file
index a8ec504..31c2246 100755 (executable)
@@ -1,77 +1,78 @@
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleFailure;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleMessage;\r
-import mircoders.storage.DatabaseMessages;\r
-\r
-/**\r
- * Title:       ServletModuleMessage\r
- * Description:\r
- * Copyright:   Copyright (c) 2001-2002\r
- * Company:     mir-coders\r
- * @author\r
- * @version 1.0\r
- */\r
-\r
-\r
-public class ServletModuleMessage extends ServletModule\r
-{\r
-  private static ServletModuleMessage instance = new ServletModuleMessage();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleMessage() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Messages");\r
-\r
-    try {\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-      definition = "internalMessage";\r
-      mainModule = new ModuleMessage(DatabaseMessages.getInstance());\r
-    }\r
-    catch (Throwable e) {\r
-      logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());\r
-\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    aNewObject.put("creator", ServletHelper.getUserName(aRequest));\r
-  }\r
-}\r
+/*
+ * 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 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.ServletModuleFailure;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleMessage;
+import mircoders.storage.DatabaseMessages;
+
+/**
+ * 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 {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "internalMessage";
+      mainModule = new ModuleMessage(DatabaseMessages.getInstance());
+    }
+    catch (Throwable e) {
+      logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());
+
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    aNewObject.put("creator", ServletHelper.getUserName(aRequest));
+  }
+}
index c75380a..6172d1c 100755 (executable)
@@ -30,6 +30,9 @@
 
 package mircoders.servlet;
 
+import gnu.regexp.RE;
+import gnu.regexp.REMatch;
+
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -47,24 +50,10 @@ import java.util.Map;
 import java.util.Random;
 import java.util.Set;
 import java.util.Vector;
+
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpUtils;
-
-import org.apache.commons.fileupload.FileItem;
-import org.apache.commons.net.smtp.SMTPClient;
-import org.apache.commons.net.smtp.SMTPReply;
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.queryParser.QueryParser;
-import org.apache.lucene.search.Hits;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.Searcher;
-import org.apache.struts.util.MessageResources;
-import gnu.regexp.RE;
-import gnu.regexp.REMatch;
 
 import mir.entity.Entity;
 import mir.generator.Generator;
@@ -101,8 +90,8 @@ import mircoders.search.ContentSearchTerm;
 import mircoders.search.ImagesSearchTerm;
 import mircoders.search.KeywordSearchTerm;
 import mircoders.search.TextSearchTerm;
-import mircoders.search.TopicSearchTerm;
 import mircoders.search.TopicMatrixSearchTerm;
+import mircoders.search.TopicSearchTerm;
 import mircoders.search.UnIndexedSearchTerm;
 import mircoders.search.VideoSearchTerm;
 import mircoders.storage.DatabaseComment;
@@ -113,6 +102,18 @@ import mircoders.storage.DatabaseImages;
 import mircoders.storage.DatabaseLanguage;
 import mircoders.storage.DatabaseTopics;
 
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.queryParser.QueryParser;
+import org.apache.lucene.search.Hits;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Searcher;
+import org.apache.struts.util.MessageResources;
+
 /*
  *  ServletModuleOpenIndy -
  *   is the open-access-servlet, which is responsible for
@@ -120,7 +121,7 @@ import mircoders.storage.DatabaseTopics;
  *    open-postings to the newswire
  *
  * @author mir-coders group
- * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.7 2003/09/03 17:49:40 zapata Exp $
+ * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.8 2003/10/23 14:55:25 rk Exp $
  *
  */
 
index 0940696..01d9075 100755 (executable)
@@ -32,10 +32,9 @@ package mircoders.servlet;
 
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseOther;
-import mircoders.global.*;
 
 /**
  *
index e1e7940..51427b5 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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 mircoders.servlet;\r
-\r
-import java.io.PrintWriter;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import org.apache.struts.util.MessageResources;\r
-\r
-import mir.generator.Generator;\r
-import mir.log.LoggerWrapper;\r
-import mir.producer.ProducerFactory;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.ResourceBundleGeneratorFunction;\r
-import mircoders.global.MirGlobal;\r
-\r
-public class ServletModuleProducer extends ServletModule\r
-{\r
-  private static ServletModuleProducer instance = new ServletModuleProducer();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  Object comments;\r
-  Map generationData;\r
-  Generator generator;\r
-  int totalNrComments;\r
-  List producersData;\r
-\r
-  void generateResponse(String aGeneratorIdentifier, PrintWriter aWriter, Map aResponseData, Locale aLocale) {\r
-    try {\r
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGeneratorIdentifier);\r
-      MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(aResponseData);\r
-      aResponseData.put( "lang", new ResourceBundleGeneratorFunction( aLocale, MessageResources.getMessageResources("bundles.admin")));\r
-      generator.generate(aWriter, aResponseData, logger);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  private ServletModuleProducer() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Producer");\r
-    defaultAction="showProducerQueueStatus";\r
-  }\r
-\r
-  public void showMessage(HttpServletRequest aRequest, HttpServletResponse aResponse, String aMessage, String anArgument1, String anArgument2) {\r
-    Map responseData;\r
-    try {\r
-      responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      responseData.put("message", aMessage);\r
-      responseData.put("argument1", anArgument1);\r
-      responseData.put("argument2", anArgument2);\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "infomessage.template");\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    Object comments;\r
-    Map generationData;\r
-    Generator generator;\r
-    int totalNrComments;\r
-    List producersData;\r
-\r
-    try {\r
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");\r
-\r
-      generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus");\r
-\r
-      producersData = new Vector();\r
-      Iterator i = MirGlobal.localizer().producers().factories().iterator();\r
-      while (i.hasNext()) {\r
-        ProducerFactory factory = (ProducerFactory) i.next();\r
-\r
-        List producerVerbs = new Vector();\r
-        Iterator j = factory.verbs();\r
-        while (j.hasNext()) {\r
-          Map verbData = new HashMap();\r
-          ProducerFactory.ProducerVerb verb = (ProducerFactory.ProducerVerb) j.next();\r
-          verbData.put("name", verb.getName());\r
-          verbData.put("description", verb.getDescription());\r
-\r
-          producerVerbs.add(verbData);\r
-        }\r
-\r
-        Map producerData = new HashMap();\r
-        producerData.put("name", factory.getName());\r
-        producerData.put("verbs", producerVerbs);\r
-\r
-        producersData.add(producerData);\r
-      }\r
-      generationData.put("producers", producersData);\r
-\r
-      generationData.put("queue", MirGlobal.producerEngine().getQueueStatus());\r
-      generator.generate(aResponse.getWriter(), generationData, logger);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    /*\r
-     * This method will only be called by external scripts (e.g. from cron jobs).\r
-     * The output therefore is very simple.\r
-     */\r
-\r
-    try {\r
-      PrintWriter out = aResponse.getWriter();\r
-\r
-      if (aRequest.getParameter("producer")!=null) {\r
-        String producerParam = aRequest.getParameter("producer");\r
-        String verbParam = aRequest.getParameter("verb");\r
-\r
-        MirGlobal.producerEngine().addJob(producerParam, verbParam);\r
-        out.println("job added");\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void producerecipe(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      String recipe = aRequest.getParameter("recipe");\r
-      MirGlobal.localizer().producers().produceRecipe(recipe);\r
-      showMessage(aRequest, aResponse, "recipeAddedToQueue", recipe, "");\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void enqueue(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
-    try {\r
-      if (aRequest.getParameter("producer")!=null) {\r
-        String producerParam = aRequest.getParameter("producer");\r
-        String verbParam = aRequest.getParameter("verb");\r
-\r
-        MirGlobal.producerEngine().addJob(producerParam, verbParam);\r
-\r
-        ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void cancel(HttpServletRequest aRequest, HttpServletResponse aResponse)  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-      if (requestParser.getParameter("cancelall") != null) {\r
-        MirGlobal.producerEngine().cancelAllJobs();\r
-      }\r
-      else {\r
-        List jobs = new Vector(requestParser.getParameterList("jobid"));\r
-\r
-        MirGlobal.producerEngine().cancelJobs(jobs);\r
-      }\r
-      ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-}\r
+/*
+ * 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 mircoders.servlet;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+
+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 mir.util.ResourceBundleGeneratorFunction;
+import mircoders.global.MirGlobal;
+
+import org.apache.struts.util.MessageResources;
+
+public class ServletModuleProducer extends ServletModule
+{
+  private static ServletModuleProducer instance = new ServletModuleProducer();
+  public static ServletModule getInstance() { return instance; }
+
+  Object comments;
+  Map generationData;
+  Generator generator;
+  int totalNrComments;
+  List producersData;
+
+  void generateResponse(String aGeneratorIdentifier, PrintWriter aWriter, Map aResponseData, Locale aLocale) {
+    try {
+      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGeneratorIdentifier);
+      MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(aResponseData);
+      aResponseData.put( "lang", new ResourceBundleGeneratorFunction( aLocale, MessageResources.getMessageResources("bundles.admin")));
+      generator.generate(aWriter, aResponseData, logger);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  private ServletModuleProducer() {
+    super();
+    logger = new LoggerWrapper("ServletModule.Producer");
+    defaultAction="showProducerQueueStatus";
+  }
+
+  public void showMessage(HttpServletRequest aRequest, HttpServletResponse aResponse, String aMessage, String anArgument1, String anArgument2) {
+    Map responseData;
+    try {
+      responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      responseData.put("message", aMessage);
+      responseData.put("argument1", anArgument1);
+      responseData.put("argument2", anArgument2);
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "infomessage.template");
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    Object comments;
+    Map generationData;
+    Generator generator;
+    int totalNrComments;
+    List producersData;
+
+    try {
+      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");
+
+      generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus");
+
+      producersData = new Vector();
+      Iterator i = MirGlobal.localizer().producers().factories().iterator();
+      while (i.hasNext()) {
+        ProducerFactory factory = (ProducerFactory) i.next();
+
+        List producerVerbs = new Vector();
+        Iterator j = factory.verbs();
+        while (j.hasNext()) {
+          Map verbData = new HashMap();
+          ProducerFactory.ProducerVerb verb = (ProducerFactory.ProducerVerb) j.next();
+          verbData.put("name", verb.getName());
+          verbData.put("description", verb.getDescription());
+
+          producerVerbs.add(verbData);
+        }
+
+        Map producerData = new HashMap();
+        producerData.put("name", factory.getName());
+        producerData.put("verbs", producerVerbs);
+
+        producersData.add(producerData);
+      }
+      generationData.put("producers", producersData);
+
+      generationData.put("queue", MirGlobal.producerEngine().getQueueStatus());
+      generator.generate(aResponse.getWriter(), generationData, logger);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    /*
+     * This method will only be called by external scripts (e.g. from cron jobs).
+     * The output therefore is very simple.
+     */
+
+    try {
+      PrintWriter out = aResponse.getWriter();
+
+      if (aRequest.getParameter("producer")!=null) {
+        String producerParam = aRequest.getParameter("producer");
+        String verbParam = aRequest.getParameter("verb");
+
+        MirGlobal.producerEngine().addJob(producerParam, verbParam);
+        out.println("job added");
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void producerecipe(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      String recipe = aRequest.getParameter("recipe");
+      MirGlobal.localizer().producers().produceRecipe(recipe);
+      showMessage(aRequest, aResponse, "recipeAddedToQueue", recipe, "");
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void enqueue(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+    try {
+      if (aRequest.getParameter("producer")!=null) {
+        String producerParam = aRequest.getParameter("producer");
+        String verbParam = aRequest.getParameter("verb");
+
+        MirGlobal.producerEngine().addJob(producerParam, verbParam);
+
+        ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");
+      }
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void cancel(HttpServletRequest aRequest, HttpServletResponse aResponse)  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      if (requestParser.getParameter("cancelall") != null) {
+        MirGlobal.producerEngine().cancelAllJobs();
+      }
+      else {
+        List jobs = new Vector(requestParser.getParameterList("jobid"));
+
+        MirGlobal.producerEngine().cancelJobs(jobs);
+      }
+      ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+}
index 63fdd7c..441f33b 100755 (executable)
@@ -32,10 +32,9 @@ package mircoders.servlet;
 
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleTopics;
 import mircoders.storage.DatabaseTopics;
-import mircoders.global.*;
 
 /**
  *
index 7959079..db06146 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.servlet;\r
-\r
-import java.io.InputStream;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-import javax.servlet.ServletContext;\r
-import javax.servlet.ServletOutputStream;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import org.apache.commons.fileupload.FileItem;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.Entity;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaHelper;\r
-import mir.media.MirMedia;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.session.UploadedFile;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.ExceptionFunctions;\r
-import mir.util.HTTPParsedRequest;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.JDBCStringRoutines;\r
-import mir.util.SQLQueryBuilder;\r
-import mir.util.URLBuilder;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUploadedMedia;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.media.MediaUploadProcessor;\r
-import mircoders.module.ModuleMediaType;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseContent;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author the mir coders\r
- * @version 1.0\r
- */\r
-\r
-public abstract class ServletModuleUploadedMedia extends ServletModule {\r
-  protected String moduleName = "UploadedMedia";\r
-\r
-  public static ServletModule getInstance() {\r
-    return null;\r
-  }\r
-\r
-  public ServletModuleUploadedMedia() {\r
-    super();\r
-\r
-    definition = "uploadedMedia";\r
-    logger = new LoggerWrapper("ServletModule.UploadedMedia");\r
-    try {\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-          throws ServletModuleExc, ServletModuleUserExc {\r
-    try {\r
-      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,\r
-          configuration.getString("Mir.DefaultEncoding"),\r
-          configuration.getInt("MaxMediaUploadSize")*1024,\r
-          configuration.getString("TempDir"));\r
-\r
-      Map mediaValues = new HashMap();\r
-\r
-      mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
-\r
-      Iterator i = mainModule.getStorageObject().getFields().iterator();\r
-      while (i.hasNext()) {\r
-        String field = (String) i.next();\r
-        String value = parsedRequest.getParameter(field);\r
-        if (value!=null)\r
-          mediaValues.put(field, value);\r
-      }\r
-\r
-      List mediaList = new Vector();\r
-\r
-      i = parsedRequest.getFiles().iterator();\r
-      while (i.hasNext()) {\r
-        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());\r
-\r
-        String suffix = file.getFieldName().substring(5);\r
-        mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));\r
-\r
-        mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));\r
-      }\r
-\r
-      String articleid = parsedRequest.getParameter("articleid");\r
-      String commentid = parsedRequest.getParameter("commentid");\r
-\r
-      if (articleid!=null) {\r
-        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);\r
-\r
-        i=mediaList.iterator();\r
-\r
-        while (i.hasNext()) {\r
-          String id = ((EntityUploadedMedia) i.next()).getId();\r
-\r
-          entContent.attach(id);\r
-          logAdminUsage(aRequest, id, "object attached to article " + articleid);\r
-        }\r
-\r
-        ((ServletModuleContent) ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid);\r
-\r
-\r
-        return;\r
-      }\r
-\r
-      if (commentid!=null) {\r
-        EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);\r
-\r
-        i=mediaList.iterator();\r
-\r
-        while (i.hasNext()) {\r
-          String id = ((EntityUploadedMedia) i.next()).getId();\r
-\r
-          comment.attach(id);\r
-\r
-          logAdminUsage(aRequest, id, "object attached to comment " + commentid);\r
-        }\r
-\r
-        ((ServletModuleComment) ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid);\r
-\r
-        return;\r
-      }\r
-\r
-      logAdminUsage(aRequest, "", mediaList.size() + " objects added");\r
-\r
-      returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null);\r
-    }\r
-    catch (Throwable t) {\r
-      Throwable cause = ExceptionFunctions.traceCauseException(t);\r
-\r
-      if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {\r
-        throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});\r
-      }\r
-      throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);\r
-    }\r
-  }\r
-\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-\r
-    try {\r
-      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,\r
-          configuration.getString("Mir.DefaultEncoding"),\r
-          configuration.getInt("MaxMediaUploadSize")*1024,\r
-          configuration.getString("TempDir"));\r
-      Map mediaValues = new HashMap();\r
-\r
-      Iterator i = mainModule.getStorageObject().getFields().iterator();\r
-      while (i.hasNext()) {\r
-        String field = (String) i.next();\r
-        String value = parsedRequest.getParameter(field);\r
-        if (value!=null)\r
-          mediaValues.put(field, value);\r
-      }\r
-\r
-      mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
-      mediaValues.put("is_produced", "0");\r
-      if (!mediaValues.containsKey("is_published"))\r
-        mediaValues.put("is_published", "0");\r
-\r
-      String id = mainModule.set(mediaValues);\r
-      logger.debug("update: media ID = " + id);\r
-      logAdminUsage(aRequest, id, "object modified");\r
-\r
-      editUploadedMediaObject(id, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);\r
-    }\r
-\r
-  }\r
-\r
-  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-                                      Object aList, int aFrom, int aTo, int aCount,\r
-                                      String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc {\r
-\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      responseData.put("searchfield", requestParser.getParameterWithDefault("searchfield", ""));\r
-      responseData.put("searchtext", requestParser.getParameterWithDefault("searchtext", ""));\r
-      responseData.put("searchispublished", requestParser.getParameterWithDefault("searchispublished", ""));\r
-      responseData.put("searchmediafolder", requestParser.getParameterWithDefault("searchmediafolder", ""));\r
-      responseData.put("articleid", requestParser.getParameter("articleid"));\r
-      responseData.put("commentid", requestParser.getParameter("commentid"));\r
-\r
-      responseData.put("thisurl", aThisUrl);\r
-      responseData.put("nexturl", aNextUrl);\r
-      responseData.put("prevurl", aPreviousUrl);\r
-\r
-      responseData.put("from", Integer.toString(aFrom));\r
-      responseData.put("count", Integer.toString(aCount));\r
-      responseData.put("to", Integer.toString(aTo));\r
-\r
-      responseData.put("medialist", aList);\r
-\r
-      addExtraData(responseData);\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-                                      String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
-\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    EntityAdapterModel model;\r
-    String nextPageUrl = null;\r
-    String previousPageUrl = null;\r
-    String thisUrl = null;\r
-\r
-    int count;\r
-\r
-    try {\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-\r
-      Object mediaList =\r
-          new CachingRewindableIterator(\r
-          new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
-                   model, definition, nrEntitiesPerListPage, anOffset)\r
-          );\r
-\r
-      count = mainModule.getSize(aWhereClause);\r
-\r
-      urlBuilder.setValue("module", moduleName);\r
-      urlBuilder.setValue("do", "list");\r
-      urlBuilder.setValue("where", aWhereClause);\r
-      urlBuilder.setValue("order", anOrderByClause);\r
-\r
-      urlBuilder.setValue("articleid", requestParser.getParameter("articleid"));\r
-      urlBuilder.setValue("commentid", requestParser.getParameter("commentid"));\r
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
-      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
-      urlBuilder.setValue("searchmediafolder", requestParser.getParameter("searchmediafolder"));\r
-      urlBuilder.setValue("where", aWhereClause);\r
-      urlBuilder.setValue("order", anOrderByClause);\r
-\r
-      urlBuilder.setValue("offset", anOffset);\r
-      thisUrl = urlBuilder.getQuery();\r
-\r
-      if (count >= anOffset + nrEntitiesPerListPage) {\r
-        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
-        nextPageUrl = urlBuilder.getQuery();\r
-      }\r
-\r
-      if (anOffset > 0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
-        previousPageUrl = urlBuilder.getQuery();\r
-      }\r
-\r
-      returnUploadedMediaList(aRequest, aResponse, mediaList,\r
-              anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl,\r
-              nextPageUrl, previousPageUrl);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
-\r
-    String queryField = "";\r
-    String searchField = requestParser.getParameter("searchfield");\r
-    String searchText = requestParser.getParameter("searchtext");\r
-    String searchIsPublished = requestParser.getParameter("searchispublished");\r
-    String searchMediaFolder = requestParser.getParameter("searchmediafolder");\r
-\r
-    queryBuilder.appendDescendingOrder("webdb_create");\r
-\r
-    if (searchIsPublished!=null)\r
-      if (searchIsPublished.equals("0")) {\r
-        queryBuilder.appendAndCondition("is_published='f'");\r
-      }\r
-      else if (searchIsPublished.equals("1")) {\r
-        queryBuilder.appendAndCondition("is_published='t'");\r
-      }\r
-\r
-    if (searchField!=null && searchText!=null && searchText.length()>0) {\r
-        queryBuilder.appendAndCondition(\r
-          "lower(" + searchField + ") like " +\r
-          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");\r
-    }\r
-\r
-    if (searchMediaFolder!=null && searchMediaFolder.length()>0) {\r
-      queryBuilder.appendAndCondition("to_media_folder="+Integer.parseInt(searchMediaFolder));\r
-    }\r
-\r
-    returnUploadedMediaList(aRequest, aResponse,\r
-            queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), requestParser.getIntegerWithDefault("offset", 0));\r
-  }\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    returnUploadedMediaList(aRequest, aResponse,\r
-       requestParser.getParameterWithDefault("where", ""),\r
-       requestParser.getParameterWithDefault("order", "webdb_create desc"),\r
-       requestParser.getIntegerWithDefault("offset", 0));\r
-  }\r
-\r
-\r
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
-\r
-      int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1);\r
-      int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);\r
-\r
-      List fields = mainModule.getStorageObject().getFields();\r
-      Map media = new HashMap();\r
-      Iterator i = fields.iterator();\r
-      while (i.hasNext()) {\r
-        media.put(i.next(), null);\r
-      }\r
-      media.put("to_media_folder", new Integer(7));\r
-      responseData.put("uploadedmedia", media);\r
-\r
-      responseData.put("new", Boolean.TRUE);\r
-      responseData.put("articleid", requestParser.getParameter("articleid"));\r
-      responseData.put("commentid", requestParser.getParameter("commentid"));\r
-      responseData.put("returnurl", null);\r
-\r
-      if (nrMedia<=0)\r
-        nrMedia=1;\r
-      if (nrMedia>maxNrMedia)\r
-        nrMedia=maxNrMedia;\r
-\r
-      List mediaFields = new Vector();\r
-      for (int j=0; j<nrMedia; j++)\r
-        mediaFields.add(new Integer(j));\r
-\r
-      responseData.put("nrmedia", new Integer(nrMedia));\r
-      responseData.put("mediafields", mediaFields);\r
-\r
-      responseData.put("edittemplate", editGenerator);\r
-      responseData.put("module", moduleName);\r
-\r
-      addExtraData(responseData);\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");\r
-    }\r
-    catch (Exception e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    editUploadedMediaObject(aRequest.getParameter("id"), aRequest, aResponse);\r
-  }\r
-\r
-  private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    if (idParam != null && !idParam.equals("")) {\r
-      try {\r
-        Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
-        EntityAdapter object =\r
-            model.makeEntityAdapter(definition, mainModule.getById(idParam));\r
-        responseData.put("uploadedmedia", object);\r
-        responseData.put("new", Boolean.FALSE);\r
-        responseData.put("articleid", null);\r
-        responseData.put("commentid", null);\r
-        responseData.put("returnurl", null);\r
-        responseData.put("thisurl", null);\r
-\r
-        responseData.put("edittemplate", editGenerator);\r
-        responseData.put("module", moduleName);\r
-\r
-        addExtraData(responseData);\r
-\r
-        ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");\r
-      }\r
-      catch (Throwable e) {\r
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-    else {\r
-      throw new ServletModuleExc("ServletmoduleUploadedMedia :: editUploadedMediaObject without id");\r
-    }\r
-  }\r
-\r
-  public void getMedia(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
-    String idParam = aRequest.getParameter("id");\r
-    if (idParam!=null && !idParam.equals("")) {\r
-      try {\r
-        EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);\r
-        Entity mediaType = ent.getMediaType();\r
-        MirMedia mediaHandler;\r
-\r
-        ServletContext ctx = MirPropertiesConfiguration.getContext();\r
-        String fName = ent.getId()+"."+mediaType.getValue("name");\r
-\r
-        mediaHandler = MediaHelper.getHandler(mediaType);\r
-        InputStream in = mediaHandler.getMedia(ent, mediaType);\r
-\r
-        aResponse.setContentType(ctx.getMimeType(fName));\r
-        //important that before calling this aResponse.getWriter was not called first\r
-        ServletOutputStream out = aResponse.getOutputStream();\r
-\r
-        int read ;\r
-        byte[] buf = new byte[8 * 1024];\r
-        while((read = in.read(buf)) != -1) {\r
-          out.write(buf, 0, read);\r
-        }\r
-        in.close();\r
-        out.close();\r
-      }\r
-      catch (Throwable e) {\r
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-    else logger.error("id not specified.");\r
-    // no exception allowed\r
-  }\r
-\r
-  public void getIcon(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-    if (idParam!=null && !idParam.equals("")) {\r
-      try {\r
-        EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);\r
-        Entity mediaType = ent.getMediaType();\r
-        MirMedia mediaHandler;\r
-\r
-        mediaHandler = MediaHelper.getHandler(mediaType);\r
-        InputStream in = mediaHandler.getIcon(ent);\r
-\r
-        if (in==null)\r
-          throw new ServletModuleExc("no icon available");\r
-\r
-        aResponse.setContentType(mediaHandler.getIconMimeType(ent, mediaType));\r
-        //important that before calling this aResponse.getWriter was not called first\r
-        ServletOutputStream out = aResponse.getOutputStream();\r
-\r
-        int read ;\r
-        byte[] buf = new byte[8 * 1024];\r
-        while((read = in.read(buf)) != -1) {\r
-          out.write(buf, 0, read);\r
-        }\r
-        in.close();\r
-        out.close();\r
-      }\r
-\r
-      catch (Throwable e) {\r
-        logger.error("getIcon: " + e.toString());\r
-      }\r
-    }\r
-    else logger.error("getIcon: id not specified.");\r
-    // no exception allowed\r
-  }\r
-\r
-  protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      aTarget.put("mediafolders",\r
-                  new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "mediaFolder"));\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-    if (idParam!=null && !idParam.equals("")) {\r
-      try {\r
-        EntityUploadedMedia entity = (EntityUploadedMedia) mainModule.getById(idParam);\r
-\r
-        ServletModuleContent.getInstance().returnList(\r
-            aRequest,\r
-            aResponse,\r
-            "exists (select * from content_x_media where content_id=content.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletModuleFailure(t);\r
-      }\r
-    }\r
-    else logger.error("showarticles: id not specified.");\r
-  }\r
-\r
-  public void showcomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-    if (idParam!=null && !idParam.equals("")) {\r
-      try {\r
-        EntityUploadedMedia entity = (EntityUploadedMedia) mainModule.getById(idParam);\r
-\r
-        ServletModuleComment.getInstance().returnList(\r
-            aRequest,\r
-            aResponse,\r
-            "exists (select * from comment_x_media where comment_id=comment.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletModuleFailure(t);\r
-      }\r
-    }\r
-    else logger.error("editObjects: id not specified.");\r
-  }\r
-\r
+/*
+ * 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 mircoders.servlet;
+
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.Entity;
+import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.media.MediaHelper;
+import mir.media.MirMedia;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.session.UploadedFile;
+import mir.util.CachingRewindableIterator;
+import mir.util.ExceptionFunctions;
+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;
+import mircoders.global.MirGlobal;
+import mircoders.media.MediaUploadProcessor;
+import mircoders.module.ModuleMediaType;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseContent;
+
+import org.apache.commons.fileupload.FileItem;
+
+/**
+ *
+ * <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();
+
+    definition = "uploadedMedia";
+    logger = new LoggerWrapper("ServletModule.UploadedMedia");
+    try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
+          throws ServletModuleExc, ServletModuleUserExc {
+    try {
+      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
+          configuration.getString("Mir.DefaultEncoding"),
+          configuration.getInt("MaxMediaUploadSize")*1024,
+          configuration.getString("TempDir"));
+
+      Map mediaValues = new HashMap();
+
+      mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
+
+      Iterator i = mainModule.getStorageObject().getFields().iterator();
+      while (i.hasNext()) {
+        String field = (String) i.next();
+        String value = parsedRequest.getParameter(field);
+        if (value!=null)
+          mediaValues.put(field, value);
+      }
+
+      List mediaList = new Vector();
+
+      i = parsedRequest.getFiles().iterator();
+      while (i.hasNext()) {
+        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
+
+        String suffix = file.getFieldName().substring(5);
+        mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
+
+        mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
+      }
+
+      String articleid = parsedRequest.getParameter("articleid");
+      String commentid = parsedRequest.getParameter("commentid");
+
+      if (articleid!=null) {
+        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
+
+        i=mediaList.iterator();
+
+        while (i.hasNext()) {
+          String id = ((EntityUploadedMedia) i.next()).getId();
+
+          entContent.attach(id);
+          logAdminUsage(aRequest, id, "object attached to article " + articleid);
+        }
+
+        ((ServletModuleContent) ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid);
+
+
+        return;
+      }
+
+      if (commentid!=null) {
+        EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);
+
+        i=mediaList.iterator();
+
+        while (i.hasNext()) {
+          String id = ((EntityUploadedMedia) i.next()).getId();
+
+          comment.attach(id);
+
+          logAdminUsage(aRequest, id, "object attached to comment " + commentid);
+        }
+
+        ((ServletModuleComment) ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid);
+
+        return;
+      }
+
+      logAdminUsage(aRequest, "", mediaList.size() + " objects added");
+
+      returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null);
+    }
+    catch (Throwable t) {
+      Throwable cause = ExceptionFunctions.traceCauseException(t);
+
+      if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
+        throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});
+      }
+      throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);
+    }
+  }
+
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+
+    try {
+      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
+          configuration.getString("Mir.DefaultEncoding"),
+          configuration.getInt("MaxMediaUploadSize")*1024,
+          configuration.getString("TempDir"));
+      Map mediaValues = new HashMap();
+
+      Iterator i = mainModule.getStorageObject().getFields().iterator();
+      while (i.hasNext()) {
+        String field = (String) i.next();
+        String value = parsedRequest.getParameter(field);
+        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"))
+        mediaValues.put("is_published", "0");
+
+      String id = mainModule.set(mediaValues);
+      logger.debug("update: media ID = " + id);
+      logAdminUsage(aRequest, id, "object modified");
+
+      editUploadedMediaObject(id, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);
+    }
+
+  }
+
+  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+                                      Object aList, int aFrom, int aTo, int aCount,
+                                      String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc {
+
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
+
+      responseData.put("searchfield", requestParser.getParameterWithDefault("searchfield", ""));
+      responseData.put("searchtext", requestParser.getParameterWithDefault("searchtext", ""));
+      responseData.put("searchispublished", requestParser.getParameterWithDefault("searchispublished", ""));
+      responseData.put("searchmediafolder", requestParser.getParameterWithDefault("searchmediafolder", ""));
+      responseData.put("articleid", requestParser.getParameter("articleid"));
+      responseData.put("commentid", requestParser.getParameter("commentid"));
+
+      responseData.put("thisurl", aThisUrl);
+      responseData.put("nexturl", aNextUrl);
+      responseData.put("prevurl", aPreviousUrl);
+
+      responseData.put("from", Integer.toString(aFrom));
+      responseData.put("count", Integer.toString(aCount));
+      responseData.put("to", Integer.toString(aTo));
+
+      responseData.put("medialist", aList);
+
+      addExtraData(responseData);
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+                                      String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
+
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+    EntityAdapterModel model;
+    String nextPageUrl = null;
+    String previousPageUrl = null;
+    String thisUrl = null;
+
+    int count;
+
+    try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+
+      Object mediaList =
+          new CachingRewindableIterator(
+          new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage,
+                   model, definition, nrEntitiesPerListPage, anOffset)
+          );
+
+      count = mainModule.getSize(aWhereClause);
+
+      urlBuilder.setValue("module", moduleName);
+      urlBuilder.setValue("do", "list");
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+      urlBuilder.setValue("articleid", requestParser.getParameter("articleid"));
+      urlBuilder.setValue("commentid", requestParser.getParameter("commentid"));
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
+      urlBuilder.setValue("searchmediafolder", requestParser.getParameter("searchmediafolder"));
+      urlBuilder.setValue("where", aWhereClause);
+      urlBuilder.setValue("order", anOrderByClause);
+
+      urlBuilder.setValue("offset", anOffset);
+      thisUrl = urlBuilder.getQuery();
+
+      if (count >= anOffset + nrEntitiesPerListPage) {
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
+        nextPageUrl = urlBuilder.getQuery();
+      }
+
+      if (anOffset > 0) {
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
+        previousPageUrl = urlBuilder.getQuery();
+      }
+
+      returnUploadedMediaList(aRequest, aResponse, mediaList,
+              anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl,
+              nextPageUrl, previousPageUrl);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
+
+    String queryField = "";
+    String searchField = requestParser.getParameter("searchfield");
+    String searchText = requestParser.getParameter("searchtext");
+    String searchIsPublished = requestParser.getParameter("searchispublished");
+    String searchMediaFolder = requestParser.getParameter("searchmediafolder");
+
+    queryBuilder.appendDescendingOrder("webdb_create");
+
+    if (searchIsPublished!=null)
+      if (searchIsPublished.equals("0")) {
+        queryBuilder.appendAndCondition("is_published='f'");
+      }
+      else if (searchIsPublished.equals("1")) {
+        queryBuilder.appendAndCondition("is_published='t'");
+      }
+
+    if (searchField!=null && searchText!=null && searchText.length()>0) {
+        queryBuilder.appendAndCondition(
+          "lower(" + searchField + ") like " +
+          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");
+    }
+
+    if (searchMediaFolder!=null && searchMediaFolder.length()>0) {
+      queryBuilder.appendAndCondition("to_media_folder="+Integer.parseInt(searchMediaFolder));
+    }
+
+    returnUploadedMediaList(aRequest, aResponse,
+            queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), requestParser.getIntegerWithDefault("offset", 0));
+  }
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    returnUploadedMediaList(aRequest, aResponse,
+       requestParser.getParameterWithDefault("where", ""),
+       requestParser.getParameterWithDefault("order", "webdb_create desc"),
+       requestParser.getIntegerWithDefault("offset", 0));
+  }
+
+
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      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);
+
+      List fields = mainModule.getStorageObject().getFields();
+      Map media = new HashMap();
+      Iterator i = fields.iterator();
+      while (i.hasNext()) {
+        media.put(i.next(), null);
+      }
+      media.put("to_media_folder", new Integer(7));
+      responseData.put("uploadedmedia", media);
+
+      responseData.put("new", Boolean.TRUE);
+      responseData.put("articleid", requestParser.getParameter("articleid"));
+      responseData.put("commentid", requestParser.getParameter("commentid"));
+      responseData.put("returnurl", null);
+
+      if (nrMedia<=0)
+        nrMedia=1;
+      if (nrMedia>maxNrMedia)
+        nrMedia=maxNrMedia;
+
+      List mediaFields = new Vector();
+      for (int j=0; j<nrMedia; j++)
+        mediaFields.add(new Integer(j));
+
+      responseData.put("nrmedia", new Integer(nrMedia));
+      responseData.put("mediafields", mediaFields);
+
+      responseData.put("edittemplate", editGenerator);
+      responseData.put("module", moduleName);
+
+      addExtraData(responseData);
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");
+    }
+    catch (Exception e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    editUploadedMediaObject(aRequest.getParameter("id"), aRequest, aResponse);
+  }
+
+  private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    if (idParam != null && !idParam.equals("")) {
+      try {
+        Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
+        EntityAdapter object =
+            model.makeEntityAdapter(definition, mainModule.getById(idParam));
+        responseData.put("uploadedmedia", object);
+        responseData.put("new", Boolean.FALSE);
+        responseData.put("articleid", null);
+        responseData.put("commentid", null);
+        responseData.put("returnurl", null);
+        responseData.put("thisurl", null);
+
+        responseData.put("edittemplate", editGenerator);
+        responseData.put("module", moduleName);
+
+        addExtraData(responseData);
+
+        ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");
+      }
+      catch (Throwable e) {
+        throw new ServletModuleFailure(e);
+      }
+    }
+    else {
+      throw new ServletModuleExc("ServletmoduleUploadedMedia :: editUploadedMediaObject without id");
+    }
+  }
+
+  public void getMedia(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    String idParam = aRequest.getParameter("id");
+    if (idParam!=null && !idParam.equals("")) {
+      try {
+        EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);
+        Entity mediaType = ent.getMediaType();
+        MirMedia mediaHandler;
+
+        ServletContext ctx = MirPropertiesConfiguration.getContext();
+        String fName = ent.getId()+"."+mediaType.getValue("name");
+
+        mediaHandler = MediaHelper.getHandler(mediaType);
+        InputStream in = mediaHandler.getMedia(ent, mediaType);
+
+        aResponse.setContentType(ctx.getMimeType(fName));
+        //important that before calling this aResponse.getWriter was not called first
+        ServletOutputStream out = aResponse.getOutputStream();
+
+        int read ;
+        byte[] buf = new byte[8 * 1024];
+        while((read = in.read(buf)) != -1) {
+          out.write(buf, 0, read);
+        }
+        in.close();
+        out.close();
+      }
+      catch (Throwable e) {
+        throw new ServletModuleFailure(e);
+      }
+    }
+    else logger.error("id not specified.");
+    // no exception allowed
+  }
+
+  public void getIcon(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+    if (idParam!=null && !idParam.equals("")) {
+      try {
+        EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);
+        Entity mediaType = ent.getMediaType();
+        MirMedia mediaHandler;
+
+        mediaHandler = MediaHelper.getHandler(mediaType);
+        InputStream in = mediaHandler.getIcon(ent);
+
+        if (in==null)
+          throw new ServletModuleExc("no icon available");
+
+        aResponse.setContentType(mediaHandler.getIconMimeType(ent, mediaType));
+        //important that before calling this aResponse.getWriter was not called first
+        ServletOutputStream out = aResponse.getOutputStream();
+
+        int read ;
+        byte[] buf = new byte[8 * 1024];
+        while((read = in.read(buf)) != -1) {
+          out.write(buf, 0, read);
+        }
+        in.close();
+        out.close();
+      }
+
+      catch (Throwable e) {
+        logger.error("getIcon: " + e.toString());
+      }
+    }
+    else logger.error("getIcon: id not specified.");
+    // no exception allowed
+  }
+
+  protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure {
+    try {
+      aTarget.put("mediafolders",
+                  new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "mediaFolder"));
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+    if (idParam!=null && !idParam.equals("")) {
+      try {
+        EntityUploadedMedia entity = (EntityUploadedMedia) mainModule.getById(idParam);
+
+        ServletModuleContent.getInstance().returnList(
+            aRequest,
+            aResponse,
+            "exists (select * from content_x_media where content_id=content.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);
+      }
+      catch (Throwable t) {
+        throw new ServletModuleFailure(t);
+      }
+    }
+    else logger.error("showarticles: id not specified.");
+  }
+
+  public void showcomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+    if (idParam!=null && !idParam.equals("")) {
+      try {
+        EntityUploadedMedia entity = (EntityUploadedMedia) mainModule.getById(idParam);
+
+        ServletModuleComment.getInstance().returnList(
+            aRequest,
+            aResponse,
+            "exists (select * from comment_x_media where comment_id=comment.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);
+      }
+      catch (Throwable t) {
+        throw new ServletModuleFailure(t);
+      }
+    }
+    else logger.error("editObjects: id not specified.");
+  }
+
 }
\ No newline at end of file
index 6736c92..51279ec 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.servlet;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.storage.StorageObjectFailure;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.URLBuilder;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleUsers;\r
-import mircoders.storage.DatabaseUsers;\r
-import mircoders.global.*;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class ServletModuleUsers extends ServletModule\r
-{\r
-  private static ServletModuleUsers instance = new ServletModuleUsers();\r
-  public static ServletModule getInstance() { return instance; }\r
-  protected ModuleUsers usersModule;\r
-\r
-  private ServletModuleUsers() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Users");\r
-\r
-    try {\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-      definition = "user";\r
-      usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
-      mainModule = usersModule;\r
-    }\r
-    catch (Throwable e) {\r
-      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");\r
-\r
-    try {\r
-      EntityUsers user = (EntityUsers) mainModule.getById(idParam);\r
-      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);\r
-\r
-      showUser(idParam, false, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc\r
-  {\r
-    try {\r
-      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));\r
-\r
-      showUser(null, false, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public String validatePassword(EntityUsers aUser, HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    if ( (aRequestParser.getParameter("newpassword") != null &&\r
-          aRequestParser.getParameter("newpassword").length() > 0) ||\r
-        (aRequestParser.getParameter("newpassword2") != null &&\r
-         aRequestParser.getParameter("newpassword2").length() > 0)\r
-        ) {\r
-      String newPassword = aRequestParser.getParameterWithDefault("newpassword", "");\r
-      String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", "");\r
-      String oldPassword = aRequestParser.getParameterWithDefault("oldpassword", "");\r
-\r
-      try {\r
-        if (!usersModule.checkUserPassword(aUser, oldPassword)) {\r
-          throw new ServletModuleUserExc("user.error.incorrectpassword", new String[] {});\r
-        }\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletModuleFailure(t);\r
-      }\r
-\r
-\r
-      if (newPassword.length() == 0 || newPassword2.length() == 0) {\r
-        throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {});\r
-      }\r
-\r
-      if (!newPassword.equals(newPassword2)) {\r
-        throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {});\r
-      }\r
-\r
-      return newPassword;\r
-    }\r
-    else\r
-      return null;\r
-  }\r
-\r
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    try {\r
-      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));\r
-\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-\r
-      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
-      if (newPassword!=null)\r
-        withValues.put("password", newPassword);\r
-      else\r
-        throw new ServletModuleUserExc("user.error.missingpassword", new String[] {});\r
-\r
-      String id = mainModule.add(withValues);\r
-\r
-      logAdminUsage(aRequest, id, "object added");\r
-\r
-      if (requestParser.hasParameter("returnurl"))\r
-        redirect(aResponse, requestParser.getParameter("returnurl"));\r
-      else\r
-        list(aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      String id = requestParser.getParameter("id");\r
-      EntityUsers user = (EntityUsers) mainModule.getById(id);\r
-      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);\r
-\r
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-      if (!withValues.containsKey("is_admin"))\r
-        withValues.put("is_admin","0");\r
-\r
-      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
-      if (newPassword!=null)\r
-        withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));\r
-\r
-      mainModule.set(withValues);\r
-\r
-      logAdminUsage(aRequest, id, "object modified");\r
-\r
-      if (requestParser.hasParameter("returnurl"))\r
-        redirect(aResponse, requestParser.getParameter("returnurl"));\r
-      else\r
-        list(aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void updatepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      String id = requestParser.getParameter("id");\r
-      EntityUsers user = (EntityUsers) mainModule.getById(id);\r
-      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);\r
-\r
-      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
-      if (newPassword!=null) {\r
-        user.setValueForProperty("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));\r
-        user.update();\r
-\r
-        logAdminUsage(aRequest, id, "password changed");\r
-\r
-        // hackish: to make sure the cached logged in user is up-to-date:\r
-        ServletHelper.setUser(aRequest, (EntityUsers) mainModule.getById(ServletHelper.getUser(aRequest).getId()));\r
-      }\r
-\r
-      if (requestParser.hasParameter("returnurl"))\r
-        redirect(aResponse, requestParser.getParameter("returnurl"));\r
-      else\r
-        redirect(aResponse, "");\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-\r
-    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
-\r
-    returnUserList(aRequest, aResponse, offset);\r
-  }\r
-\r
-  public void returnUserList(\r
-       HttpServletRequest aRequest,\r
-       HttpServletResponse aResponse,\r
-       int anOffset) throws ServletModuleExc {\r
-\r
-// ML: to be deleted, support for 3 extra vars to be added\r
-\r
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-    URLBuilder urlBuilder = new URLBuilder();\r
-    EntityAdapterModel model;\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-\r
-      Object userList =\r
-          new CachingRewindableIterator(\r
-            new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage,\r
-               MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset)\r
-      );\r
-\r
-      responseData.put("nexturl", null);\r
-      responseData.put("prevurl", null);\r
-\r
-      count=mainModule.getSize("");\r
-\r
-      urlBuilder.setValue("module", "Users");\r
-      urlBuilder.setValue("do", "list");\r
-\r
-      urlBuilder.setValue("offset", anOffset);\r
-      responseData.put("offset" , new Integer(anOffset).toString());\r
-      responseData.put("thisurl" , urlBuilder.getQuery());\r
-\r
-      if (count>=anOffset+nrEntitiesPerListPage) {\r
-        urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));\r
-        responseData.put("nexturl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      if (anOffset>0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
-        responseData.put("prevurl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      responseData.put("users", userList);\r
-      responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest))));\r
-      responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest))));\r
-      responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest))));\r
-\r
-      responseData.put("from" , Integer.toString(anOffset+1));\r
-      responseData.put("count", Integer.toString(count));\r
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
-      responseData.put("offset" , Integer.toString(anOffset));\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void showUser(String anId, boolean anOnlyPassword, HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
-      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
-      Map user;\r
-      URLBuilder urlBuilder = new URLBuilder();\r
-\r
-      urlBuilder.setValue("module", "Users");\r
-      if (anOnlyPassword)\r
-        urlBuilder.setValue("do", "changepassword");\r
-      else\r
-        urlBuilder.setValue("do", "edit");\r
-      urlBuilder.setValue("id", anId);\r
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
-\r
-      if (anId!=null) {\r
-        responseData.put("new", Boolean.FALSE);\r
-        user = model.makeEntityAdapter("user", mainModule.getById(anId));\r
-      }\r
-      else {\r
-        List fields = DatabaseUsers.getInstance().getFields();\r
-        responseData.put("new", Boolean.TRUE);\r
-        user = new HashMap();\r
-        Iterator i = fields.iterator();\r
-        while (i.hasNext()) {\r
-          user.put(i.next(), null);\r
-        }\r
-\r
-        MirGlobal.localizer().adminInterface().initializeArticle(user);\r
-      }\r
-      responseData.put("user", user);\r
-      responseData.put("passwordonly", new Boolean(anOnlyPassword));\r
-\r
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleUserExc, ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      EntityUsers user = (EntityUsers) mainModule.getById(aRequest.getParameter("id"));\r
-\r
-      MirGlobal.accessControl().user().assertMayDeleteUser(ServletHelper.getUser(aRequest), user);\r
-\r
-      super.delete(aRequest, aResponse);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure(t);\r
-    }\r
-  }\r
-\r
-  public void changepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String idParam = aRequest.getParameter("id");\r
-\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");\r
-\r
-    try {\r
-      EntityUsers user = (EntityUsers) mainModule.getById(idParam);\r
-      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);\r
-\r
-      showUser(idParam, true, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-}\r
-\r
+/*
+ * 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 mircoders.servlet;
+
+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 mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.CachingRewindableIterator;
+import mir.util.HTTPRequestParser;
+import mir.util.URLBuilder;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleUsers;
+import mircoders.storage.DatabaseUsers;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+public class ServletModuleUsers extends ServletModule
+{
+  private static ServletModuleUsers instance = new ServletModuleUsers();
+  public static ServletModule getInstance() { return instance; }
+  protected ModuleUsers usersModule;
+
+  private ServletModuleUsers() {
+    super();
+    logger = new LoggerWrapper("ServletModule.Users");
+
+    try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "user";
+      usersModule = new ModuleUsers(DatabaseUsers.getInstance());
+      mainModule = usersModule;
+    }
+    catch (Throwable e) {
+      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());
+    }
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+
+    if (idParam == null)
+      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
+
+    try {
+      EntityUsers user = (EntityUsers) mainModule.getById(idParam);
+      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);
+
+      showUser(idParam, false, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc
+  {
+    try {
+      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));
+
+      showUser(null, false, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public String validatePassword(EntityUsers aUser, HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    if ( (aRequestParser.getParameter("newpassword") != null &&
+          aRequestParser.getParameter("newpassword").length() > 0) ||
+        (aRequestParser.getParameter("newpassword2") != null &&
+         aRequestParser.getParameter("newpassword2").length() > 0)
+        ) {
+      String newPassword = aRequestParser.getParameterWithDefault("newpassword", "");
+      String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", "");
+      String oldPassword = aRequestParser.getParameterWithDefault("oldpassword", "");
+
+      try {
+        if (!usersModule.checkUserPassword(aUser, oldPassword)) {
+          throw new ServletModuleUserExc("user.error.incorrectpassword", new String[] {});
+        }
+      }
+      catch (Throwable t) {
+        throw new ServletModuleFailure(t);
+      }
+
+
+      if (newPassword.length() == 0 || newPassword2.length() == 0) {
+        throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {});
+      }
+
+      if (!newPassword.equals(newPassword2)) {
+        throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {});
+      }
+
+      return newPassword;
+    }
+    else
+      return null;
+  }
+
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    try {
+      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));
+
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);
+      if (newPassword!=null)
+        withValues.put("password", newPassword);
+      else
+        throw new ServletModuleUserExc("user.error.missingpassword", new String[] {});
+
+      String id = mainModule.add(withValues);
+
+      logAdminUsage(aRequest, id, "object added");
+
+      if (requestParser.hasParameter("returnurl"))
+        redirect(aResponse, requestParser.getParameter("returnurl"));
+      else
+        list(aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      String id = requestParser.getParameter("id");
+      EntityUsers user = (EntityUsers) mainModule.getById(id);
+      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);
+
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+      if (!withValues.containsKey("is_admin"))
+        withValues.put("is_admin","0");
+
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);
+      if (newPassword!=null)
+        withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));
+
+      mainModule.set(withValues);
+
+      logAdminUsage(aRequest, id, "object modified");
+
+      if (requestParser.hasParameter("returnurl"))
+        redirect(aResponse, requestParser.getParameter("returnurl"));
+      else
+        list(aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void updatepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      String id = requestParser.getParameter("id");
+      EntityUsers user = (EntityUsers) mainModule.getById(id);
+      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);
+
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);
+      if (newPassword!=null) {
+        user.setValueForProperty("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));
+        user.update();
+
+        logAdminUsage(aRequest, id, "password changed");
+
+        // hackish: to make sure the cached logged in user is up-to-date:
+        ServletHelper.setUser(aRequest, (EntityUsers) mainModule.getById(ServletHelper.getUser(aRequest).getId()));
+      }
+
+      if (requestParser.hasParameter("returnurl"))
+        redirect(aResponse, requestParser.getParameter("returnurl"));
+      else
+        redirect(aResponse, "");
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+    int offset = requestParser.getIntegerWithDefault("offset", 0);
+
+    returnUserList(aRequest, aResponse, offset);
+  }
+
+  public void returnUserList(
+       HttpServletRequest aRequest,
+       HttpServletResponse aResponse,
+       int anOffset) throws ServletModuleExc {
+
+// ML: to be deleted, support for 3 extra vars to be added
+
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    URLBuilder urlBuilder = new URLBuilder();
+    EntityAdapterModel model;
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      model = MirGlobal.localizer().dataModel().adapterModel();
+
+      Object userList =
+          new CachingRewindableIterator(
+            new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage,
+               MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset)
+      );
+
+      responseData.put("nexturl", null);
+      responseData.put("prevurl", null);
+
+      count=mainModule.getSize("");
+
+      urlBuilder.setValue("module", "Users");
+      urlBuilder.setValue("do", "list");
+
+      urlBuilder.setValue("offset", anOffset);
+      responseData.put("offset" , new Integer(anOffset).toString());
+      responseData.put("thisurl" , urlBuilder.getQuery());
+
+      if (count>=anOffset+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("users", userList);
+      responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest))));
+      responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest))));
+      responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest))));
+
+      responseData.put("from" , Integer.toString(anOffset+1));
+      responseData.put("count", Integer.toString(count));
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+      responseData.put("offset" , Integer.toString(anOffset));
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void showUser(String anId, boolean anOnlyPassword, HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
+      Map user;
+      URLBuilder urlBuilder = new URLBuilder();
+
+      urlBuilder.setValue("module", "Users");
+      if (anOnlyPassword)
+        urlBuilder.setValue("do", "changepassword");
+      else
+        urlBuilder.setValue("do", "edit");
+      urlBuilder.setValue("id", anId);
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+
+      if (anId!=null) {
+        responseData.put("new", Boolean.FALSE);
+        user = model.makeEntityAdapter("user", mainModule.getById(anId));
+      }
+      else {
+        List fields = DatabaseUsers.getInstance().getFields();
+        responseData.put("new", Boolean.TRUE);
+        user = new HashMap();
+        Iterator i = fields.iterator();
+        while (i.hasNext()) {
+          user.put(i.next(), null);
+        }
+
+        MirGlobal.localizer().adminInterface().initializeArticle(user);
+      }
+      responseData.put("user", user);
+      responseData.put("passwordonly", new Boolean(anOnlyPassword));
+
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleUserExc, ServletModuleExc, ServletModuleFailure {
+    try {
+      EntityUsers user = (EntityUsers) mainModule.getById(aRequest.getParameter("id"));
+
+      MirGlobal.accessControl().user().assertMayDeleteUser(ServletHelper.getUser(aRequest), user);
+
+      super.delete(aRequest, aResponse);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
+  }
+
+  public void changepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    String idParam = aRequest.getParameter("id");
+
+    if (idParam == null)
+      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
+
+    try {
+      EntityUsers user = (EntityUsers) mainModule.getById(idParam);
+      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);
+
+      showUser(idParam, true, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+}
+
index 2499be3..fb07f92 100755 (executable)
@@ -32,10 +32,9 @@ package mircoders.servlet;
 
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
+import mircoders.global.MirGlobal;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseVideo;
-import mircoders.global.*;
 
 /**
  *
index 681fbaa..606963b 100755 (executable)
@@ -1,91 +1,90 @@
-/*\r
- * Copyright (C) 2001, 2002 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
-\r
-package mircoders.storage;\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.List;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.storage.Database;\r
-import mir.storage.StorageObject;\r
-import mir.storage.StorageObjectFailure;\r
-\r
-/**\r
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
- *\r
- *\r
- */\r
-\r
-public class DatabaseImages extends Database implements StorageObject{\r
-\r
-  private static DatabaseImages instance;\r
-\r
-  public synchronized static DatabaseImages getInstance() {\r
-    if (instance == null) {\r
-      instance = new DatabaseImages();\r
-    }\r
-    return instance;\r
-  }\r
-\r
-  private DatabaseImages() {\r
-    super();\r
-\r
-    logger = new LoggerWrapper("Database.Images");\r
-\r
-    hasTimestamp = true;\r
-    theTable = "images";\r
-    theCoreTable = "media";\r
-    theEntityClass = mircoders.entity.EntityImages.class;\r
-  }\r
-\r
-  public void update(Entity theEntity) throws StorageObjectFailure {\r
-    String date = theEntity.getValue("date");\r
-    if (date == null) {\r
-      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
-      theEntity.setValueForProperty("date", date);\r
-    }\r
-\r
-    super.update(theEntity);\r
-  }\r
-\r
-  public String insert(Entity theEntity) throws StorageObjectFailure {\r
-    String date = theEntity.getValue("date");\r
-\r
-    if (date == null) {\r
-      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
-      theEntity.setValueForProperty("date", date);\r
-    }\r
-\r
-    return super.insert(theEntity);\r
-  }\r
-}\r
+/*
+ * 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 mircoders.storage;
+
+import java.util.GregorianCalendar;
+
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.storage.Database;
+import mir.storage.StorageObject;
+import mir.storage.StorageObjectFailure;
+
+/**
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
+ *
+ *
+ */
+
+public class DatabaseImages extends Database implements StorageObject{
+
+  private static DatabaseImages instance;
+
+  public synchronized static DatabaseImages getInstance() {
+    if (instance == null) {
+      instance = new DatabaseImages();
+    }
+    return instance;
+  }
+
+  private DatabaseImages() {
+    super();
+
+    logger = new LoggerWrapper("Database.Images");
+
+    hasTimestamp = true;
+    theTable = "images";
+    theCoreTable = "media";
+    theEntityClass = mircoders.entity.EntityImages.class;
+  }
+
+  public void update(Entity theEntity) throws StorageObjectFailure {
+    String date = theEntity.getValue("date");
+    if (date == null) {
+      date = StringUtil.date2webdbDate(new GregorianCalendar());
+      theEntity.setValueForProperty("date", date);
+    }
+
+    super.update(theEntity);
+  }
+
+  public String insert(Entity theEntity) throws StorageObjectFailure {
+    String date = theEntity.getValue("date");
+
+    if (date == null) {
+      date = StringUtil.date2webdbDate(new GregorianCalendar());
+      theEntity.setValueForProperty("date", date);
+    }
+
+    return super.insert(theEntity);
+  }
+}
index 5f2b138..d5609ea 100755 (executable)
@@ -30,7 +30,7 @@
 
 package mircoders.storage;
 
-import java.util.*;
+import java.util.GregorianCalendar;
 
 import mir.entity.Entity;
 import mir.log.LoggerWrapper;
index 52e28f7..5286af8 100755 (executable)
@@ -34,7 +34,9 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
-import java.util.*;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
 
 import mir.util.ExceptionFunctions;
 import mir.util.PropertiesManipulator;
index c6e1619..351274e 100755 (executable)
@@ -1,96 +1,97 @@
-package tool;\r
-\r
-import java.security.MessageDigest;\r
-import java.util.TimeZone;\r
-\r
-import gnu.regexp.RE;\r
-import mir.util.StringRoutines;\r
-\r
-/**\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public class ConfigTool {\r
-  public ConfigTool() {\r
-  }\r
-\r
-  public static void timezone(String aSpecification) {\r
-    try {\r
-      RE specification = new RE(aSpecification);\r
-      String[] timeZoneIds = TimeZone.getAvailableIDs();\r
-\r
-      System.out.println("ID\tOffset\tDST?\tName");\r
-      for (int i=0; i<timeZoneIds.length; i++) {\r
-        if (specification.isMatch(timeZoneIds[i])) {\r
-          TimeZone timeZone = TimeZone.getTimeZone(timeZoneIds[i]);\r
-          long offset = timeZone.getRawOffset()/(1000*60);\r
-          String sign = "";\r
-          if (offset<0) {\r
-            offset=-offset;\r
-            sign = "-";\r
-          }\r
-\r
-          System.out.println(timeZone.getID() + "\t" + sign + offset/60 + ":" + StringRoutines.padStringLeft(Long.toString(offset%60),2,'0')+"\t"+(timeZone.useDaylightTime()?"yes":"no")+"\t"+ timeZone.getDisplayName());\r
-        }\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      System.err.println(t.toString());\r
-    }\r
-  }\r
-\r
-  public static void digest(String aDigest, String aData) {\r
-    try {\r
-      MessageDigest messageDigest = MessageDigest.getInstance(aDigest);\r
-\r
-      System.out.println(StringRoutines.convertToHex(messageDigest.digest(aData.getBytes("UTF-8"))));\r
-    }\r
-    catch (Throwable t) {\r
-      System.err.println(t.toString());\r
-    }\r
-  }\r
-\r
-  public static void main(String[] anArguments) {\r
-    String command = "help";\r
-\r
-    if (anArguments.length >= 1) {\r
-      command = anArguments[0];\r
-\r
-      if (command.equals("timezone")) {\r
-        if (anArguments.length<=2) {\r
-          if (anArguments.length==2)\r
-            timezone(anArguments[1]);\r
-          else\r
-            timezone(".*");\r
-        }\r
-\r
-        return;\r
-      }\r
-      else if (command.equals("digest")) {\r
-        if (anArguments.length == 3) {\r
-          digest(anArguments[1], anArguments[2]);\r
-\r
-          return;\r
-        }\r
-      }\r
-    }\r
-\r
-\r
-\r
-    System.out.println("Usage:");\r
-\r
-    System.out.println("  ConfigTool timezone [regexp]");\r
-    System.out.println("");\r
-    System.out.println("      Shows the available timezones");\r
-    System.out.println("");\r
-    System.out.println("  BundleTool digest <digestname> <string>");\r
-    System.out.println("");\r
-    System.out.println("      Calculates the digest of a string.");\r
-    System.out.println("");\r
-  }\r
+package tool;
+
+import gnu.regexp.RE;
+
+import java.security.MessageDigest;
+import java.util.TimeZone;
+
+import mir.util.StringRoutines;
+
+/**
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public class ConfigTool {
+  public ConfigTool() {
+  }
+
+  public static void timezone(String aSpecification) {
+    try {
+      RE specification = new RE(aSpecification);
+      String[] timeZoneIds = TimeZone.getAvailableIDs();
+
+      System.out.println("ID\tOffset\tDST?\tName");
+      for (int i=0; i<timeZoneIds.length; i++) {
+        if (specification.isMatch(timeZoneIds[i])) {
+          TimeZone timeZone = TimeZone.getTimeZone(timeZoneIds[i]);
+          long offset = timeZone.getRawOffset()/(1000*60);
+          String sign = "";
+          if (offset<0) {
+            offset=-offset;
+            sign = "-";
+          }
+
+          System.out.println(timeZone.getID() + "\t" + sign + offset/60 + ":" + StringRoutines.padStringLeft(Long.toString(offset%60),2,'0')+"\t"+(timeZone.useDaylightTime()?"yes":"no")+"\t"+ timeZone.getDisplayName());
+        }
+      }
+    }
+    catch (Throwable t) {
+      System.err.println(t.toString());
+    }
+  }
+
+  public static void digest(String aDigest, String aData) {
+    try {
+      MessageDigest messageDigest = MessageDigest.getInstance(aDigest);
+
+      System.out.println(StringRoutines.convertToHex(messageDigest.digest(aData.getBytes("UTF-8"))));
+    }
+    catch (Throwable t) {
+      System.err.println(t.toString());
+    }
+  }
+
+  public static void main(String[] anArguments) {
+    String command = "help";
+
+    if (anArguments.length >= 1) {
+      command = anArguments[0];
+
+      if (command.equals("timezone")) {
+        if (anArguments.length<=2) {
+          if (anArguments.length==2)
+            timezone(anArguments[1]);
+          else
+            timezone(".*");
+        }
+
+        return;
+      }
+      else if (command.equals("digest")) {
+        if (anArguments.length == 3) {
+          digest(anArguments[1], anArguments[2]);
+
+          return;
+        }
+      }
+    }
+
+
+
+    System.out.println("Usage:");
+
+    System.out.println("  ConfigTool timezone [regexp]");
+    System.out.println("");
+    System.out.println("      Shows the available timezones");
+    System.out.println("");
+    System.out.println("  BundleTool digest <digestname> <string>");
+    System.out.println("");
+    System.out.println("      Calculates the digest of a string.");
+    System.out.println("");
+  }
 }
\ No newline at end of file