organising imports
authoridfx <idfx>
Sat, 8 Mar 2003 17:18:18 +0000 (17:18 +0000)
committeridfx <idfx>
Sat, 8 Mar 2003 17:18:18 +0000 (17:18 +0000)
22 files changed:
source/Mir.java
source/OpenMir.java
source/mir/servlet/ServletModule.java
source/mir/util/ExceptionFunctions.java
source/mircoders/entity/EntityImages.java
source/mircoders/module/ModuleComment.java
source/mircoders/producer/IndexingProducerNode.java
source/mircoders/producer/PDFGeneratingProducerNode.java
source/mircoders/producer/UnIndexingProducerNode.java
source/mircoders/servlet/ServletHelper.java
source/mircoders/servlet/ServletModuleAdmin.java
source/mircoders/servlet/ServletModuleBreaking.java
source/mircoders/servlet/ServletModuleComment.java
source/mircoders/servlet/ServletModuleContent.java
source/mircoders/servlet/ServletModuleFileEdit.java
source/mircoders/servlet/ServletModuleHidden.java
source/mircoders/servlet/ServletModuleLinksImcs.java
source/mircoders/servlet/ServletModuleMessage.java
source/mircoders/servlet/ServletModuleOpenIndy.java
source/mircoders/servlet/ServletModuleProducer.java
source/mircoders/servlet/ServletModuleUploadedMedia.java
source/mircoders/servlet/ServletModuleUsers.java

index 31650ea..48c5797 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-import java.io.IOException;\r
-import java.io.PrintWriter;\r
-import java.lang.reflect.Method;\r
-import java.util.GregorianCalendar;\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
-\r
-import javax.servlet.ServletException;\r
-import javax.servlet.UnavailableException;\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.generator.FreemarkerGenerator;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.HTMLTemplateProcessor;\r
-import mir.misc.StringUtil;\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.StringRoutines;\r
-import mir.util.ExceptionFunctions;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleMessage;\r
-import mircoders.module.ModuleUsers;\r
-import mircoders.storage.DatabaseArticleType;\r
-import mircoders.storage.DatabaseMessages;\r
-import mircoders.storage.DatabaseUsers;\r
-\r
-import org.apache.struts.util.MessageResources;\r
-\r
-import freemarker.template.SimpleHash;\r
-import freemarker.template.SimpleList;\r
-import freemarker.template.SimpleScalar;\r
-import freemarker.template.TemplateModel;\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.34 2003/03/07 00:50:22 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
-\r
-  //I don't know about making this static cause it removes the\r
-  //possibility to change the config on the fly.. -mh\r
-  private static List loginLanguages = null;\r
-  public HttpSession session;\r
-\r
-  public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-    throws ServletException, IOException {\r
-    doPost(aRequest, aResponse);\r
-  }\r
-\r
-  protected TemplateModel getLoginLanguages() throws ServletException {\r
-    synchronized (Mir.class) {\r
-      try {\r
-        if (loginLanguages == null) {\r
-          MessageResources messageResources2 =\r
-            MessageResources.getMessageResources("bundles.admin");\r
-          MessageResources messageResources =\r
-            MessageResources.getMessageResources("bundles.adminlocal");\r
-          List languages =\r
-            StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault(\r
-                "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 FreemarkerGenerator.makeAdapter(loginLanguages);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletException(t.getMessage());\r
-      }\r
-    }\r
-  }\r
-\r
-  // FIXME: this should probalby go into AbstractServlet so it can be used in\r
-  // OpenMir as well -mh\r
-  protected String getDefaultLanguage(HttpServletRequest aRequest) {\r
-    String defaultlanguage =\r
-      MirGlobal.getConfigPropertyWithDefault("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
-  public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-    throws ServletException, IOException, UnavailableException {\r
-    long startTime = System.currentTimeMillis();\r
-    long sessionConnectTime = 0;\r
-    EntityUsers userEntity;\r
-    String http = "";\r
-\r
-    if ((configuration.getString("RootUri") == null) ||\r
-        configuration.getString("RootUri").equals("")) {\r
-      configuration.setProperty("RootUri", aRequest.getContextPath());\r
-    }\r
-\r
-    configuration.addProperty("ServletName", getServletName());\r
-\r
-    //*** test\r
-    // Log.info(this, "blalalala");\r
-    session = aRequest.getSession(true);\r
-    userEntity = (EntityUsers) session.getAttribute("login.uid");\r
-\r
-    if (aRequest.getServerPort() == 443) {\r
-      http = "https";\r
-    } else {\r
-      http = "http";\r
-    }\r
-\r
-    //make sure client browsers don't cache anything\r
-    setNoCaching(aResponse);\r
-\r
-    //FIXME: this seems kind of hackish and only here because we can have\r
-    // default other than the one that the browser is set to.\r
-    Locale locale = new Locale(getDefaultLanguage(aRequest), "");\r
-    MessageResources messageResources =\r
-      MessageResources.getMessageResources("bundles.admin");\r
-    String htmlcharset = messageResources.getMessage(locale, "htmlcharset");\r
-\r
-    aResponse.setContentType("text/html; charset=" + htmlcharset);\r
-\r
-    String moduleName = aRequest.getParameter("module");\r
-    checkLanguage(session, aRequest);\r
-\r
-    /** @todo for cleanup and readability this should be moved to\r
-     *  method loginIfNecessary() */\r
-    if ((moduleName != null) && moduleName.equals("direct")) {\r
-      //...\r
-    }\r
-\r
-    // Authentication\r
-    if (((moduleName != null) && moduleName.equals("login")) ||\r
-        (userEntity == null)) {\r
-      String user = aRequest.getParameter("login");\r
-      String passwd = aRequest.getParameter("password");\r
-      logger.debug("--login: evaluating for user: " + user);\r
-      userEntity = allowedUser(user, passwd);\r
-\r
-      if (userEntity == null) {\r
-        // login failed: redirecting to login\r
-        logger.warn("--login: failed!");\r
-        _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
-\r
-        return;\r
-      } else if ((moduleName != null) && moduleName.equals("login")) {\r
-        // login successful\r
-        logger.info("--login: successful! setting uid: " + userEntity.getId());\r
-        session.setAttribute("login.uid", userEntity);\r
-        logger.debug("--login: trying to retrieve login.target");\r
-\r
-        String target = (String) session.getAttribute("login.target");\r
-\r
-        if (target != null) {\r
-          logger.debug("Redirect: " + target);\r
-\r
-          int serverPort = aRequest.getServerPort();\r
-          String redirect = "";\r
-          String redirectString = "";\r
-\r
-          if (serverPort == 80) {\r
-            redirect =\r
-              aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);\r
-            redirectString =\r
-              "<html><head><meta http-equiv=refresh content=\"1;URL=" +\r
-              redirect + "\"></head><body>going <a href=\"" + redirect +\r
-              "\">Mir</a></body></html>";\r
-          } else {\r
-            redirect =\r
-              aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +\r
-                aRequest.getServerPort() + target);\r
-            redirectString =\r
-              "<html><head><meta http-equiv=refresh content=\"1;URL=" +\r
-              redirect + "\"></head><body>going <a href=\"" + redirect +\r
-              "\">Mir</a></body></html>";\r
-          }\r
-\r
-          aResponse.getWriter().println(redirectString);\r
-\r
-          //aResponse.sendRedirect(redirect);\r
-        } else {\r
-          // redirecting to default target\r
-          logger.debug("--login: no target - redirecting to default");\r
-          _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);\r
-        }\r
-\r
-        return;\r
-      }\r
-       // if login succesful\r
-    }\r
-     // if login\r
-\r
-    if ((moduleName != null) && moduleName.equals("logout")) {\r
-      logger.info("--logout");\r
-      session.invalidate();\r
-\r
-      //session = aRequest.getSession(true);\r
-      //checkLanguage(session, aRequest);\r
-      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
-\r
-      return;\r
-    }\r
-\r
-    // Check if authed!\r
-    if (userEntity == null) {\r
-      // redirect to loginpage\r
-      String redirectString = aRequest.getRequestURI();\r
-      String queryString = aRequest.getQueryString();\r
-\r
-      if ((queryString != null) && !queryString.equals("")) {\r
-        redirectString += ("?" + aRequest.getQueryString());\r
-        logger.debug("STORING: " + redirectString);\r
-        session.setAttribute("login.target", redirectString);\r
-      }\r
-\r
-      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());\r
-\r
-      return;\r
-    }\r
-\r
-    // If no module is specified goto standard startpage\r
-    if ((moduleName == null) || moduleName.equals("")) {\r
-      logger.debug("no module: redirect to standardpage");\r
-      _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);\r
-\r
-      return;\r
-    }\r
-\r
-    // end of auth\r
-    // From now on regular dispatching...\r
-    try {\r
-      // get servletmodule by parameter and continue with dispacher\r
-      ServletModule smod = getServletModuleForName(moduleName);\r
-      ServletModuleDispatch.dispatch(smod, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      Throwable cause = ExceptionFunctions.traceCauseException(e);\r
-\r
-      if (cause instanceof ServletModuleUserExc)\r
-        handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);\r
-      else\r
-        handleError(aRequest, aResponse, aResponse.getWriter(), cause);\r
-\r
-    }\r
-\r
-    // timing...\r
-    sessionConnectTime = System.currentTimeMillis() - startTime;\r
-    logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");\r
-  }\r
-\r
-  /**\r
-   *  Private method getServletModuleForName returns ServletModule\r
-   *  from Cache\r
-   *\r
-   * @param moduleName\r
-   * @return ServletModule\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
-        } 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
-    } else {\r
-      return (ServletModule) servletModuleInstanceHash.get(moduleName);\r
-    }\r
-  }\r
-\r
-  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
-                               PrintWriter out, Throwable anException) {\r
-    try {\r
-      logger.info("user error: " + anException.getMessage());\r
-      SimpleHash modelRoot = new SimpleHash();\r
-      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));\r
-      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));\r
-      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),\r
-                                    modelRoot, out, aRequest.getLocale() );\r
-      out.close();\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("Error in UserErrorTemplate");\r
-    }\r
-\r
-  }\r
-\r
-  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {\r
-\r
-    try {\r
-      logger.error("error: " + anException);\r
-      SimpleHash modelRoot = new SimpleHash();\r
-      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));\r
-      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(\r
-                                               new GregorianCalendar())));\r
-      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),\r
-                                    modelRoot,out, aRequest.getLocale());\r
-      out.close();\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("Error in ErrorTemplate");\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  evaluate login for user / password\r
-   */\r
-  protected EntityUsers allowedUser(String user, String password) {\r
-    try {\r
-      if (usersModule == null) {\r
-        usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
-      }\r
-\r
-      return usersModule.getUserForLogin(user, password);\r
-    } catch (Exception e) {\r
-      logger.debug(e.getMessage());\r
-      e.printStackTrace();\r
-\r
-      return null;\r
-    }\r
-  }\r
-\r
-  // Redirect-methods\r
-  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,\r
-    PrintWriter out) {\r
-    String loginTemplate = configuration.getString("Mir.LoginTemplate");\r
-    String sessionUrl = aResponse.encodeURL("");\r
-\r
-    try {\r
-      SimpleHash mergeData = new SimpleHash();\r
-      SimpleList languages = new SimpleList();\r
-\r
-      mergeData.put("session", sessionUrl);\r
-\r
-      mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));\r
-      mergeData.put("languages", getLoginLanguages());\r
-\r
-      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,\r
-        getLocale(aRequest));\r
-    }\r
-    catch (Throwable e) {\r
-      handleError(aRequest, aResponse, out, e);\r
-    }\r
-  }\r
-\r
-  private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,\r
-    PrintWriter out, EntityUsers userEntity) {\r
-    String startTemplate = "templates/admin/start_admin.template";\r
-    String sessionUrl = aResponse.encodeURL("");\r
-\r
-    try {\r
-      // merge with logged in user and messages\r
-      SimpleHash mergeData = new SimpleHash();\r
-      mergeData.put("session", sessionUrl);\r
-      mergeData.put("login_user", userEntity);\r
-\r
-      if (messageModule == null) {\r
-        messageModule = new ModuleMessage(DatabaseMessages.getInstance());\r
-      }\r
-\r
-      mergeData.put("messages",\r
-        messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));\r
-\r
-      mergeData.put("articletypes",\r
-        DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));\r
-\r
-      HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,\r
-        getLocale(aRequest));\r
-    }\r
-    catch (Exception e) {\r
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      handleError(aRequest, aResponse, out, e);\r
-    }\r
-  }\r
-\r
-  public String getServletInfo() {\r
-    return "Mir " + configuration.getString("Mir.Version");\r
-  }\r
-\r
-  private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {\r
-    // a lang parameter always sets the language\r
-    String lang = aRequest.getParameter("language");\r
-\r
-    if (lang != null) {\r
-      logger.info("selected language " + lang + " overrides accept-language");\r
-      setLanguage(session, lang);\r
-      setLocale(session, new Locale(lang, ""));\r
-    }\r
-    // otherwise store language from accept header in session\r
-    else if (session.getAttribute("Language") == null) {\r
-      logger.info("accept-language is " + aRequest.getLocale().getLanguage());\r
-      setLanguage(session, aRequest.getLocale().getLanguage());\r
-      setLocale(session, aRequest.getLocale());\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 the com.oreilly.servlet library, 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.io.PrintWriter;
+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.ServletException;
+import javax.servlet.UnavailableException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.generator.FreemarkerGenerator;
+import mir.log.LoggerWrapper;
+import mir.misc.HTMLTemplateProcessor;
+import mir.misc.StringUtil;
+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.storage.DatabaseArticleType;
+import mircoders.storage.DatabaseMessages;
+import mircoders.storage.DatabaseUsers;
+
+import org.apache.struts.util.MessageResources;
+
+import freemarker.template.SimpleHash;
+import freemarker.template.SimpleList;
+import freemarker.template.SimpleScalar;
+import freemarker.template.TemplateModel;
+
+
+
+/**
+ * Mir.java - main servlet, that dispatches to servletmodules
+ *
+ * @author $Author: idfx $
+ * @version $Id: Mir.java,v 1.35 2003/03/08 17:18:19 idfx Exp $
+ *
+ */
+public class Mir extends AbstractServlet {
+  private static ModuleUsers usersModule = null;
+  private static ModuleMessage messageModule = null;
+  private final static Map servletModuleInstanceHash = new HashMap();
+
+  //I don't know about making this static cause it removes the
+  //possibility to change the config on the fly.. -mh
+  private static List loginLanguages = null;
+  public HttpSession session;
+
+  public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse)
+    throws ServletException, IOException {
+    doPost(aRequest, aResponse);
+  }
+
+  protected TemplateModel getLoginLanguages() throws ServletException {
+    synchronized (Mir.class) {
+      try {
+        if (loginLanguages == null) {
+          MessageResources messageResources2 =
+            MessageResources.getMessageResources("bundles.admin");
+          MessageResources messageResources =
+            MessageResources.getMessageResources("bundles.adminlocal");
+          List languages =
+            StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault(
+                "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 FreemarkerGenerator.makeAdapter(loginLanguages);
+      }
+      catch (Throwable t) {
+        throw new ServletException(t.getMessage());
+      }
+    }
+  }
+
+  // FIXME: this should probalby go into AbstractServlet so it can be used in
+  // OpenMir as well -mh
+  protected String getDefaultLanguage(HttpServletRequest aRequest) {
+    String defaultlanguage =
+      MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", "");
+
+    if (defaultlanguage.length() == 0) {
+      Locale locale = aRequest.getLocale();
+      defaultlanguage = locale.getLanguage();
+    }
+
+    return defaultlanguage;
+  }
+
+  public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse)
+    throws ServletException, IOException, UnavailableException {
+    long startTime = System.currentTimeMillis();
+    long sessionConnectTime = 0;
+    EntityUsers userEntity;
+    String http = "";
+
+    if ((configuration.getString("RootUri") == null) ||
+        configuration.getString("RootUri").equals("")) {
+      configuration.setProperty("RootUri", aRequest.getContextPath());
+    }
+
+    configuration.addProperty("ServletName", getServletName());
+
+    //*** test
+    // Log.info(this, "blalalala");
+    session = aRequest.getSession(true);
+    userEntity = (EntityUsers) session.getAttribute("login.uid");
+
+    if (aRequest.getServerPort() == 443) {
+      http = "https";
+    } else {
+      http = "http";
+    }
+
+    //make sure client browsers don't cache anything
+    setNoCaching(aResponse);
+
+    //FIXME: this seems kind of hackish and only here because we can have
+    // default other than the one that the browser is set to.
+    Locale locale = new Locale(getDefaultLanguage(aRequest), "");
+    MessageResources messageResources =
+      MessageResources.getMessageResources("bundles.admin");
+    String htmlcharset = messageResources.getMessage(locale, "htmlcharset");
+
+    aResponse.setContentType("text/html; charset=" + htmlcharset);
+
+    String moduleName = aRequest.getParameter("module");
+    checkLanguage(session, aRequest);
+
+    /** @todo for cleanup and readability this should be moved to
+     *  method loginIfNecessary() */
+    if ((moduleName != null) && moduleName.equals("direct")) {
+      //...
+    }
+
+    // Authentication
+    if (((moduleName != null) && moduleName.equals("login")) ||
+        (userEntity == null)) {
+      String user = aRequest.getParameter("login");
+      String passwd = aRequest.getParameter("password");
+      logger.debug("--login: evaluating for user: " + user);
+      userEntity = allowedUser(user, passwd);
+
+      if (userEntity == null) {
+        // login failed: redirecting to login
+        logger.warn("--login: failed!");
+        _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
+
+        return;
+      } else if ((moduleName != null) && moduleName.equals("login")) {
+        // login successful
+        logger.info("--login: successful! setting uid: " + userEntity.getId());
+        session.setAttribute("login.uid", userEntity);
+        logger.debug("--login: trying to retrieve login.target");
+
+        String target = (String) session.getAttribute("login.target");
+
+        if (target != null) {
+          logger.debug("Redirect: " + target);
+
+          int serverPort = aRequest.getServerPort();
+          String redirect = "";
+          String redirectString = "";
+
+          if (serverPort == 80) {
+            redirect =
+              aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
+            redirectString =
+              "<html><head><meta http-equiv=refresh content=\"1;URL=" +
+              redirect + "\"></head><body>going <a href=\"" + redirect +
+              "\">Mir</a></body></html>";
+          } else {
+            redirect =
+              aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
+                aRequest.getServerPort() + target);
+            redirectString =
+              "<html><head><meta http-equiv=refresh content=\"1;URL=" +
+              redirect + "\"></head><body>going <a href=\"" + redirect +
+              "\">Mir</a></body></html>";
+          }
+
+          aResponse.getWriter().println(redirectString);
+
+          //aResponse.sendRedirect(redirect);
+        } else {
+          // redirecting to default target
+          logger.debug("--login: no target - redirecting to default");
+          _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
+        }
+
+        return;
+      }
+       // if login succesful
+    }
+     // if login
+
+    if ((moduleName != null) && moduleName.equals("logout")) {
+      logger.info("--logout");
+      session.invalidate();
+
+      //session = aRequest.getSession(true);
+      //checkLanguage(session, aRequest);
+      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
+
+      return;
+    }
+
+    // Check if authed!
+    if (userEntity == null) {
+      // redirect to loginpage
+      String redirectString = aRequest.getRequestURI();
+      String queryString = aRequest.getQueryString();
+
+      if ((queryString != null) && !queryString.equals("")) {
+        redirectString += ("?" + aRequest.getQueryString());
+        logger.debug("STORING: " + redirectString);
+        session.setAttribute("login.target", redirectString);
+      }
+
+      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
+
+      return;
+    }
+
+    // If no module is specified goto standard startpage
+    if ((moduleName == null) || moduleName.equals("")) {
+      logger.debug("no module: redirect to standardpage");
+      _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
+
+      return;
+    }
+
+    // end of auth
+    // From now on regular dispatching...
+    try {
+      // get servletmodule by parameter and continue with dispacher
+      ServletModule smod = getServletModuleForName(moduleName);
+      ServletModuleDispatch.dispatch(smod, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      Throwable cause = ExceptionFunctions.traceCauseException(e);
+
+      if (cause instanceof ServletModuleUserExc)
+        handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
+      else
+        handleError(aRequest, aResponse, aResponse.getWriter(), cause);
+
+    }
+
+    // timing...
+    sessionConnectTime = System.currentTimeMillis() - startTime;
+    logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
+  }
+
+  /**
+   *  Private method getServletModuleForName returns ServletModule
+   *  from Cache
+   *
+   * @param moduleName
+   * @return ServletModule
+   *
+   */
+  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,
+                               PrintWriter out, Throwable anException) {
+    try {
+      logger.info("user error: " + anException.getMessage());
+      SimpleHash modelRoot = new SimpleHash();
+      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
+      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
+                                    modelRoot, out, aRequest.getLocale() );
+      out.close();
+    }
+    catch (Exception e) {
+      logger.error("Error in UserErrorTemplate");
+    }
+
+  }
+
+  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
+
+    try {
+      logger.error("error: " + anException);
+      SimpleHash modelRoot = new SimpleHash();
+      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
+      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
+                                               new GregorianCalendar())));
+      HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
+                                    modelRoot,out, aRequest.getLocale());
+      out.close();
+    }
+    catch (Exception e) {
+      logger.error("Error in ErrorTemplate");
+    }
+  }
+
+  /**
+   *  evaluate login for user / password
+   */
+  protected EntityUsers allowedUser(String user, String password) {
+    try {
+      if (usersModule == null) {
+        usersModule = new ModuleUsers(DatabaseUsers.getInstance());
+      }
+
+      return usersModule.getUserForLogin(user, password);
+    } catch (Exception e) {
+      logger.debug(e.getMessage());
+      e.printStackTrace();
+
+      return null;
+    }
+  }
+
+  // Redirect-methods
+  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
+    PrintWriter out) {
+    String loginTemplate = configuration.getString("Mir.LoginTemplate");
+    String sessionUrl = aResponse.encodeURL("");
+
+    try {
+      SimpleHash mergeData = new SimpleHash();
+      SimpleList languages = new SimpleList();
+
+      mergeData.put("session", sessionUrl);
+
+      mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
+      mergeData.put("languages", getLoginLanguages());
+
+      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,
+        getLocale(aRequest));
+    }
+    catch (Throwable e) {
+      handleError(aRequest, aResponse, out, e);
+    }
+  }
+
+  private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
+    PrintWriter out, EntityUsers userEntity) {
+    String startTemplate = "templates/admin/start_admin.template";
+    String sessionUrl = aResponse.encodeURL("");
+
+    try {
+      // merge with logged in user and messages
+      SimpleHash mergeData = new SimpleHash();
+      mergeData.put("session", sessionUrl);
+      mergeData.put("login_user", userEntity);
+
+      if (messageModule == null) {
+        messageModule = new ModuleMessage(DatabaseMessages.getInstance());
+      }
+
+      mergeData.put("messages",
+        messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
+
+      mergeData.put("articletypes",
+        DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
+
+      HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,
+        getLocale(aRequest));
+    }
+    catch (Exception e) {
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      handleError(aRequest, aResponse, out, e);
+    }
+  }
+
+  public String getServletInfo() {
+    return "Mir " + configuration.getString("Mir.Version");
+  }
+
+  private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
+    // a lang parameter always sets the language
+    String lang = aRequest.getParameter("language");
+
+    if (lang != null) {
+      logger.info("selected language " + lang + " overrides accept-language");
+      setLanguage(session, lang);
+      setLocale(session, new Locale(lang, ""));
+    }
+    // otherwise store language from accept header in session
+    else if (session.getAttribute("Language") == null) {
+      logger.info("accept-language is " + aRequest.getLocale().getLanguage());
+      setLanguage(session, aRequest.getLocale().getLanguage());
+      setLocale(session, aRequest.getLocale());
+    }
+  }
+}
index 3a0a5fa..7b54da2 100755 (executable)
@@ -44,11 +44,8 @@ import mir.misc.HTMLTemplateProcessor;
 import mir.misc.StringUtil;
 import mir.servlet.AbstractServlet;
 import mir.servlet.ServletModuleDispatch;
-import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleUserExc;
-import mir.servlet.ServletModuleFailure;
 import mir.util.ExceptionFunctions;
-
 import mircoders.servlet.ServletModuleOpenIndy;
 import freemarker.template.SimpleHash;
 import freemarker.template.SimpleScalar;
@@ -57,7 +54,7 @@ import freemarker.template.SimpleScalar;
  *  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.23 2003/03/07 00:50:22 zapata Exp $
+ *  @version $Id: OpenMir.java,v 1.24 2003/03/08 17:18:19 idfx Exp $
  *
  */
 
index 76bb151..a9dfd62 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mir.servlet;\r
-\r
-import java.io.IOException;\r
-import java.io.PrintWriter;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-\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.EntityList;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.HTMLParseException;\r
-import mir.misc.HTMLTemplateProcessor;\r
-import mir.misc.LineFilterWriter;\r
-import mir.module.AbstractModule;\r
-import mir.module.ModuleException;\r
-import mir.storage.StorageObject;\r
-import mir.util.HTTPRequestParser;\r
-import freemarker.template.SimpleHash;\r
-import freemarker.template.TemplateModelRoot;\r
-\r
-\r
-\r
-\r
-/**\r
- * Abstract class ServletModule provides the base functionality for servlets.\r
- * Deriving a class from ServletModule enables class to insert/edit/update/delete\r
- * and list Entity from a Database via mainModule.\r
- *\r
- *\r
- *  Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der\r
- *  abgeleiteten ServletModule zur Verf?gung.\r
- *\r
- * @version 28.6.1999\r
- * @author RK\r
- */\r
-\r
-public abstract class ServletModule {\r
-\r
-  public String defaultAction;\r
-  protected LoggerWrapper logger;\r
-  protected MirPropertiesConfiguration configuration;\r
-  protected AbstractModule mainModule;\r
-  protected String templateListString;\r
-  protected String templateObjektString;\r
-  protected String templateConfirmString;\r
-\r
-\r
-  public ServletModule(){\r
-    try {\r
-      configuration = MirPropertiesConfiguration.instance();\r
-    }\r
-    catch (PropertiesConfigExc e) {\r
-      throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden.\r
-   * @return ServletModule\r
-   */\r
-  public static ServletModule getInstance() {\r
-    return null;\r
-  }\r
-\r
-  /**\r
-   * get the module name to be used for generic operations like delete.\r
-   */\r
-  protected String getOperationModuleName() {\r
-    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());\r
-  }\r
-\r
-  /**\r
-   * get the session binded language\r
-   */\r
-  public String getLanguage(HttpServletRequest req) {\r
-    HttpSession session = req.getSession(false);\r
-    String language = (String) session.getAttribute("Language");\r
-    if (language == null) {\r
-      language = configuration.getString("StandardLanguage");\r
-    }\r
-    return language;\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 req) {\r
-    Locale loc = null;\r
-    HttpSession session = req.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 = req.getLocale();\r
-    }\r
-    return loc;\r
-  }\r
-\r
-  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
-    try {\r
-      aResponse.sendRedirect(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
-   *  list(req,res) - generische Listmethode. Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   *\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-  public void list(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
-    try {\r
-      EntityList theList;\r
-      String offsetParam = req.getParameter("offset");\r
-      int offset = 0;\r
-      PrintWriter out = res.getWriter();\r
-\r
-      // hier offsetcode bearbeiten\r
-      if (offsetParam != null && !offsetParam.equals("")) {\r
-        offset = Integer.parseInt(offsetParam);\r
-      }\r
-      if (req.getParameter("next") != null) {\r
-        offset = Integer.parseInt(req.getParameter("nextoffset"));\r
-      }\r
-      else {\r
-        if (req.getParameter("prev") != null) {\r
-          offset = Integer.parseInt(req.getParameter("prevoffset"));\r
-        }\r
-      }\r
-      theList = mainModule.getByWhereClause(null, offset);\r
-\r
-      HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req));\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  add(req,res) - generische Addmethode. Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-  public void add(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-\r
-    try {\r
-      SimpleHash mergeData = new SimpleHash();\r
-      mergeData.put("new", "1");\r
-      deliver(req, res, mergeData, templateObjektString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  insert(req,res) - generische Insertmethode, folgt auf add.\r
-   *  Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   *\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-  public void insert(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());\r
-      logger.debug("--trying to add...");\r
-      String id = mainModule.add(withValues);\r
-      logger.debug("--trying to deliver..." + id);\r
-      list(req, res);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  delete(req,res) - generic delete method. Can be overridden in subclasses.\r
-   *\r
-   */\r
-\r
-  public void delete(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      String idParam = req.getParameter("id");\r
-\r
-      if (idParam == null)\r
-        throw new ServletModuleExc("Invalid call to delete: no id supplied");\r
-\r
-      String confirmParam = req.getParameter("confirm");\r
-      String cancelParam = req.getParameter("cancel");\r
-      if (confirmParam == null && cancelParam == null) {\r
-        SimpleHash mergeData = new SimpleHash();\r
-\r
-        mergeData.put("module", getOperationModuleName());\r
-        mergeData.put("infoString", getOperationModuleName() + ": " + idParam);\r
-        mergeData.put("id", idParam);\r
-        mergeData.put("where", req.getParameter("where"));\r
-        mergeData.put("order", req.getParameter("order"));\r
-        mergeData.put("offset", req.getParameter("offset"));\r
-        // this stuff is to be compatible with the other more advanced\r
-        // search method used for media and comments\r
-        mergeData.put("query_media_folder", req.getParameter("query_media_folder"));\r
-        mergeData.put("query_is_published", req.getParameter("query_is_published"));\r
-        mergeData.put("query_text", req.getParameter("query_text"));\r
-        mergeData.put("query_field", req.getParameter("query_field"));\r
-\r
-        deliver(req, res, mergeData, templateConfirmString);\r
-      }\r
-      else {\r
-        if (confirmParam != null && !confirmParam.equals("")) {\r
-          //theLog.printInfo("delete confirmed!");\r
-          mainModule.deleteById(idParam);\r
-          list(req, res); // back to list\r
-        }\r
-        else {\r
-          if (req.getParameter("where") != null)\r
-            list(req, res);\r
-          else\r
-            edit(req, res);\r
-        }\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   *\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-  public void edit(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    edit(req, res, req.getParameter("id"));\r
-  }\r
-\r
-  /**\r
-   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   *\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   *  update(req,res) - generische Updatemethode. Wennn die Funktionalitaet\r
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse\r
-   *  ueberschreiben werden.\r
-   *\r
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   */\r
-\r
-  public void update(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
-    try {\r
-      String idParam = req.getParameter("id");\r
-      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());\r
-\r
-      String id = mainModule.set(withValues);\r
-      String whereParam = req.getParameter("where");\r
-      String orderParam = req.getParameter("order");\r
-\r
-      if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) {\r
-        list(req, res);\r
-      }\r
-      else {\r
-        edit(req, res);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * deliver liefert das Template mit dem Filenamen templateFilename\r
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus\r
-   * TemplateModelRoot rtm gemischt wurde\r
-   *\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den\r
-   *   Daten, die ins Template gemerged werden sollen.\r
-   * @param tmpl Name des Templates\r
-   * @exception ServletModuleException\r
-   */\r
-  public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm,\r
-         TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure  {\r
-    if (rtm == null)\r
-      rtm = new SimpleHash();\r
-\r
-    try {\r
-      PrintWriter out = res.getWriter();\r
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req));\r
-\r
-      // we default to admin bundles here, which is not exactly beautiful...\r
-      // but this whole producer stuff is going to be rewritten soon.\r
-      // ServletModuleOpenIndy overwrites deliver() to use open bundles\r
-      // (br1)\r
-      out.close();\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   * deliver liefert das Template mit dem Filenamen templateFilename\r
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus\r
-   * TemplateModelRoot rtm gemischt wurde\r
-   *\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den\r
-   *   Daten, die ins Template gemerged werden sollen.\r
-   * @param tmpl Name des Templates\r
-   * @exception ServletModuleException\r
-   */\r
-  public void deliver(HttpServletRequest req, HttpServletResponse res,\r
-        TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure {\r
-    deliver(req, res, rtm, null, templateFilename);\r
-  }\r
-\r
-  /**\r
-   * deliver liefert das Template mit dem Filenamen templateFilename\r
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus\r
-   * TemplateModelRoot rtm gemischt wurde\r
-   *\r
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird\r
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den\r
-   *   Daten, die ins Template gemerged werden sollen.\r
-   * @param tmpl Name des Templates\r
-   * @exception ServletModuleException\r
-   */\r
-  public void deliver_compressed(HttpServletRequest req, HttpServletResponse res,\r
-                                 TemplateModelRoot rtm, String templateFilename)\r
-      throws ServletModuleFailure {\r
-    if (rtm == null) rtm = new SimpleHash();\r
-    try {\r
-      PrintWriter out = new LineFilterWriter(res.getWriter());\r
-      //PrintWriter out =  res.getWriter();\r
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));\r
-      out.close();\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  /**\r
-   * deliver liefert das Template mit dem Filenamen templateFilename\r
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus\r
-   * TemplateModelRoot rtm gemischt wurde\r
-   *\r
-   * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen.\r
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den\r
-   *   Daten, die ins Template gemerged werden sollen.\r
-   * @param tmpl Name des Templates\r
-   * @exception ServletModuleException\r
-   */\r
-  private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out,\r
-                       TemplateModelRoot rtm, String templateFilename)\r
-      throws ServletModuleFailure {\r
-    try {\r
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, out,\r
-                                    getLocale(req));\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 req, StorageObject theStorage)\r
-      throws ServletModuleExc, ServletModuleFailure {\r
-\r
-    try {\r
-      HTTPRequestParser parser;\r
-      List theFieldList;\r
-\r
-      logger.debug("using charset: " + req.getParameter("charset"));\r
-      logger.debug("using method: " + req.getParameter("do"));\r
-      if (req.getParameter("charset") != null) {\r
-        parser = new HTTPRequestParser(req, req.getParameter("charset"));\r
-        logger.debug("using charset: " + req.getParameter("charset"));\r
-        logger.debug("original charset: " + req.getCharacterEncoding());\r
-      }\r
-      else {\r
-        parser = new HTTPRequestParser(req);\r
-      }\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
-        logger.debug("field " + aField + " = " + parser.getParameter(aField));\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
-\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 the com.oreilly.servlet library, 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.PrintWriter;
+import java.util.HashMap;
+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.EntityList;
+import mir.log.LoggerWrapper;
+import mir.misc.HTMLTemplateProcessor;
+import mir.misc.LineFilterWriter;
+import mir.module.AbstractModule;
+import mir.storage.StorageObject;
+import mir.util.HTTPRequestParser;
+import freemarker.template.SimpleHash;
+import freemarker.template.TemplateModelRoot;
+
+
+
+
+/**
+ * Abstract class ServletModule provides the base functionality for servlets.
+ * Deriving a class from ServletModule enables class to insert/edit/update/delete
+ * and list Entity from a Database via mainModule.
+ *
+ *
+ *  Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der
+ *  abgeleiteten ServletModule zur Verf?gung.
+ *
+ * @version 28.6.1999
+ * @author RK
+ */
+
+public abstract class ServletModule {
+
+  public String defaultAction;
+  protected LoggerWrapper logger;
+  protected MirPropertiesConfiguration configuration;
+  protected AbstractModule mainModule;
+  protected String templateListString;
+  protected String templateObjektString;
+  protected String templateConfirmString;
+
+
+  public ServletModule(){
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+    }
+    catch (PropertiesConfigExc e) {
+      throw new RuntimeException("Can't get configuration: " + e.getMessage());
+    }
+  }
+
+
+  /**
+   * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden.
+   * @return ServletModule
+   */
+  public static ServletModule getInstance() {
+    return null;
+  }
+
+  /**
+   * get the module name to be used for generic operations like delete.
+   */
+  protected String getOperationModuleName() {
+    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
+  }
+
+  /**
+   * get the session binded language
+   */
+  public String getLanguage(HttpServletRequest req) {
+    HttpSession session = req.getSession(false);
+    String language = (String) session.getAttribute("Language");
+    if (language == null) {
+      language = configuration.getString("StandardLanguage");
+    }
+    return language;
+  }
+
+  /**
+   * 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 req) {
+    Locale loc = null;
+    HttpSession session = req.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 = req.getLocale();
+    }
+    return loc;
+  }
+
+  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {
+    try {
+      aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);
+    }
+  }
+
+  /**
+   *  list(req,res) - generische Listmethode. Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   *
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+  public void list(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+    try {
+      EntityList theList;
+      String offsetParam = req.getParameter("offset");
+      int offset = 0;
+      PrintWriter out = res.getWriter();
+
+      // hier offsetcode bearbeiten
+      if (offsetParam != null && !offsetParam.equals("")) {
+        offset = Integer.parseInt(offsetParam);
+      }
+      if (req.getParameter("next") != null) {
+        offset = Integer.parseInt(req.getParameter("nextoffset"));
+      }
+      else {
+        if (req.getParameter("prev") != null) {
+          offset = Integer.parseInt(req.getParameter("prevoffset"));
+        }
+      }
+      theList = mainModule.getByWhereClause(null, offset);
+
+      HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req));
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *  add(req,res) - generische Addmethode. Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+  public void add(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+
+    try {
+      SimpleHash mergeData = new SimpleHash();
+      mergeData.put("new", "1");
+      deliver(req, res, mergeData, templateObjektString);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *  insert(req,res) - generische Insertmethode, folgt auf add.
+   *  Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   *
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+  public void insert(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());
+      logger.debug("--trying to add...");
+      String id = mainModule.add(withValues);
+      logger.debug("--trying to deliver..." + id);
+      list(req, res);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *  delete(req,res) - generic delete method. Can be overridden in subclasses.
+   *
+   */
+
+  public void delete(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      String idParam = req.getParameter("id");
+
+      if (idParam == null)
+        throw new ServletModuleExc("Invalid call to delete: no id supplied");
+
+      String confirmParam = req.getParameter("confirm");
+      String cancelParam = req.getParameter("cancel");
+      if (confirmParam == null && cancelParam == null) {
+        SimpleHash mergeData = new SimpleHash();
+
+        mergeData.put("module", getOperationModuleName());
+        mergeData.put("infoString", getOperationModuleName() + ": " + idParam);
+        mergeData.put("id", idParam);
+        mergeData.put("where", req.getParameter("where"));
+        mergeData.put("order", req.getParameter("order"));
+        mergeData.put("offset", req.getParameter("offset"));
+        // this stuff is to be compatible with the other more advanced
+        // search method used for media and comments
+        mergeData.put("query_media_folder", req.getParameter("query_media_folder"));
+        mergeData.put("query_is_published", req.getParameter("query_is_published"));
+        mergeData.put("query_text", req.getParameter("query_text"));
+        mergeData.put("query_field", req.getParameter("query_field"));
+
+        deliver(req, res, mergeData, templateConfirmString);
+      }
+      else {
+        if (confirmParam != null && !confirmParam.equals("")) {
+          //theLog.printInfo("delete confirmed!");
+          mainModule.deleteById(idParam);
+          list(req, res); // back to list
+        }
+        else {
+          if (req.getParameter("where") != null)
+            list(req, res);
+          else
+            edit(req, res);
+        }
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   *
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+  public void edit(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    edit(req, res, req.getParameter("id"));
+  }
+
+  /**
+   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   *
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   *  update(req,res) - generische Updatemethode. Wennn die Funktionalitaet
+   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
+   *  ueberschreiben werden.
+   *
+   * @param req Http-Request, das vom Dispatcher durchgereicht wird
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   */
+
+  public void update(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
+    try {
+      String idParam = req.getParameter("id");
+      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());
+
+      String id = mainModule.set(withValues);
+      String whereParam = req.getParameter("where");
+      String orderParam = req.getParameter("order");
+
+      if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) {
+        list(req, res);
+      }
+      else {
+        edit(req, res);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * deliver liefert das Template mit dem Filenamen templateFilename
+   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
+   * TemplateModelRoot rtm gemischt wurde
+   *
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
+   * @param tmpl Name des Templates
+   * @exception ServletModuleException
+   */
+  public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm,
+         TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure  {
+    if (rtm == null)
+      rtm = new SimpleHash();
+
+    try {
+      PrintWriter out = res.getWriter();
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req));
+
+      // we default to admin bundles here, which is not exactly beautiful...
+      // but this whole producer stuff is going to be rewritten soon.
+      // ServletModuleOpenIndy overwrites deliver() to use open bundles
+      // (br1)
+      out.close();
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+
+  /**
+   * deliver liefert das Template mit dem Filenamen templateFilename
+   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
+   * TemplateModelRoot rtm gemischt wurde
+   *
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
+   * @param tmpl Name des Templates
+   * @exception ServletModuleException
+   */
+  public void deliver(HttpServletRequest req, HttpServletResponse res,
+        TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure {
+    deliver(req, res, rtm, null, templateFilename);
+  }
+
+  /**
+   * deliver liefert das Template mit dem Filenamen templateFilename
+   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
+   * TemplateModelRoot rtm gemischt wurde
+   *
+   * @param res Http-Response, die vom Dispatcher durchgereicht wird
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
+   * @param tmpl Name des Templates
+   * @exception ServletModuleException
+   */
+  public void deliver_compressed(HttpServletRequest req, HttpServletResponse res,
+                                 TemplateModelRoot rtm, String templateFilename)
+      throws ServletModuleFailure {
+    if (rtm == null) rtm = new SimpleHash();
+    try {
+      PrintWriter out = new LineFilterWriter(res.getWriter());
+      //PrintWriter out =  res.getWriter();
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req));
+      out.close();
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * deliver liefert das Template mit dem Filenamen templateFilename
+   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
+   * TemplateModelRoot rtm gemischt wurde
+   *
+   * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen.
+   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
+   *   Daten, die ins Template gemerged werden sollen.
+   * @param tmpl Name des Templates
+   * @exception ServletModuleException
+   */
+  private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out,
+                       TemplateModelRoot rtm, String templateFilename)
+      throws ServletModuleFailure {
+    try {
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, out,
+                                    getLocale(req));
+    }
+    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 req, StorageObject theStorage)
+      throws ServletModuleExc, ServletModuleFailure {
+
+    try {
+      HTTPRequestParser parser;
+      List theFieldList;
+
+      logger.debug("using charset: " + req.getParameter("charset"));
+      logger.debug("using method: " + req.getParameter("do"));
+      if (req.getParameter("charset") != null) {
+        parser = new HTTPRequestParser(req, req.getParameter("charset"));
+        logger.debug("using charset: " + req.getParameter("charset"));
+        logger.debug("original charset: " + req.getCharacterEncoding());
+      }
+      else {
+        parser = new HTTPRequestParser(req);
+      }
+
+      theFieldList = theStorage.getFields();
+
+      Map withValues = new HashMap();
+      String aField, aValue;
+
+      for (int i = 0; i < theFieldList.size(); i++) {
+        aField = (String) theFieldList.get(i);
+
+        logger.debug("field " + aField + " = " + parser.getParameter(aField));
+
+        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);
+    }
+  }
+
+}
index 5c06501..cd6459f 100755 (executable)
 
 package mir.util;
 
+import java.lang.reflect.InvocationTargetException;
+
 import multex.Failure;
+
 import org.xml.sax.SAXException;
-import java.lang.reflect.InvocationTargetException;
 
 /**
  *
index 6ab1d15..ea96e81 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.entity;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.sql.Connection;\r
-import java.sql.PreparedStatement;\r
-import java.sql.ResultSet;\r
-import java.sql.SQLException;\r
-import java.sql.Statement;\r
-\r
-import org.postgresql.largeobject.BlobInputStream;\r
-import org.postgresql.largeobject.LargeObject;\r
-import org.postgresql.largeobject.LargeObjectManager;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.misc.FileUtil;\r
-import mir.misc.WebdbImage;\r
-import mir.log.LoggerWrapper;\r
-import mir.storage.StorageObject;\r
-import mir.storage.StorageObjectFailure;\r
-\r
-/**\r
- * Diese Klasse enth?lt die Daten eines MetaObjekts\r
- *\r
- * @author RK, mh, mir-coders\r
- * @version $Id: EntityImages.java,v 1.18 2003/03/08 05:50:42 zapata Exp $\r
- */\r
-\r
-\r
-public class EntityImages extends EntityUploadedMedia\r
-{\r
-\r
-  public EntityImages()\r
-  {\r
-    super();\r
-\r
-    logger = new LoggerWrapper("Entity.UploadedMedia.Images");\r
-  }\r
-\r
-  public EntityImages(StorageObject theStorage) {\r
-    this();\r
-    setStorage(theStorage);\r
-  }\r
-\r
-  //\r
-  // methods\r
-\r
-\r
-  public InputStream getImage() throws StorageObjectFailure {\r
-    logger.debug("EntityImages.getimage started");\r
-    java.sql.Connection con=null;\r
-    Statement stmt=null;\r
-    BlobInputStream in;\r
-    InputStream img_in = null;\r
-    try {\r
-      con = theStorageObject.getPooledCon();\r
-      con.setAutoCommit(false);\r
-      LargeObjectManager lom;\r
-      java.sql.Connection jCon;\r
-      stmt = con.createStatement();\r
-      ResultSet rs = theStorageObject.executeSql(stmt,\r
-          "select image_data from images where id="+getId());\r
-      jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)\r
-           .getNativeConnection();\r
-      lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();\r
-      if(rs!=null) {\r
-        if (rs.next()) {\r
-          LargeObject lob = lom.open(rs.getInt(1));\r
-          in = (BlobInputStream)lob.getInputStream();\r
-          img_in = new ImageInputStream(in, con, stmt);\r
-        }\r
-        rs.close();\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      logger.error("EntityImages.getImage failed: " + t.toString());\r
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-\r
-      try {\r
-        con.setAutoCommit(true);\r
-      }\r
-      catch (Throwable e) {\r
-        logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());\r
-        e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      }\r
-\r
-      try {\r
-        theStorageObject.freeConnection(con, stmt);\r
-      }\r
-      catch (Throwable e) {\r
-        logger.error("EntityImages.getImage freeing connection failed: " +e.toString());\r
-      }\r
-\r
-      throwStorageObjectFailure(t, "EntityImages -- getImage failed: ");\r
-    }\r
-    return img_in;\r
-  }\r
-\r
-  public void setImage(InputStream in, String type)\r
-        throws StorageObjectFailure {\r
-\r
-    if (in != null) {\r
-      Connection con = null;\r
-      PreparedStatement pstmt = null;\r
-      File f = null;\r
-      try {\r
-        logger.debug("EntityImages.settimage :: making internal representation of image");\r
-\r
-        File tempDir = new File(MirPropertiesConfiguration.instance().getString("TempDir"));\r
-        f = File.createTempFile("mir", ".tmp", tempDir);\r
-        FileUtil.write(f, in);\r
-        WebdbImage webdbImage= new WebdbImage(f, type);\r
-        logger.debug("EntityImages.settimage :: made internal representation of image");\r
-\r
-        con = theStorageObject.getPooledCon();\r
-        con.setAutoCommit(false);\r
-        logger.debug("EntityImages.settimage :: trying to insert image");\r
-\r
-        // setting values\r
-        LargeObjectManager lom;\r
-        java.sql.Connection jCon;\r
-        jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)\r
-             .getNativeConnection();\r
-\r
-        lom = ((org.postgresql.Connection) jCon).getLargeObjectAPI();\r
-\r
-        int oidImage = lom.create();\r
-        int oidIcon = lom.create();\r
-        LargeObject lobImage = lom.open(oidImage);\r
-        LargeObject lobIcon = lom.open(oidIcon);\r
-        webdbImage.setImage(lobImage.getOutputStream());\r
-        webdbImage.setIcon(lobIcon.getOutputStream());\r
-        lobImage.close();\r
-        lobIcon.close();\r
-\r
-        setValueForProperty("img_height", new Integer(webdbImage.getImageHeight()).toString());\r
-        setValueForProperty("img_width", new Integer(webdbImage.getImageWidth()).toString());\r
-        setValueForProperty("icon_height", new Integer(webdbImage.getIconHeight()).toString());\r
-        setValueForProperty("icon_width", new Integer(webdbImage.getIconWidth()).toString());\r
-        setValueForProperty("image_data", new Integer(oidImage).toString());\r
-        setValueForProperty("icon_data", new Integer(oidIcon).toString());\r
-        update();\r
-      } catch (Exception e) {\r
-        throwStorageObjectFailure(e, "settimage :: setImage gescheitert: ");\r
-      } finally {\r
-        try {\r
-          if (con!=null)\r
-            con.setAutoCommit(true);\r
-          // get rid of the temp. file\r
-          f.delete();\r
-        } catch (SQLException e) {\r
-          throwStorageObjectFailure(e,"Resetting transaction-mode failed");\r
-        }\r
-        if (con!=null)\r
-          theStorageObject.freeConnection(con,pstmt);\r
-      }\r
-    }\r
-  }\r
-\r
-  /**\r
-   * Takes an OutputStream as an argument and reads in the data\r
-   * from the DB and writes it to the OutputStream.\r
-   *\r
-   * It will also take care of closing the OutputStream.\r
-   */\r
-  public InputStream getIcon() throws StorageObjectFailure {\r
-    Connection con=null;\r
-    Statement stmt=null;\r
-    BlobInputStream in=null;\r
-    ImageInputStream img_in=null;\r
-\r
-    try {\r
-      con = theStorageObject.getPooledCon();\r
-      con.setAutoCommit(false);\r
-      LargeObjectManager lom;\r
-      java.sql.Connection jCon;\r
-      stmt = con.createStatement();\r
-      ResultSet rs = theStorageObject.executeSql(stmt, "select icon_data from images where id="+getId());\r
-      jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)\r
-           .getNativeConnection();\r
-      lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();\r
-      if(rs!=null) {\r
-        if (rs.next()) {\r
-          LargeObject lob = lom.open(rs.getInt(1));\r
-          in = (BlobInputStream)lob.getInputStream();\r
-          img_in = new ImageInputStream( in, con ,stmt);\r
-          //img_data = rs.getBytes(1);\r
-        }\r
-        rs.close();\r
-      }\r
-    }\r
-    catch (Throwable t) {\r
-      logger.error("EntityImages.getIcon failed: "+t.toString());\r
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-\r
-      try {\r
-        con.setAutoCommit(true);\r
-      }\r
-      catch (SQLException e) {\r
-        logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString());\r
-        e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-      }\r
-      try {\r
-        theStorageObject.freeConnection(con, stmt);\r
-      }\r
-      catch (Throwable e) {\r
-       logger.error("EntityImages -- freeing connection failed: " + e.getMessage());\r
-      }\r
-\r
-      throwStorageObjectFailure(t, "EntityImages -- getIcon failed:");\r
-    }\r
-\r
-    return img_in;\r
-  }\r
-\r
-  /**\r
-   * a small wrapper class that allows us to store the DB connection resources\r
-   * that the BlobInputStream is using and free them upon closing of the stream\r
-   */\r
-  private class ImageInputStream extends InputStream {\r
-\r
-    InputStream _in;\r
-    Connection _con;\r
-    Statement _stmt;\r
-\r
-    public ImageInputStream(BlobInputStream in, Connection con,\r
-                            Statement stmt ) {\r
-      _in = in;\r
-      _con = con;\r
-      _stmt = stmt;\r
-    }\r
-\r
-    public void close () throws IOException {\r
-      _in.close();\r
-      try {\r
-        _con.setAutoCommit(true);\r
-        theStorageObject.freeConnection(_con,_stmt);\r
-      } catch (Exception e) {\r
-        throw new IOException("close(): "+e.toString());\r
-      }\r
-    }\r
-\r
-    public int read() throws IOException {\r
-      return _in.read();\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 the com.oreilly.servlet library, 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.entity;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
+import mir.misc.FileUtil;
+import mir.misc.WebdbImage;
+import mir.storage.StorageObject;
+import mir.storage.StorageObjectFailure;
+
+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.19 2003/03/08 17:18:19 idfx Exp $
+ */
+
+
+public class EntityImages extends EntityUploadedMedia
+{
+
+  public EntityImages()
+  {
+    super();
+
+    logger = new LoggerWrapper("Entity.UploadedMedia.Images");
+  }
+
+  public EntityImages(StorageObject theStorage) {
+    this();
+    setStorage(theStorage);
+  }
+
+  //
+  // methods
+
+
+  public InputStream getImage() throws StorageObjectFailure {
+    logger.debug("EntityImages.getimage started");
+    java.sql.Connection con=null;
+    Statement stmt=null;
+    BlobInputStream in;
+    InputStream img_in = null;
+    try {
+      con = theStorageObject.getPooledCon();
+      con.setAutoCommit(false);
+      LargeObjectManager lom;
+      java.sql.Connection jCon;
+      stmt = con.createStatement();
+      ResultSet rs = theStorageObject.executeSql(stmt,
+          "select image_data from images where id="+getId());
+      jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+           .getNativeConnection();
+      lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+      if(rs!=null) {
+        if (rs.next()) {
+          LargeObject lob = lom.open(rs.getInt(1));
+          in = (BlobInputStream)lob.getInputStream();
+          img_in = new ImageInputStream(in, con, stmt);
+        }
+        rs.close();
+      }
+    }
+    catch (Throwable t) {
+      logger.error("EntityImages.getImage failed: " + t.toString());
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+
+      try {
+        con.setAutoCommit(true);
+      }
+      catch (Throwable e) {
+        logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
+        e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      }
+
+      try {
+        theStorageObject.freeConnection(con, stmt);
+      }
+      catch (Throwable e) {
+        logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
+      }
+
+      throwStorageObjectFailure(t, "EntityImages -- getImage failed: ");
+    }
+    return img_in;
+  }
+
+  public void setImage(InputStream in, String type)
+        throws StorageObjectFailure {
+
+    if (in != null) {
+      Connection con = null;
+      PreparedStatement pstmt = null;
+      File f = null;
+      try {
+        logger.debug("EntityImages.settimage :: making internal representation of image");
+
+        File tempDir = new File(MirPropertiesConfiguration.instance().getString("TempDir"));
+        f = File.createTempFile("mir", ".tmp", tempDir);
+        FileUtil.write(f, in);
+        WebdbImage webdbImage= new WebdbImage(f, type);
+        logger.debug("EntityImages.settimage :: made internal representation of image");
+
+        con = theStorageObject.getPooledCon();
+        con.setAutoCommit(false);
+        logger.debug("EntityImages.settimage :: trying to insert image");
+
+        // setting values
+        LargeObjectManager lom;
+        java.sql.Connection jCon;
+        jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+             .getNativeConnection();
+
+        lom = ((org.postgresql.Connection) jCon).getLargeObjectAPI();
+
+        int oidImage = lom.create();
+        int oidIcon = lom.create();
+        LargeObject lobImage = lom.open(oidImage);
+        LargeObject lobIcon = lom.open(oidIcon);
+        webdbImage.setImage(lobImage.getOutputStream());
+        webdbImage.setIcon(lobIcon.getOutputStream());
+        lobImage.close();
+        lobIcon.close();
+
+        setValueForProperty("img_height", new Integer(webdbImage.getImageHeight()).toString());
+        setValueForProperty("img_width", new Integer(webdbImage.getImageWidth()).toString());
+        setValueForProperty("icon_height", new Integer(webdbImage.getIconHeight()).toString());
+        setValueForProperty("icon_width", new Integer(webdbImage.getIconWidth()).toString());
+        setValueForProperty("image_data", new Integer(oidImage).toString());
+        setValueForProperty("icon_data", new Integer(oidIcon).toString());
+        update();
+      } catch (Exception e) {
+        throwStorageObjectFailure(e, "settimage :: setImage gescheitert: ");
+      } finally {
+        try {
+          if (con!=null)
+            con.setAutoCommit(true);
+          // get rid of the temp. file
+          f.delete();
+        } catch (SQLException e) {
+          throwStorageObjectFailure(e,"Resetting transaction-mode failed");
+        }
+        if (con!=null)
+          theStorageObject.freeConnection(con,pstmt);
+      }
+    }
+  }
+
+  /**
+   * Takes an OutputStream as an argument and reads in the data
+   * from the DB and writes it to the OutputStream.
+   *
+   * It will also take care of closing the OutputStream.
+   */
+  public InputStream getIcon() throws StorageObjectFailure {
+    Connection con=null;
+    Statement stmt=null;
+    BlobInputStream in=null;
+    ImageInputStream img_in=null;
+
+    try {
+      con = theStorageObject.getPooledCon();
+      con.setAutoCommit(false);
+      LargeObjectManager lom;
+      java.sql.Connection jCon;
+      stmt = con.createStatement();
+      ResultSet rs = theStorageObject.executeSql(stmt, "select icon_data from images where id="+getId());
+      jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+           .getNativeConnection();
+      lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+      if(rs!=null) {
+        if (rs.next()) {
+          LargeObject lob = lom.open(rs.getInt(1));
+          in = (BlobInputStream)lob.getInputStream();
+          img_in = new ImageInputStream( in, con ,stmt);
+          //img_data = rs.getBytes(1);
+        }
+        rs.close();
+      }
+    }
+    catch (Throwable t) {
+      logger.error("EntityImages.getIcon failed: "+t.toString());
+      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+
+      try {
+        con.setAutoCommit(true);
+      }
+      catch (SQLException e) {
+        logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString());
+        e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      }
+      try {
+        theStorageObject.freeConnection(con, stmt);
+      }
+      catch (Throwable e) {
+       logger.error("EntityImages -- freeing connection failed: " + e.getMessage());
+      }
+
+      throwStorageObjectFailure(t, "EntityImages -- getIcon failed:");
+    }
+
+    return img_in;
+  }
+
+  /**
+   * a small wrapper class that allows us to store the DB connection resources
+   * that the BlobInputStream is using and free them upon closing of the stream
+   */
+  private class ImageInputStream extends InputStream {
+
+    InputStream _in;
+    Connection _con;
+    Statement _stmt;
+
+    public ImageInputStream(BlobInputStream in, Connection con,
+                            Statement stmt ) {
+      _in = in;
+      _con = con;
+      _stmt = stmt;
+    }
+
+    public void close () throws IOException {
+      _in.close();
+      try {
+        _con.setAutoCommit(true);
+        theStorageObject.freeConnection(_con,_stmt);
+      } catch (Exception e) {
+        throw new IOException("close(): "+e.toString());
+      }
+    }
+
+    public int read() throws IOException {
+      return _in.read();
+    }
+  }
+}
index 3579184..89a8bf0 100755 (executable)
 
 package mircoders.module;
 
-import java.io.PrintWriter;
 import java.util.Map;
 
 import mir.entity.Entity;
-import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.module.AbstractModule;
 import mir.module.ModuleException;
@@ -104,7 +102,7 @@ public class ModuleComment extends AbstractModule
     }
     catch (StorageObjectFailure e){
       logger.error("ModuleComment.set: " + e.getMessage());
-      e.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
 
       throw new ModuleException(e.toString());
     } catch (StorageObjectExc e) {
index 74e20ab..79dc550 100755 (executable)
  */
 package mircoders.producer;
 
-import java.io.PrintWriter;
 import java.util.Map;
 
 import mir.entity.Entity;
 import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.misc.StringUtil;
 import mir.producer.ProducerFailure;
@@ -168,7 +166,7 @@ public class IndexingProducerNode implements ProducerNode {
     }
     catch (Throwable t) {
       aLogger.error("Error while indexing content: " + t.getMessage());
-      t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE));
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
     }
     finally {
       if (indexWriter != null) {
index 82327ee..d58add9 100755 (executable)
@@ -71,7 +71,7 @@ public class PDFGeneratingProducerNode implements ProducerNode {
 
     }
     catch (Throwable t) {
-      t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE));
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
       aLogger.error("  error while generating: " + t.getMessage() + t.toString());
     }
     endTime = System.currentTimeMillis();
index 05ec425..35da0bc 100755 (executable)
 
 package mircoders.producer;
 
-import java.io.PrintWriter;
 import java.util.Map;
 
 import mir.entity.Entity;
 import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.producer.ProducerFailure;
 import mir.producer.ProducerNode;
@@ -84,7 +82,7 @@ public class UnIndexingProducerNode implements ProducerNode {
     }
     catch (Throwable t) {
       aLogger.error("Error while unindexing content: " + t.getMessage());
-      t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE));
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
     }
 
     endTime = System.currentTimeMillis();
index a294cce..c07d68b 100755 (executable)
@@ -9,9 +9,9 @@ import mir.entity.adapter.EntityIteratorAdapter;
 import mir.generator.Generator;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
+import mir.util.CachingRewindableIterator;
 import mir.util.NullWriter;
 import mir.util.ResourceBundleGeneratorFunction;
-import mir.util.CachingRewindableIterator;
 import mircoders.global.MirGlobal;
 
 import org.apache.struts.util.MessageResources;
index 88b119d..eb4ae4d 100755 (executable)
 
 package mircoders.servlet;
 
-import java.io.PrintWriter;
 import java.util.Map;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleFailure;
index 0b057a9..b752549 100755 (executable)
@@ -31,7 +31,6 @@
 
 package mircoders.servlet;
 
-import java.io.IOException;
 import java.net.URLEncoder;
 
 import javax.servlet.http.HttpServletRequest;
@@ -41,7 +40,6 @@ import mir.config.MirPropertiesConfiguration;
 import mir.entity.EntityList;
 import mir.log.LoggerWrapper;
 import mir.misc.HTMLTemplateProcessor;
-import mir.module.ModuleException;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleFailure;
 import mircoders.module.ModuleBreaking;
index 1e1c652..510b984 100755 (executable)
@@ -31,7 +31,6 @@
 
 package mircoders.servlet;
 
-import java.io.PrintWriter;
 import java.util.Map;
 
 import javax.servlet.http.HttpServletRequest;
@@ -40,7 +39,6 @@ import javax.servlet.http.HttpServletResponse;
 import mir.config.MirPropertiesConfiguration;
 import mir.entity.adapter.EntityAdapterModel;
 import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleExc;
index 0300a58..0c5954e 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.servlet;\r
-\r
-import java.io.IOException;\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 javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\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.module.ModuleException;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleUserExc;\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 mir.util.SQLQueryBuilder;\r
-import mir.util.URLBuilder;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.search.IndexUtil;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-\r
-import org.apache.lucene.index.IndexReader;\r
-\r
-import freemarker.template.SimpleHash;\r
-\r
-/*\r
- *  ServletModuleContent -\r
- *  deliver html for the article admin form.\r
- *\r
- * @version $Id: ServletModuleContent.java,v 1.40 2003/03/06 05:40:40 zapata Exp $\r
- * @author rk, mir-coders\r
- *\r
- */\r
-\r
-public class ServletModuleContent extends ServletModule\r
-{\r
-  private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;\r
-  private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");\r
-\r
-  private static ServletModuleContent instance = new ServletModuleContent();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleContent() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Content");\r
-    try {\r
-\r
-      templateListString = configuration.getString("ServletModule.Content.ListTemplate");\r
-      templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");\r
-      templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");\r
-\r
-      mainModule = new ModuleContent(DatabaseContent.getInstance());\r
-    }\r
-    catch (StorageObjectFailure e) {\r
-      logger.error("servletmodulecontent konnte nicht initialisiert werden");\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
-    returnArticleList(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("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.appendAscendingOrder("webdb_create");\r
-        else if (searchOrder.equals("dateasc"))\r
-          queryBuilder.appendDescendingOrder("webdb_create");\r
-        else if (searchOrder.equals("title"))\r
-          queryBuilder.appendDescendingOrder("title");\r
-        else if (searchOrder.equals("creator"))\r
-          queryBuilder.appendDescendingOrder("creator");\r
-      }\r
-\r
-      returnArticleList(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 req, HttpServletResponse res) throws ServletModuleExc {\r
-    _showObject(null, req, res);\r
-  }\r
-\r
-\r
-  public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-//theLog.printDebugInfo(":: content :: trying to insert");\r
-    try {\r
-      EntityUsers   user = _getUser(req);\r
-      Map withValues = getIntersectingValues(req, 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", user.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 id = mainModule.add(withValues);\r
-      DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));\r
-\r
-      _showObject(id, req, res);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    EntityUsers   user = _getUser(req);\r
-\r
-    String idParam = req.getParameter("id");\r
-    if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");\r
-\r
-    String confirmParam = req.getParameter("confirm");\r
-    String cancelParam = req.getParameter("cancel");\r
-\r
-    logger.info("where = " + req.getParameter("where"));\r
-\r
-    if (confirmParam == null && cancelParam == null) {\r
-\r
-      SimpleHash mergeData = new SimpleHash();\r
-      mergeData.put("module", "Content");\r
-      mergeData.put("infoString", "Content: " + idParam);\r
-      mergeData.put("id", idParam);\r
-      mergeData.put("where", req.getParameter("where"));\r
-      mergeData.put("order", req.getParameter("order"));\r
-      mergeData.put("offset", req.getParameter("offset"));\r
-      deliver(req, res, mergeData, templateConfirmString);\r
-    }\r
-    else {\r
-      if (confirmParam!= null && !confirmParam.equals("")) {\r
-        try {\r
-          mainModule.deleteById(idParam);\r
-\r
-          /** @todo the following two should be implied in\r
-           *  DatabaseContent */\r
-\r
-          //delete rows in the content_x_topic-table\r
-          DatabaseContentToTopics.getInstance().deleteByContentId(idParam);\r
-          //delete rows in the comment-table\r
-          DatabaseComment.getInstance().deleteByContentId(idParam);\r
-          //delete from lucene index, if any\r
-          String index = configuration.getString("IndexPath");\r
-          if (IndexReader.indexExists(index)){\r
-            IndexUtil.unindexID(idParam,index);\r
-          }\r
-\r
-        }\r
-        catch (Throwable e) {\r
-          throw new ServletModuleFailure(e);\r
-        }\r
-        list(req,res);\r
-      }\r
-      else {\r
-        // Datensatz anzeigen\r
-        _showObject(idParam, req, res);\r
-      }\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String idParam = req.getParameter("id");\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("Invalid call: id not supplied ");\r
-    _showObject(idParam, req, res);\r
-  }\r
-\r
-// methods for attaching media file\r
-  public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String  mediaIdParam = req.getParameter("mid");\r
-    String  idParam = req.getParameter("cid");\r
-    if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing");\r
-\r
-    try {\r
-      EntityContent entContent = (EntityContent)mainModule.getById(idParam);\r
-      entContent.attach(mediaIdParam);\r
-    }\r
-    catch(ModuleException e) {\r
-      logger.error("smod content :: attach :: could not get entityContent");\r
-    }\r
-    catch(StorageObjectFailure e) {\r
-      logger.error("smod content :: attach :: could not get entityContent");\r
-    }\r
-\r
-    _showObject(idParam, req, res);\r
-  }\r
-\r
-  public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String  cidParam = req.getParameter("cid");\r
-    String  midParam = req.getParameter("mid");\r
-    if (cidParam == null)\r
-      throw new ServletModuleExc("smod content :: dettach :: cid missing");\r
-    if (midParam == null)\r
-      throw new ServletModuleExc("smod content :: dettach :: mid missing");\r
-\r
-    try {\r
-      EntityContent entContent = (EntityContent)mainModule.getById(cidParam);\r
-      entContent.dettach(cidParam,midParam);\r
-    }\r
-    catch(ModuleException e) {\r
-      logger.error("smod content :: dettach :: could not get entityContent");\r
-    }\r
-    catch(StorageObjectFailure e) {\r
-      logger.error("smod content :: dettach :: could not get entityContent");\r
-    }\r
-\r
-    _showObject(cidParam, req, res);\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
-      String[] topic_id = aRequest.getParameterValues("to_topic");\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 id = mainModule.set(withValues);\r
-      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);\r
-\r
-      String whereParam = aRequest.getParameter("where");\r
-      String orderParam = aRequest.getParameter("order");\r
-\r
-      if (returnUrl!=null){\r
-        redirect(aResponse, returnUrl);\r
-      }\r
-      else\r
-        _showObject(idParam, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\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
-  public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)\r
-      throws ServletModuleExc {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map responseData = ServletHelper.makeGenerationData(getLocale(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
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
-      responseData.put("thisurl", urlBuilder.getQuery());\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void returnArticleList(\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 nrArticlesPerPage = 20;\r
-    int count;\r
-\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));\r
-      model = MirGlobal.localizer().dataModel().adapterModel();\r
-\r
-      Object articleList =\r
-          new CachingRewindableIterator(\r
-            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,\r
-               MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, 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+nrArticlesPerPage) {\r
-        urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));\r
-        responseData.put("nexturl" , urlBuilder.getQuery());\r
-      }\r
-\r
-      if (anOffset>0) {\r
-        urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 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+nrArticlesPerPage, 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, listTemplate);\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
-      returnArticleList(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
-      returnArticleList(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
-    }\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
-    }\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
-  private EntityUsers _getUser(HttpServletRequest req)\r
-  {\r
-    HttpSession session=req.getSession(false);\r
-\r
-    return (EntityUsers)session.getAttribute("login.uid");\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 the com.oreilly.servlet library, 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.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.module.ModuleException;
+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 mir.util.SQLQueryBuilder;
+import mir.util.URLBuilder;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleContent;
+import mircoders.search.IndexUtil;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseContentToTopics;
+
+import org.apache.lucene.index.IndexReader;
+
+import freemarker.template.SimpleHash;
+
+/*
+ *  ServletModuleContent -
+ *  deliver html for the article admin form.
+ *
+ * @version $Id: ServletModuleContent.java,v 1.41 2003/03/08 17:18:19 idfx Exp $
+ * @author rk, mir-coders
+ *
+ */
+
+public class ServletModuleContent extends ServletModule
+{
+  private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;
+  private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");
+
+  private static ServletModuleContent instance = new ServletModuleContent();
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleContent() {
+    super();
+    logger = new LoggerWrapper("ServletModule.Content");
+    try {
+
+      templateListString = configuration.getString("ServletModule.Content.ListTemplate");
+      templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");
+      templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");
+
+      mainModule = new ModuleContent(DatabaseContent.getInstance());
+    }
+    catch (StorageObjectFailure e) {
+      logger.error("servletmodulecontent konnte nicht initialisiert werden");
+    }
+  }
+
+  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");
+
+    returnArticleList(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("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.appendAscendingOrder("webdb_create");
+        else if (searchOrder.equals("dateasc"))
+          queryBuilder.appendDescendingOrder("webdb_create");
+        else if (searchOrder.equals("title"))
+          queryBuilder.appendDescendingOrder("title");
+        else if (searchOrder.equals("creator"))
+          queryBuilder.appendDescendingOrder("creator");
+      }
+
+      returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+    _showObject(null, req, res);
+  }
+
+
+  public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+//theLog.printDebugInfo(":: content :: trying to insert");
+    try {
+      EntityUsers   user = _getUser(req);
+      Map withValues = getIntersectingValues(req, DatabaseContent.getInstance());
+
+      String now = StringUtil.date2webdbDate(new GregorianCalendar());
+      withValues.put("date", now);
+      withValues.put("publish_path", StringUtil.webdbDate2path(now));
+      withValues.put("to_publisher", user.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 id = mainModule.add(withValues);
+      DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
+
+      _showObject(id, req, res);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    EntityUsers   user = _getUser(req);
+
+    String idParam = req.getParameter("id");
+    if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
+
+    String confirmParam = req.getParameter("confirm");
+    String cancelParam = req.getParameter("cancel");
+
+    logger.info("where = " + req.getParameter("where"));
+
+    if (confirmParam == null && cancelParam == null) {
+
+      SimpleHash mergeData = new SimpleHash();
+      mergeData.put("module", "Content");
+      mergeData.put("infoString", "Content: " + idParam);
+      mergeData.put("id", idParam);
+      mergeData.put("where", req.getParameter("where"));
+      mergeData.put("order", req.getParameter("order"));
+      mergeData.put("offset", req.getParameter("offset"));
+      deliver(req, res, mergeData, templateConfirmString);
+    }
+    else {
+      if (confirmParam!= null && !confirmParam.equals("")) {
+        try {
+          mainModule.deleteById(idParam);
+
+          /** @todo the following two should be implied in
+           *  DatabaseContent */
+
+          //delete rows in the content_x_topic-table
+          DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
+          //delete rows in the comment-table
+          DatabaseComment.getInstance().deleteByContentId(idParam);
+          //delete from lucene index, if any
+          String index = configuration.getString("IndexPath");
+          if (IndexReader.indexExists(index)){
+            IndexUtil.unindexID(idParam,index);
+          }
+
+        }
+        catch (Throwable e) {
+          throw new ServletModuleFailure(e);
+        }
+        list(req,res);
+      }
+      else {
+        // Datensatz anzeigen
+        _showObject(idParam, req, res);
+      }
+    }
+  }
+
+  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String idParam = req.getParameter("id");
+    if (idParam == null)
+      throw new ServletModuleExc("Invalid call: id not supplied ");
+    _showObject(idParam, req, res);
+  }
+
+// methods for attaching media file
+  public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String  mediaIdParam = req.getParameter("mid");
+    String  idParam = req.getParameter("cid");
+    if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing");
+
+    try {
+      EntityContent entContent = (EntityContent)mainModule.getById(idParam);
+      entContent.attach(mediaIdParam);
+    }
+    catch(ModuleException e) {
+      logger.error("smod content :: attach :: could not get entityContent");
+    }
+    catch(StorageObjectFailure e) {
+      logger.error("smod content :: attach :: could not get entityContent");
+    }
+
+    _showObject(idParam, req, res);
+  }
+
+  public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String  cidParam = req.getParameter("cid");
+    String  midParam = req.getParameter("mid");
+    if (cidParam == null)
+      throw new ServletModuleExc("smod content :: dettach :: cid missing");
+    if (midParam == null)
+      throw new ServletModuleExc("smod content :: dettach :: mid missing");
+
+    try {
+      EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
+      entContent.dettach(cidParam,midParam);
+    }
+    catch(ModuleException e) {
+      logger.error("smod content :: dettach :: could not get entityContent");
+    }
+    catch(StorageObjectFailure e) {
+      logger.error("smod content :: dettach :: could not get entityContent");
+    }
+
+    _showObject(cidParam, req, res);
+  }
+
+  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[] topic_id = aRequest.getParameterValues("to_topic");
+      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 id = mainModule.set(withValues);
+      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);
+
+      String whereParam = aRequest.getParameter("where");
+      String orderParam = aRequest.getParameter("order");
+
+      if (returnUrl!=null){
+        redirect(aResponse, returnUrl);
+      }
+      else
+        _showObject(idParam, aRequest, aResponse);
+    }
+    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.
+*/
+  public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map responseData = ServletHelper.makeGenerationData(getLocale(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);
+
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));
+      responseData.put("thisurl", urlBuilder.getQuery());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void returnArticleList(
+       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 nrArticlesPerPage = 20;
+    int count;
+
+    try {
+      Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
+      model = MirGlobal.localizer().dataModel().adapterModel();
+
+      Object articleList =
+          new CachingRewindableIterator(
+            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
+               MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, 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+nrArticlesPerPage) {
+        urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
+        responseData.put("nexturl" , urlBuilder.getQuery());
+      }
+
+      if (anOffset>0) {
+        urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 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+nrArticlesPerPage, count)));
+      responseData.put("offset" , Integer.toString(anOffset));
+      responseData.put("order", anOrderByClause);
+      responseData.put("where" , aWhereClause);
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
+    }
+    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"));
+
+      returnArticleList(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!");
+
+      returnArticleList(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();
+    }
+    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();
+    }
+    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);
+  }
+
+  private EntityUsers _getUser(HttpServletRequest req)
+  {
+    HttpSession session=req.getSession(false);
+
+    return (EntityUsers)session.getAttribute("login.uid");
+  }
+}
index c93712e..251e1a0 100755 (executable)
@@ -34,7 +34,6 @@ package mircoders.servlet;
 import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
-import java.io.IOException;
 import java.io.StringReader;
 import java.io.StringWriter;
 
@@ -55,8 +54,8 @@ import freemarker.template.SimpleList;
  *  Allows one to do a basic edit of a file in a directory specified
  *  in the config file.
  *
- * @author $Author: zapata $
- * @version $Revision: 1.6 $ $Date: 2003/03/06 05:40:40 $
+ * @author $Author: idfx $
+ * @version $Revision: 1.7 $ $Date: 2003/03/08 17:18:19 $
  *
  */
 
index bae412b..b7a6358 100755 (executable)
 
 package mircoders.servlet;
 
-import java.io.IOException;
-
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import mir.entity.EntityList;
 import mir.log.LoggerWrapper;
 import mir.misc.HTMLTemplateProcessor;
-import mir.module.ModuleException;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
index dc740ea..e854dcd 100755 (executable)
@@ -31,7 +31,6 @@
 
 package mircoders.servlet;
 
-import java.io.IOException;
 import java.io.PrintWriter;
 import java.net.URLEncoder;
 
@@ -40,9 +39,7 @@ import javax.servlet.http.HttpServletResponse;
 
 import mir.entity.EntityList;
 import mir.log.LoggerWrapper;
-import mir.misc.HTMLParseException;
 import mir.misc.HTMLTemplateProcessor;
-import mir.module.ModuleException;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
index fbe12e9..cedb77a 100755 (executable)
@@ -31,7 +31,6 @@
 
 package mircoders.servlet;
 
-import java.io.IOException;
 import java.net.URLEncoder;
 
 import javax.servlet.http.HttpServletRequest;
@@ -40,7 +39,6 @@ import javax.servlet.http.HttpServletResponse;
 import mir.entity.EntityList;
 import mir.log.LoggerWrapper;
 import mir.misc.HTMLTemplateProcessor;
-import mir.module.ModuleException;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
index beb854b..d787df6 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.servlet;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.io.PrintWriter;\r
-import java.io.StringWriter;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.Enumeration;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.ListIterator;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.Random;\r
-import java.util.Set;\r
-\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.servlet.http.HttpSession;\r
-\r
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
-import mir.entity.Entity;\r
-import mir.entity.EntityList;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.FileHandler;\r
-import mir.misc.FileHandlerException;\r
-import mir.misc.FileHandlerUserException;\r
-import mir.misc.HTMLParseException;\r
-import mir.misc.HTMLTemplateProcessor;\r
-import mir.misc.StringUtil;\r
-import mir.misc.WebdbMultipartRequest;\r
-import mir.module.ModuleException;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.storage.StorageObjectFailure;\r
-import mir.util.StringRoutines;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.media.MediaRequest;\r
-import mircoders.module.ModuleComment;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.module.ModuleImages;\r
-import mircoders.module.ModuleTopics;\r
-import mircoders.search.AudioSearchTerm;\r
-import mircoders.search.ContentSearchTerm;\r
-import mircoders.search.ImagesSearchTerm;\r
-import mircoders.search.KeywordSearchTerm;\r
-import mircoders.search.TextSearchTerm;\r
-import mircoders.search.TopicSearchTerm;\r
-import mircoders.search.UnIndexedSearchTerm;\r
-import mircoders.search.VideoSearchTerm;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseContentToMedia;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-import mircoders.storage.DatabaseImages;\r
-import mircoders.storage.DatabaseLanguage;\r
-import mircoders.storage.DatabaseTopics;\r
-\r
-import org.apache.commons.net.smtp.SMTPClient;\r
-import org.apache.commons.net.smtp.SMTPReply;\r
-import org.apache.fop.apps.Driver;\r
-import org.apache.fop.apps.XSLTInputHandler;\r
-import org.apache.log.Hierarchy;\r
-import org.apache.log.Priority;\r
-import org.apache.lucene.analysis.standard.StandardAnalyzer;\r
-import org.apache.lucene.document.Document;\r
-import org.apache.lucene.queryParser.QueryParser;\r
-import org.apache.lucene.search.Hits;\r
-import org.apache.lucene.search.IndexSearcher;\r
-import org.apache.lucene.search.Query;\r
-import org.apache.lucene.search.Searcher;\r
-\r
-import freemarker.template.SimpleHash;\r
-import freemarker.template.SimpleList;\r
-import freemarker.template.SimpleScalar;\r
-import freemarker.template.TemplateModelRoot;\r
-\r
-/*\r
- *  ServletModuleOpenIndy -\r
- *   is the open-access-servlet, which is responsible for\r
- *    adding comments to articles &\r
- *    open-postings to the newswire\r
- *\r
- * @author mir-coders group\r
- * @version $Id: ServletModuleOpenIndy.java,v 1.63 2003/03/06 05:40:40 zapata Exp $\r
- *\r
- */\r
-\r
-public class ServletModuleOpenIndy extends ServletModule\r
-{\r
-\r
-  private String        commentFormTemplate, commentFormDoneTemplate,\r
-    commentFormDupeTemplate;\r
-  private String        postingFormTemplate, postingFormDoneTemplate,\r
-    postingFormDupeTemplate;\r
-  private String        searchResultsTemplate;\r
-  private String        prepareMailTemplate,sentMailTemplate;\r
-  private ModuleContent contentModule;\r
-  private ModuleComment commentModule;\r
-  private ModuleImages  imageModule;\r
-  private ModuleTopics  themenModule;\r
-  private String        directOp ="yes";\r
-  private String        passwdProtection ="yes";\r
-  // Singelton / Kontruktor\r
-  private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleOpenIndy() {\r
-    super();\r
-    try {\r
-      logger = new LoggerWrapper("ServletModule.OpenIndy");\r
-\r
-      commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");\r
-      commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");\r
-      commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");\r
-      postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");\r
-      postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");\r
-      postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");\r
-      searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");\r
-      prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");\r
-      sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");\r
-      directOp = configuration.getString("DirectOpenposting").toLowerCase();\r
-      passwdProtection = configuration.getString("PasswdProtection").toLowerCase();\r
-      mainModule = new ModuleComment(DatabaseComment.getInstance());\r
-      contentModule = new ModuleContent(DatabaseContent.getInstance());\r
-      themenModule = new ModuleTopics(DatabaseTopics.getInstance());\r
-      imageModule = new ModuleImages(DatabaseImages.getInstance());\r
-      defaultAction="addposting";\r
-\r
-    }\r
-    catch (StorageObjectFailure e) {\r
-      logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-\r
-  /**\r
-   *  Method for making a comment\r
-   */\r
-\r
-  public void addcomment(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    String aid = req.getParameter("aid"); // the article id the comment will belong to\r
-    String language = req.getParameter("language");\r
-\r
-    if (aid!=null && !aid.equals("")) {\r
-      try {\r
-        SimpleHash mergeData = new SimpleHash();\r
-\r
-        // onetimepasswd\r
-        if (passwdProtection.equals("yes")) {\r
-          String passwd = this.createOneTimePasswd();\r
-          HttpSession session = req.getSession(false);\r
-          session.setAttribute("passwd", passwd);\r
-          mergeData.put("passwd", passwd);\r
-        }\r
-\r
-        if (language != null) {\r
-          HttpSession session = req.getSession(false);\r
-          session.setAttribute("Locale", new Locale(language, ""));\r
-          session.setAttribute("passwd", language);\r
-        }\r
-\r
-        mergeData.put("aid", aid);\r
-\r
-        SimpleHash extraInfo = new SimpleHash();\r
-        extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());\r
-\r
-        deliver(req, res, mergeData, extraInfo, commentFormTemplate);\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);\r
-      }\r
-    }\r
-    else throw new ServletModuleExc("aid not set!");\r
-  }\r
-\r
-  /**\r
-   *  Method for inserting a comment into the Database and delivering\r
-   *  the commentDone Page\r
-   */\r
-\r
-  public void inscomment(HttpServletRequest req, HttpServletResponse res)\r
-    throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    String aid = req.getParameter("to_media"); // the article id the comment will belong to\r
-    if (aid!=null && !aid.equals(""))\r
-      {\r
-        // ok, collecting data from form\r
-        try {\r
-          Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());\r
-\r
-          //no html in comments(for now)\r
-          for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
-            String k=(String)i.next();\r
-            String v=(String)withValues.get(k);\r
-\r
-            withValues.put(k,StringUtil.removeHTMLTags(v));\r
-          }\r
-          withValues.put("is_published","1");\r
-          withValues.put("to_comment_status","1");\r
-\r
-          //checking the onetimepasswd\r
-          if(passwdProtection.equals("yes")){\r
-            HttpSession session = req.getSession(false);\r
-            String sessionPasswd = (String)session.getAttribute("passwd");\r
-            if ( sessionPasswd == null){\r
-              throw new ServletModuleUserExc("Lost password");\r
-            }\r
-            String passwd = req.getParameter("passwd");\r
-            if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
-              throw new ServletModuleUserExc("Missing password");\r
-            }\r
-            session.invalidate();\r
-          }\r
-\r
-          // inserting into database\r
-          String id = mainModule.add(withValues);\r
-          logger.debug("id: "+id);\r
-          //insert was not successfull\r
-          if(id==null){\r
-            deliver(req, res, new SimpleHash(), commentFormDupeTemplate);\r
-          } else {\r
-            DatabaseContent.getInstance().setUnproduced("id="+aid);\r
-\r
-            try {\r
-              EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);\r
-              MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
-            }\r
-            catch (Throwable t) {\r
-              throw new ServletModuleExc(t.getMessage());\r
-            }\r
-          }\r
-\r
-          // redirecting to url\r
-          // should implement back to article\r
-          SimpleHash mergeData = new SimpleHash();\r
-          deliver(req, res, mergeData, commentFormDoneTemplate);\r
-        }\r
-        catch (Throwable e) {\r
-          throw new ServletModuleFailure(e);\r
-        }\r
-      }\r
-    else throw new ServletModuleExc("aid not set!");\r
-\r
-  }\r
-\r
-  /**\r
-   *  Method for delivering the form-Page for open posting\r
-   */\r
-\r
-  public void addposting(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    SimpleHash mergeData = new SimpleHash();\r
-\r
-    // onetimepasswd\r
-    if(passwdProtection.equals("yes")){\r
-      String passwd = this.createOneTimePasswd();\r
-      HttpSession session = req.getSession(false);\r
-      session.setAttribute("passwd",passwd);\r
-      mergeData.put("passwd", passwd);\r
-    }\r
-\r
-    String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");\r
-    String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");\r
-    String numOfMedia = req.getParameter("medianum");\r
-\r
-    if(numOfMedia==null||numOfMedia.equals("")){\r
-      numOfMedia=defaultMedia;\r
-    }\r
-    else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
-      numOfMedia = maxMedia;\r
-    }\r
-\r
-    int mediaNum = Integer.parseInt(numOfMedia);\r
-    SimpleList mediaFields = new SimpleList();\r
-    for(int i =0; i<mediaNum;i++){\r
-      Integer mNum = new Integer(i+1);\r
-      mediaFields.add(mNum.toString());\r
-    }\r
-    mergeData.put("medianum",numOfMedia);\r
-    mergeData.put("mediafields",mediaFields);\r
-\r
-\r
-    SimpleHash extraInfo = new SimpleHash();\r
-    try{\r
-      extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );\r
-      extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());\r
-\r
-      extraInfo.put("topics", themenModule.getTopicsList());\r
-\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("languagePopUpData or getTopicslist failed "+e.toString());\r
-\r
-      throw new ServletModuleFailure("OpenIndy -- failed getting language or topics: "+e.toString(), e);\r
-    }\r
-\r
-\r
-\r
-    deliver(req, res, mergeData, extraInfo, postingFormTemplate);\r
-  }\r
-\r
-  /**\r
-   *  Method for inserting an open posting into the Database and delivering\r
-   *  the postingDone Page\r
-   */\r
-\r
-  public void insposting(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    SimpleHash mergeData = new SimpleHash();\r
-    boolean setMedia=false;\r
-    boolean setTopic = false;\r
-\r
-    try {\r
-\r
-      WebdbMultipartRequest mp = null;\r
-      EntityList mediaList = null;\r
-      try {\r
-        // new MediaRequest, "1" is the id for the openPosting user\r
-        MediaRequest mediaReq = new MediaRequest("1", true);\r
-        mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
-        mediaList = mediaReq.getEntityList();\r
-      }\r
-      catch (FileHandlerUserException e) {\r
-        throw new ServletModuleFailure(e);\r
-      }\r
-\r
-      Map withValues = mp.getParameters();\r
-\r
-      //checking the onetimepasswd\r
-      if(passwdProtection.equals("yes")){\r
-        HttpSession session = req.getSession(false);\r
-        String sessionPasswd = (String)session.getAttribute("passwd");\r
-        if ( sessionPasswd == null){\r
-          throw new ServletModuleUserExc("Lost password");\r
-        }\r
-        String passwd = (String)withValues.get("passwd");\r
-        if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
-          throw new ServletModuleUserExc("Missing password");\r
-        }\r
-        session.invalidate();\r
-      }\r
-\r
-      if ((((String)withValues.get("title")).length() == 0) ||\r
-          (((String)withValues.get("description")).length() == 0) ||\r
-          (((String)withValues.get("content_data")).length() == 0))\r
-        throw new ServletModuleUserExc("Missing field");\r
-\r
-      // call the routines that escape html\r
-\r
-      for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
-        String k=(String)i.next();\r
-        String v=(String)withValues.get(k);\r
-\r
-        if (k.equals("content_data")){\r
-          //this doesn't quite work yet, so for now, all html goes\r
-          //withValues.put(k,StringUtil.approveHTMLTags(v));\r
-          withValues.put(k,StringUtil.deleteForbiddenTags(v));\r
-        } else if (k.equals("description")) {\r
-          String tmp = StringUtil.deleteForbiddenTags(v);\r
-          withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));\r
-        } else {\r
-          withValues.put(k,StringUtil.removeHTMLTags(v));\r
-        }\r
-\r
-      }\r
-\r
-      withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
-      withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));\r
-      withValues.put("is_produced", "0");\r
-      // by default stuff is published, they can be un-published through the\r
-      // admin interface.\r
-      withValues.put("is_published","1");\r
-      // if op direct article-type == newswire\r
-      if (directOp.equals("yes")) withValues.put("to_article_type","1");\r
-\r
-      withValues.put("to_publisher","1");\r
-\r
-      // owner is openposting user\r
-      //      ML: this is not multi-language friendly and this can be done in a template\r
-      //      if (withValues.get("creator").toString().equals(""))\r
-      //        withValues.put("creator","Anonym");\r
-\r
-      // inserting  content into database\r
-      String cid = contentModule.add(withValues);\r
-      logger.debug("id: "+cid);\r
-      //insert was not successfull\r
-      if(cid==null){\r
-        //How do we know that it was not succesful cause of a\r
-        //dupe, what if it failed cause of "No space left on device"?\r
-        //Or is there something I am missing? Wouldn't it be better\r
-        //to have an explicit dupe check and then insert? I have no\r
-        //idea what I am talking about. this comment is in case\r
-        //I forget to explicitely ask. -mh\r
-        deliver(req, res, mergeData, postingFormDupeTemplate);\r
-      }\r
-\r
-      String[] to_topicsArr = mp.getParameterValues("to_topic");\r
-\r
-      if (to_topicsArr != null && to_topicsArr.length > 0) {\r
-        try{\r
-          DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);\r
-          setTopic = true;\r
-        }\r
-        catch (Exception e) {\r
-          logger.error("setting content_x_topic failed");\r
-          contentModule.deleteById(cid);\r
-          throw new ServletModuleExc("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());\r
-        } //end try\r
-      } //end if\r
-\r
-      //if we're here all is ok... associate the media to the article\r
-      for(int i=0;i<mediaList.size();i++) {\r
-        Entity mediaEnt = (Entity)mediaList.elementAt(i);\r
-        DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());\r
-      }\r
-\r
-      try {\r
-        MirGlobal.localizer().openPostings().afterContentPosting(\r
-                                                                 (EntityContent)contentModule.getById(cid));\r
-      }\r
-      catch (Throwable t) {\r
-        throw new ServletModuleFailure(t);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-\r
-    deliver(req, res, mergeData, postingFormDoneTemplate);\r
-  }\r
-\r
-    /*\r
-   * Method for preparing and sending a content as an email message\r
-   */\r
-\r
-  public void mail(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
-  {\r
-    String aid = req.getParameter("mail_aid");\r
-    if (aid == null){\r
-      throw new ServletModuleUserExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");\r
-    }\r
-\r
-    String to = req.getParameter("mail_to");\r
-    String from = req.getParameter("mail_from");\r
-    String from_name = req.getParameter("mail_from_name");\r
-    String comment = req.getParameter("mail_comment");\r
-    String mail_language = req.getParameter("mail_language");\r
-\r
-    SimpleHash mergeData = new SimpleHash();\r
-\r
-    if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){\r
-\r
-      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
-        String pName=(String)theParams.nextElement();\r
-        if (pName.startsWith("mail_")){\r
-          mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
-        }\r
-      }\r
-      deliver(req,res,mergeData,prepareMailTemplate);\r
-    }\r
-    else {\r
-      //run checks on to and from and mail_language to make sure no monkey business occurring\r
-      if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ){\r
-        throw new ServletModuleUserExc("Sorry, you've entered an illegal character into the language field.  Go back and try again, asshole.");\r
-      }\r
-      if (to.indexOf('\n') != -1\r
-          || to.indexOf('\r') != -1\r
-          || to.indexOf(',') != -1\r
-          || from.indexOf('\n') != -1\r
-          || from.indexOf('\r') != -1\r
-          || from.indexOf(',') != -1 ){\r
-        throw new ServletModuleUserExc("Sorry, you've entered an illegal character into the from or to field.  Go back and try again.");\r
-      }\r
-      EntityContent contentEnt;\r
-      try{\r
-        contentEnt = (EntityContent)contentModule.getById(aid);\r
-      }\r
-      catch (Throwable e){\r
-        throw new ServletModuleFailure("Couldn't get content for article "+aid + ": " + e.getMessage(), e);\r
-      }\r
-      String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
-      String producerDocRoot=configuration.getString("Producer.DocRoot");\r
-      String publishPath = contentEnt.getValue("publish_path");\r
-      String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +\r
-                                                                                                         publishPath + "/" + aid + ".txt";\r
-\r
-\r
-      File inputFile = new File(txtFilePath);\r
-      String content;\r
-\r
-      try{\r
-        FileReader in = new FileReader(inputFile);\r
-        StringWriter out = new StringWriter();\r
-        int c;\r
-        while ((c = in.read()) != -1)\r
-          out.write(c);\r
-        in.close();\r
-        content= out.toString();\r
-      }\r
-      catch (FileNotFoundException e){\r
-        throw new ServletModuleFailure("No text file found in " + txtFilePath, e);\r
-      }\r
-      catch (IOException e){\r
-        throw new ServletModuleFailure("Problem reading file in " + txtFilePath, e);\r
-      }\r
-      // add some headers\r
-      content = "To: " + to + "\nReply-To: "+ from + "\n" + content;\r
-      // put in the comment where it should go\r
-      if (comment != null) {\r
-        String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;\r
-        try {\r
-          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);\r
-        }\r
-        catch (Throwable e){\r
-          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);\r
-        }\r
-      }\r
-      else{\r
-        try {\r
-          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");\r
-        }\r
-        catch (Throwable e){\r
-          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);\r
-        }\r
-      }\r
-\r
-      SMTPClient client=new SMTPClient();\r
-      try {\r
-        int reply;\r
-        client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));\r
-\r
-        reply = client.getReplyCode();\r
-\r
-        if (!SMTPReply.isPositiveCompletion(reply)) {\r
-          client.disconnect();\r
-          throw new ServletModuleExc("SMTP server refused connection.");\r
-        }\r
-\r
-        client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);\r
-\r
-        client.disconnect();\r
-        //mission accomplished\r
-        deliver(req, res, mergeData, sentMailTemplate);\r
-      }\r
-      catch(IOException e) {\r
-        if(client.isConnected()) {\r
-          try {\r
-            client.disconnect();\r
-          } catch(IOException f) {\r
-            // do nothing\r
-          }\r
-        }\r
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-  }\r
-\r
-\r
-  /*\r
-   * Method for querying a lucene index\r
-   */\r
-  public void search(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
-    try {\r
-      int increment=10;\r
-\r
-      HttpSession session = req.getSession(false);\r
-\r
-      String queryString="";\r
-\r
-      SimpleHash mergeData = new SimpleHash();\r
-\r
-      KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");\r
-      UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");\r
-      TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");\r
-      TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");\r
-      TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");\r
-      ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");\r
-      TopicSearchTerm topicTerm = new TopicSearchTerm();\r
-      ImagesSearchTerm imagesTerm = new ImagesSearchTerm();\r
-      AudioSearchTerm audioTerm = new AudioSearchTerm();\r
-      VideoSearchTerm videoTerm = new VideoSearchTerm();\r
-\r
-      //make the query available to subsequent iterations\r
-\r
-      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
-        String pName=(String)theParams.nextElement();\r
-        if (pName.startsWith("search_")){\r
-          mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
-        }\r
-      }\r
-\r
-      try{\r
-        mergeData.put("topics", themenModule.getTopicsAsSimpleList());\r
-      }\r
-      catch(ModuleException e) {\r
-        logger.debug("Can't get topics: " + e.toString());\r
-      }\r
-\r
-      String searchBackValue = req.getParameter("search_back");\r
-      String searchForwardValue = req.getParameter("search_forward");\r
-\r
-      if (searchBackValue != null){\r
-        int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
-        int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
-        if (newPosition<0)\r
-          newPosition=0;\r
-        if (newPosition >= totalHits)\r
-          newPosition=totalHits-1;\r
-        session.setAttribute("positionInResults",new Integer(newPosition));\r
-      }\r
-      else {\r
-        if (searchForwardValue != null){\r
-          int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
-          int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
-          if (newPosition<0)\r
-            newPosition=0;\r
-          if (newPosition >= totalHits)\r
-            newPosition=totalHits-1;\r
-\r
-          session.setAttribute("positionInResults",new Integer(newPosition));\r
-        }\r
-        else {\r
-          String indexPath=configuration.getString("IndexPath");\r
-\r
-\r
-          String creatorFragment = creatorTerm.makeTerm(req);\r
-          if (creatorFragment != null){\r
-            queryString = queryString + " +" + creatorFragment;\r
-          }\r
-\r
-          // search title, description, and content for something\r
-          // the contentTerm uses param "search_boolean" to combine its terms\r
-          String contentFragment = contentTerm.makeTerm(req);\r
-          if (contentFragment != null){\r
-            logger.debug("contentFragment: " + contentFragment);\r
-            queryString = queryString + " +" + contentFragment;\r
-          }\r
-\r
-          String topicFragment = topicTerm.makeTerm(req);\r
-          if (topicFragment != null){\r
-            queryString = queryString + " +" + topicFragment;\r
-          }\r
-\r
-          String imagesFragment = imagesTerm.makeTerm(req);\r
-          if (imagesFragment != null){\r
-            queryString = queryString + " +" + imagesFragment;\r
-          }\r
-\r
-          String audioFragment = audioTerm.makeTerm(req);\r
-          if (audioFragment != null){\r
-            queryString = queryString + " +" + audioFragment;\r
-          }\r
-\r
-          String videoFragment = videoTerm.makeTerm(req);\r
-          if (videoFragment != null){\r
-            queryString = queryString + " +" + videoFragment;\r
-          }\r
-\r
-          if (queryString == null || queryString == ""){\r
-            queryString = "";\r
-          }\r
-          else{\r
-            try{\r
-              Searcher searcher = null;\r
-              try {\r
-                searcher = new IndexSearcher(indexPath);\r
-              }\r
-              catch(IOException e) {\r
-                logger.debug("Can't open indexPath: " + indexPath);\r
-                throw new ServletModuleExc("Problem with Search Index! : "+ e.toString());\r
-              }\r
-\r
-              Query query = null;\r
-              try {\r
-                query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
-              }\r
-              catch(Exception e) {\r
-                searcher.close();\r
-                logger.debug("Query don't parse: " + queryString);\r
-                throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')");\r
-              }\r
-\r
-              Hits hits = null;\r
-              try {\r
-                hits = searcher.search(query);\r
-              }\r
-              catch(IOException e) {\r
-                searcher.close();\r
-                logger.debug("Can't get hits: " + e.toString());\r
-                throw new ServletModuleExc("Problem getting hits!");\r
-              }\r
-\r
-              int start = 0;\r
-              int end = hits.length();\r
-\r
-              String sortBy=req.getParameter("search_sort");\r
-              if (sortBy == null || sortBy.equals("")){\r
-                throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");\r
-              }\r
-\r
-              // here is where the documents will go for storage across sessions\r
-              ArrayList theDocumentsSorted = new ArrayList();\r
-\r
-              if (sortBy.equals("score")){\r
-                for(int i = start; i < end; i++) {\r
-                  theDocumentsSorted.add(hits.doc(i));\r
-                }\r
-              }\r
-              else{\r
-                // then we'll sort by date!\r
-                Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
-                for(int i = start; i < end; i++) {\r
-                  String creationDate=(hits.doc(i)).get("creationDate");\r
-                  // do a little dance in case two contents created at the same second!\r
-                  if (dateToPosition.containsKey(creationDate)){\r
-                    ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
-                  }\r
-                  else{\r
-                    ArrayList thePositions = new ArrayList();\r
-                    thePositions.add(new Integer(i));\r
-                    dateToPosition.put(creationDate,thePositions);\r
-                  }\r
-                }\r
-                Set keys = dateToPosition.keySet();\r
-                ArrayList keyList= new ArrayList(keys);\r
-                Collections.sort(keyList);\r
-                if (sortBy.equals("date_desc")){\r
-                  Collections.reverse(keyList);\r
-                }\r
-                else{\r
-                  if (!sortBy.equals("date_asc")){\r
-                    throw new ServletModuleExc("don't know how to sort by: "+ sortBy);\r
-                  }\r
-                }\r
-                ListIterator keyTraverser = keyList.listIterator();\r
-                while (keyTraverser.hasNext()){\r
-                  ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
-                  ListIterator positionsTraverser=positions.listIterator();\r
-                  while (positionsTraverser.hasNext()){\r
-                    theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
-                  }\r
-                }\r
-              }\r
-\r
-              try{\r
-                searcher.close();\r
-              }\r
-              catch (IOException e){\r
-                logger.debug("Can't close searcher: " + e.toString());\r
-                throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);\r
-              }\r
-\r
-\r
-              session.removeAttribute("numberOfHits");\r
-              session.removeAttribute("theDocumentsSorted");\r
-              session.removeAttribute("positionInResults");\r
-\r
-              session.setAttribute("numberOfHits",new Integer(end));\r
-              session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
-              session.setAttribute("positionInResults",new Integer(0));\r
-\r
-            }\r
-            catch (IOException e){\r
-              logger.debug("Can't close searcher: " + e.toString());\r
-              throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);\r
-            }\r
-          }\r
-        }\r
-      }\r
-\r
-      try {\r
-        ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
-        if (theDocs != null){\r
-\r
-          mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
-          SimpleList theHits = new SimpleList();\r
-          int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
-          int terminus;\r
-          int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
-\r
-          if (!(pIR+increment>=numHits)){\r
-            mergeData.put("hasNext","y");\r
-          }\r
-          if (pIR>0){\r
-            mergeData.put("hasPrevious","y");\r
-          }\r
-\r
-          if ((pIR+increment)>numHits){\r
-            terminus=numHits;\r
-          }\r
-          else {\r
-            terminus=pIR+increment;\r
-          }\r
-          for(int i = pIR; i < terminus; i++) {\r
-            SimpleHash h = new SimpleHash();\r
-            Document theHit = (Document)theDocs.get(i);\r
-            whereTerm.returnMeta(h,theHit);\r
-            creatorTerm.returnMeta(h,theHit);\r
-            titleTerm.returnMeta(h,theHit);\r
-            descriptionTerm.returnMeta(h,theHit);\r
-            dateTerm.returnMeta(h,theHit);\r
-            imagesTerm.returnMeta(h,theHit);\r
-            audioTerm.returnMeta(h,theHit);\r
-            videoTerm.returnMeta(h,theHit);\r
-            theHits.add(h);\r
-          }\r
-          mergeData.put("hits",theHits);\r
-        }\r
-      }\r
-      catch (Throwable e) {\r
-        logger.error("Can't iterate over hits: " + e.toString());\r
-\r
-        throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);\r
-      }\r
-\r
-      mergeData.put("queryString",queryString);\r
-      deliver(req,res,mergeData,searchResultsTemplate);\r
-    }\r
-    catch (NullPointerException n){\r
-      throw new ServletModuleFailure("Null Pointer: "+n.toString(), n);\r
-    }\r
-  }\r
-\r
-  /*\r
-   * Method for dynamically generating a pdf from a fo file\r
-   */\r
-  public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
-    String ID_REQUEST_PARAM = "id";\r
-    String language = req.getParameter("language");\r
-    String generateFO=configuration.getString("GenerateFO");\r
-    String generatePDF=configuration.getString("GeneratePDF");\r
-\r
-\r
-    //don't do anything if we are not making FO files, or if we are\r
-    //pregenerating PDF's\r
-    if (generateFO.equals("yes") && generatePDF.equals("no")){\r
-      //fop complains unless you do the logging this way\r
-      org.apache.log.Logger log = null;\r
-      Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
-      log = hierarchy.getLoggerFor("fop");\r
-      log.setPriority(Priority.WARN);\r
-\r
-      String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
-      String producerDocRoot=configuration.getString("Producer.DocRoot");\r
-      //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
-      String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");\r
-      try {\r
-        String idParam = req.getParameter(ID_REQUEST_PARAM);\r
-        if (idParam != null) {\r
-          EntityContent contentEnt =\r
-            (EntityContent)contentModule.getById(idParam);\r
-          String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));\r
-          String foFile;\r
-\r
-          if (language == null){\r
-            foFile = producerStorageRoot + producerDocRoot + "/"\r
-              + publishPath  + idParam + ".fo";\r
-          }\r
-          else{\r
-            foFile = producerStorageRoot + producerDocRoot + "/"\r
-              + language + publishPath  + idParam + ".fo";\r
-          }\r
-          logger.debug("USING FILES" + foFile + " and " + xslSheet);\r
-          XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
-                                                        new File(xslSheet));\r
-\r
-          ByteArrayOutputStream out = new ByteArrayOutputStream();\r
-          res.setContentType("application/pdf");\r
-\r
-          Driver driver = new Driver();\r
-          driver.setLogger(log);\r
-          driver.setRenderer(Driver.RENDER_PDF);\r
-          driver.setOutputStream(out);\r
-          driver.render(input.getParser(), input.getInputSource());\r
-\r
-          byte[] content = out.toByteArray();\r
-          res.setContentLength(content.length);\r
-          res.getOutputStream().write(content);\r
-          res.getOutputStream().flush();\r
-        }\r
-        else {\r
-          throw new ServletModuleUserExc("Missing id parameter.");\r
-        }\r
-      }\r
-      catch (Exception ex) {\r
-        logger.error(ex.toString());\r
-        throw new ServletModuleFailure(ex);\r
-      }\r
-    } else {\r
-      throw new ServletModuleExc("Can't generate a PDF because the config tells me not to.");\r
-    }\r
-  }\r
-\r
-  private void _throwBadContentType (String fileName, String contentType)\r
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
-\r
-    logger.error("Wrong file type uploaded!: " + fileName+" "\r
-                          +contentType);\r
-    throw new ServletModuleUserExc("The file you uploaded is of the "\r
-                                         +"following mime-type: "+contentType\r
-                                         +", we do not support this mime-type. "\r
-                                         +"Error One or more files of unrecognized type. Sorry");\r
-  }\r
-\r
-  protected String createOneTimePasswd(){\r
-    Random r = new Random();\r
-    int random = r.nextInt();\r
-    long l = System.currentTimeMillis();\r
-    l = (l*l*l*l)/random;\r
-    if(l<0) l = l * -1;\r
-    String returnString = ""+l;\r
-    return returnString.substring(5);\r
-  }\r
-\r
-\r
-  /* this is an overwritten method of ServletModule in order\r
-     to use different bundles for open and admin */\r
-  public void deliver(HttpServletRequest req, HttpServletResponse res,\r
-                      TemplateModelRoot rtm, TemplateModelRoot popups,\r
-                      String templateFilename) throws ServletModuleFailure\r
-  {\r
-    if (rtm == null) rtm = new SimpleHash();\r
-    try {\r
-      PrintWriter out = res.getWriter();\r
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,\r
-                                    getLocale(req), "bundles.open");\r
-      out.close();\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\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 the com.oreilly.servlet library, 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.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import mir.entity.Entity;
+import mir.entity.EntityList;
+import mir.log.LoggerWrapper;
+import mir.misc.FileHandler;
+import mir.misc.FileHandlerUserException;
+import mir.misc.HTMLTemplateProcessor;
+import mir.misc.StringUtil;
+import mir.misc.WebdbMultipartRequest;
+import mir.module.ModuleException;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.storage.StorageObjectFailure;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.media.MediaRequest;
+import mircoders.module.ModuleComment;
+import mircoders.module.ModuleContent;
+import mircoders.module.ModuleImages;
+import mircoders.module.ModuleTopics;
+import mircoders.search.AudioSearchTerm;
+import mircoders.search.ContentSearchTerm;
+import mircoders.search.ImagesSearchTerm;
+import mircoders.search.KeywordSearchTerm;
+import mircoders.search.TextSearchTerm;
+import mircoders.search.TopicSearchTerm;
+import mircoders.search.UnIndexedSearchTerm;
+import mircoders.search.VideoSearchTerm;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseContentToMedia;
+import mircoders.storage.DatabaseContentToTopics;
+import mircoders.storage.DatabaseImages;
+import mircoders.storage.DatabaseLanguage;
+import mircoders.storage.DatabaseTopics;
+
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+import org.apache.fop.apps.Driver;
+import org.apache.fop.apps.XSLTInputHandler;
+import org.apache.log.Hierarchy;
+import org.apache.log.Priority;
+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 freemarker.template.SimpleHash;
+import freemarker.template.SimpleList;
+import freemarker.template.SimpleScalar;
+import freemarker.template.TemplateModelRoot;
+
+/*
+ *  ServletModuleOpenIndy -
+ *   is the open-access-servlet, which is responsible for
+ *    adding comments to articles &
+ *    open-postings to the newswire
+ *
+ * @author mir-coders group
+ * @version $Id: ServletModuleOpenIndy.java,v 1.64 2003/03/08 17:18:19 idfx Exp $
+ *
+ */
+
+public class ServletModuleOpenIndy extends ServletModule
+{
+
+  private String        commentFormTemplate, commentFormDoneTemplate,
+    commentFormDupeTemplate;
+  private String        postingFormTemplate, postingFormDoneTemplate,
+    postingFormDupeTemplate;
+  private String        searchResultsTemplate;
+  private String        prepareMailTemplate,sentMailTemplate;
+  private ModuleContent contentModule;
+  private ModuleComment commentModule;
+  private ModuleImages  imageModule;
+  private ModuleTopics  themenModule;
+  private String        directOp ="yes";
+  private String        passwdProtection ="yes";
+  // Singelton / Kontruktor
+  private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleOpenIndy() {
+    super();
+    try {
+      logger = new LoggerWrapper("ServletModule.OpenIndy");
+
+      commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
+      commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
+      commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
+      postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
+      postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
+      postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
+      searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
+      prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
+      sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
+      directOp = configuration.getString("DirectOpenposting").toLowerCase();
+      passwdProtection = configuration.getString("PasswdProtection").toLowerCase();
+      mainModule = new ModuleComment(DatabaseComment.getInstance());
+      contentModule = new ModuleContent(DatabaseContent.getInstance());
+      themenModule = new ModuleTopics(DatabaseTopics.getInstance());
+      imageModule = new ModuleImages(DatabaseImages.getInstance());
+      defaultAction="addposting";
+
+    }
+    catch (StorageObjectFailure e) {
+      logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
+    }
+  }
+
+
+  /**
+   *  Method for making a comment
+   */
+
+  public void addcomment(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    String aid = req.getParameter("aid"); // the article id the comment will belong to
+    String language = req.getParameter("language");
+
+    if (aid!=null && !aid.equals("")) {
+      try {
+        SimpleHash mergeData = new SimpleHash();
+
+        // onetimepasswd
+        if (passwdProtection.equals("yes")) {
+          String passwd = this.createOneTimePasswd();
+          HttpSession session = req.getSession(false);
+          session.setAttribute("passwd", passwd);
+          mergeData.put("passwd", passwd);
+        }
+
+        if (language != null) {
+          HttpSession session = req.getSession(false);
+          session.setAttribute("Locale", new Locale(language, ""));
+          session.setAttribute("passwd", language);
+        }
+
+        mergeData.put("aid", aid);
+
+        SimpleHash extraInfo = new SimpleHash();
+        extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
+
+        deliver(req, res, mergeData, extraInfo, commentFormTemplate);
+      }
+      catch (Throwable t) {
+        throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
+      }
+    }
+    else throw new ServletModuleExc("aid not set!");
+  }
+
+  /**
+   *  Method for inserting a comment into the Database and delivering
+   *  the commentDone Page
+   */
+
+  public void inscomment(HttpServletRequest req, HttpServletResponse res)
+    throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    String aid = req.getParameter("to_media"); // the article id the comment will belong to
+    if (aid!=null && !aid.equals(""))
+      {
+        // ok, collecting data from form
+        try {
+          Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
+
+          //no html in comments(for now)
+          for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
+            String k=(String)i.next();
+            String v=(String)withValues.get(k);
+
+            withValues.put(k,StringUtil.removeHTMLTags(v));
+          }
+          withValues.put("is_published","1");
+          withValues.put("to_comment_status","1");
+
+          //checking the onetimepasswd
+          if(passwdProtection.equals("yes")){
+            HttpSession session = req.getSession(false);
+            String sessionPasswd = (String)session.getAttribute("passwd");
+            if ( sessionPasswd == null){
+              throw new ServletModuleUserExc("Lost password");
+            }
+            String passwd = req.getParameter("passwd");
+            if ( passwd == null || (!sessionPasswd.equals(passwd))) {
+              throw new ServletModuleUserExc("Missing password");
+            }
+            session.invalidate();
+          }
+
+          // inserting into database
+          String id = mainModule.add(withValues);
+          logger.debug("id: "+id);
+          //insert was not successfull
+          if(id==null){
+            deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
+          } else {
+            DatabaseContent.getInstance().setUnproduced("id="+aid);
+
+            try {
+              EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
+              MirGlobal.localizer().openPostings().afterCommentPosting(comment);
+            }
+            catch (Throwable t) {
+              throw new ServletModuleExc(t.getMessage());
+            }
+          }
+
+          // redirecting to url
+          // should implement back to article
+          SimpleHash mergeData = new SimpleHash();
+          deliver(req, res, mergeData, commentFormDoneTemplate);
+        }
+        catch (Throwable e) {
+          throw new ServletModuleFailure(e);
+        }
+      }
+    else throw new ServletModuleExc("aid not set!");
+
+  }
+
+  /**
+   *  Method for delivering the form-Page for open posting
+   */
+
+  public void addposting(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    SimpleHash mergeData = new SimpleHash();
+
+    // onetimepasswd
+    if(passwdProtection.equals("yes")){
+      String passwd = this.createOneTimePasswd();
+      HttpSession session = req.getSession(false);
+      session.setAttribute("passwd",passwd);
+      mergeData.put("passwd", passwd);
+    }
+
+    String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
+    String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
+    String numOfMedia = req.getParameter("medianum");
+
+    if(numOfMedia==null||numOfMedia.equals("")){
+      numOfMedia=defaultMedia;
+    }
+    else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
+      numOfMedia = maxMedia;
+    }
+
+    int mediaNum = Integer.parseInt(numOfMedia);
+    SimpleList mediaFields = new SimpleList();
+    for(int i =0; i<mediaNum;i++){
+      Integer mNum = new Integer(i+1);
+      mediaFields.add(mNum.toString());
+    }
+    mergeData.put("medianum",numOfMedia);
+    mergeData.put("mediafields",mediaFields);
+
+
+    SimpleHash extraInfo = new SimpleHash();
+    try{
+      extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );
+      extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
+
+      extraInfo.put("topics", themenModule.getTopicsList());
+
+    }
+    catch (Exception e) {
+      logger.error("languagePopUpData or getTopicslist failed "+e.toString());
+
+      throw new ServletModuleFailure("OpenIndy -- failed getting language or topics: "+e.toString(), e);
+    }
+
+
+
+    deliver(req, res, mergeData, extraInfo, postingFormTemplate);
+  }
+
+  /**
+   *  Method for inserting an open posting into the Database and delivering
+   *  the postingDone Page
+   */
+
+  public void insposting(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    SimpleHash mergeData = new SimpleHash();
+    boolean setMedia=false;
+    boolean setTopic = false;
+
+    try {
+
+      WebdbMultipartRequest mp = null;
+      EntityList mediaList = null;
+      try {
+        // new MediaRequest, "1" is the id for the openPosting user
+        MediaRequest mediaReq = new MediaRequest("1", true);
+        mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
+        mediaList = mediaReq.getEntityList();
+      }
+      catch (FileHandlerUserException e) {
+        throw new ServletModuleFailure(e);
+      }
+
+      Map withValues = mp.getParameters();
+
+      //checking the onetimepasswd
+      if(passwdProtection.equals("yes")){
+        HttpSession session = req.getSession(false);
+        String sessionPasswd = (String)session.getAttribute("passwd");
+        if ( sessionPasswd == null){
+          throw new ServletModuleUserExc("Lost password");
+        }
+        String passwd = (String)withValues.get("passwd");
+        if ( passwd == null || (!sessionPasswd.equals(passwd))) {
+          throw new ServletModuleUserExc("Missing password");
+        }
+        session.invalidate();
+      }
+
+      if ((((String)withValues.get("title")).length() == 0) ||
+          (((String)withValues.get("description")).length() == 0) ||
+          (((String)withValues.get("content_data")).length() == 0))
+        throw new ServletModuleUserExc("Missing field");
+
+      // call the routines that escape html
+
+      for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
+        String k=(String)i.next();
+        String v=(String)withValues.get(k);
+
+        if (k.equals("content_data")){
+          //this doesn't quite work yet, so for now, all html goes
+          //withValues.put(k,StringUtil.approveHTMLTags(v));
+          withValues.put(k,StringUtil.deleteForbiddenTags(v));
+        } else if (k.equals("description")) {
+          String tmp = StringUtil.deleteForbiddenTags(v);
+          withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
+        } else {
+          withValues.put(k,StringUtil.removeHTMLTags(v));
+        }
+
+      }
+
+      withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+      withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
+      withValues.put("is_produced", "0");
+      // by default stuff is published, they can be un-published through the
+      // admin interface.
+      withValues.put("is_published","1");
+      // if op direct article-type == newswire
+      if (directOp.equals("yes")) withValues.put("to_article_type","1");
+
+      withValues.put("to_publisher","1");
+
+      // owner is openposting user
+      //      ML: this is not multi-language friendly and this can be done in a template
+      //      if (withValues.get("creator").toString().equals(""))
+      //        withValues.put("creator","Anonym");
+
+      // inserting  content into database
+      String cid = contentModule.add(withValues);
+      logger.debug("id: "+cid);
+      //insert was not successfull
+      if(cid==null){
+        //How do we know that it was not succesful cause of a
+        //dupe, what if it failed cause of "No space left on device"?
+        //Or is there something I am missing? Wouldn't it be better
+        //to have an explicit dupe check and then insert? I have no
+        //idea what I am talking about. this comment is in case
+        //I forget to explicitely ask. -mh
+        deliver(req, res, mergeData, postingFormDupeTemplate);
+      }
+
+      String[] to_topicsArr = mp.getParameterValues("to_topic");
+
+      if (to_topicsArr != null && to_topicsArr.length > 0) {
+        try{
+          DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
+          setTopic = true;
+        }
+        catch (Exception e) {
+          logger.error("setting content_x_topic failed");
+          contentModule.deleteById(cid);
+          throw new ServletModuleExc("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
+        } //end try
+      } //end if
+
+      //if we're here all is ok... associate the media to the article
+      for(int i=0;i<mediaList.size();i++) {
+        Entity mediaEnt = (Entity)mediaList.elementAt(i);
+        DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
+      }
+
+      try {
+        MirGlobal.localizer().openPostings().afterContentPosting(
+                                                                 (EntityContent)contentModule.getById(cid));
+      }
+      catch (Throwable t) {
+        throw new ServletModuleFailure(t);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+
+    deliver(req, res, mergeData, postingFormDoneTemplate);
+  }
+
+    /*
+   * Method for preparing and sending a content as an email message
+   */
+
+  public void mail(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    String aid = req.getParameter("mail_aid");
+    if (aid == null){
+      throw new ServletModuleUserExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
+    }
+
+    String to = req.getParameter("mail_to");
+    String from = req.getParameter("mail_from");
+    String from_name = req.getParameter("mail_from_name");
+    String comment = req.getParameter("mail_comment");
+    String mail_language = req.getParameter("mail_language");
+
+    SimpleHash mergeData = new SimpleHash();
+
+    if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
+
+      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
+        String pName=(String)theParams.nextElement();
+        if (pName.startsWith("mail_")){
+          mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
+        }
+      }
+      deliver(req,res,mergeData,prepareMailTemplate);
+    }
+    else {
+      //run checks on to and from and mail_language to make sure no monkey business occurring
+      if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ){
+        throw new ServletModuleUserExc("Sorry, you've entered an illegal character into the language field.  Go back and try again, asshole.");
+      }
+      if (to.indexOf('\n') != -1
+          || to.indexOf('\r') != -1
+          || to.indexOf(',') != -1
+          || from.indexOf('\n') != -1
+          || from.indexOf('\r') != -1
+          || from.indexOf(',') != -1 ){
+        throw new ServletModuleUserExc("Sorry, you've entered an illegal character into the from or to field.  Go back and try again.");
+      }
+      EntityContent contentEnt;
+      try{
+        contentEnt = (EntityContent)contentModule.getById(aid);
+      }
+      catch (Throwable e){
+        throw new ServletModuleFailure("Couldn't get content for article "+aid + ": " + e.getMessage(), e);
+      }
+      String producerStorageRoot=configuration.getString("Producer.StorageRoot");
+      String producerDocRoot=configuration.getString("Producer.DocRoot");
+      String publishPath = contentEnt.getValue("publish_path");
+      String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +
+                                                                                                         publishPath + "/" + aid + ".txt";
+
+
+      File inputFile = new File(txtFilePath);
+      String content;
+
+      try{
+        FileReader in = new FileReader(inputFile);
+        StringWriter out = new StringWriter();
+        int c;
+        while ((c = in.read()) != -1)
+          out.write(c);
+        in.close();
+        content= out.toString();
+      }
+      catch (FileNotFoundException e){
+        throw new ServletModuleFailure("No text file found in " + txtFilePath, e);
+      }
+      catch (IOException e){
+        throw new ServletModuleFailure("Problem reading file in " + txtFilePath, e);
+      }
+      // add some headers
+      content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
+      // put in the comment where it should go
+      if (comment != null) {
+        String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
+        try {
+          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
+        }
+        catch (Throwable e){
+          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
+        }
+      }
+      else{
+        try {
+          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
+        }
+        catch (Throwable e){
+          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
+        }
+      }
+
+      SMTPClient client=new SMTPClient();
+      try {
+        int reply;
+        client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
+
+        reply = client.getReplyCode();
+
+        if (!SMTPReply.isPositiveCompletion(reply)) {
+          client.disconnect();
+          throw new ServletModuleExc("SMTP server refused connection.");
+        }
+
+        client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
+
+        client.disconnect();
+        //mission accomplished
+        deliver(req, res, mergeData, sentMailTemplate);
+      }
+      catch(IOException e) {
+        if(client.isConnected()) {
+          try {
+            client.disconnect();
+          } catch(IOException f) {
+            // do nothing
+          }
+        }
+        throw new ServletModuleFailure(e);
+      }
+    }
+  }
+
+
+  /*
+   * Method for querying a lucene index
+   */
+  public void search(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+    try {
+      int increment=10;
+
+      HttpSession session = req.getSession(false);
+
+      String queryString="";
+
+      SimpleHash mergeData = new SimpleHash();
+
+      KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");
+      UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");
+      TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");
+      TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");
+      TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");
+      ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");
+      TopicSearchTerm topicTerm = new TopicSearchTerm();
+      ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
+      AudioSearchTerm audioTerm = new AudioSearchTerm();
+      VideoSearchTerm videoTerm = new VideoSearchTerm();
+
+      //make the query available to subsequent iterations
+
+      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
+        String pName=(String)theParams.nextElement();
+        if (pName.startsWith("search_")){
+          mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
+        }
+      }
+
+      try{
+        mergeData.put("topics", themenModule.getTopicsAsSimpleList());
+      }
+      catch(ModuleException e) {
+        logger.debug("Can't get topics: " + e.toString());
+      }
+
+      String searchBackValue = req.getParameter("search_back");
+      String searchForwardValue = req.getParameter("search_forward");
+
+      if (searchBackValue != null){
+        int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
+        int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;
+        if (newPosition<0)
+          newPosition=0;
+        if (newPosition >= totalHits)
+          newPosition=totalHits-1;
+        session.setAttribute("positionInResults",new Integer(newPosition));
+      }
+      else {
+        if (searchForwardValue != null){
+          int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
+          int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;
+          if (newPosition<0)
+            newPosition=0;
+          if (newPosition >= totalHits)
+            newPosition=totalHits-1;
+
+          session.setAttribute("positionInResults",new Integer(newPosition));
+        }
+        else {
+          String indexPath=configuration.getString("IndexPath");
+
+
+          String creatorFragment = creatorTerm.makeTerm(req);
+          if (creatorFragment != null){
+            queryString = queryString + " +" + creatorFragment;
+          }
+
+          // search title, description, and content for something
+          // the contentTerm uses param "search_boolean" to combine its terms
+          String contentFragment = contentTerm.makeTerm(req);
+          if (contentFragment != null){
+            logger.debug("contentFragment: " + contentFragment);
+            queryString = queryString + " +" + contentFragment;
+          }
+
+          String topicFragment = topicTerm.makeTerm(req);
+          if (topicFragment != null){
+            queryString = queryString + " +" + topicFragment;
+          }
+
+          String imagesFragment = imagesTerm.makeTerm(req);
+          if (imagesFragment != null){
+            queryString = queryString + " +" + imagesFragment;
+          }
+
+          String audioFragment = audioTerm.makeTerm(req);
+          if (audioFragment != null){
+            queryString = queryString + " +" + audioFragment;
+          }
+
+          String videoFragment = videoTerm.makeTerm(req);
+          if (videoFragment != null){
+            queryString = queryString + " +" + videoFragment;
+          }
+
+          if (queryString == null || queryString == ""){
+            queryString = "";
+          }
+          else{
+            try{
+              Searcher searcher = null;
+              try {
+                searcher = new IndexSearcher(indexPath);
+              }
+              catch(IOException e) {
+                logger.debug("Can't open indexPath: " + indexPath);
+                throw new ServletModuleExc("Problem with Search Index! : "+ e.toString());
+              }
+
+              Query query = null;
+              try {
+                query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
+              }
+              catch(Exception e) {
+                searcher.close();
+                logger.debug("Query don't parse: " + queryString);
+                throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')");
+              }
+
+              Hits hits = null;
+              try {
+                hits = searcher.search(query);
+              }
+              catch(IOException e) {
+                searcher.close();
+                logger.debug("Can't get hits: " + e.toString());
+                throw new ServletModuleExc("Problem getting hits!");
+              }
+
+              int start = 0;
+              int end = hits.length();
+
+              String sortBy=req.getParameter("search_sort");
+              if (sortBy == null || sortBy.equals("")){
+                throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
+              }
+
+              // here is where the documents will go for storage across sessions
+              ArrayList theDocumentsSorted = new ArrayList();
+
+              if (sortBy.equals("score")){
+                for(int i = start; i < end; i++) {
+                  theDocumentsSorted.add(hits.doc(i));
+                }
+              }
+              else{
+                // then we'll sort by date!
+                Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be
+                for(int i = start; i < end; i++) {
+                  String creationDate=(hits.doc(i)).get("creationDate");
+                  // do a little dance in case two contents created at the same second!
+                  if (dateToPosition.containsKey(creationDate)){
+                    ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
+                  }
+                  else{
+                    ArrayList thePositions = new ArrayList();
+                    thePositions.add(new Integer(i));
+                    dateToPosition.put(creationDate,thePositions);
+                  }
+                }
+                Set keys = dateToPosition.keySet();
+                ArrayList keyList= new ArrayList(keys);
+                Collections.sort(keyList);
+                if (sortBy.equals("date_desc")){
+                  Collections.reverse(keyList);
+                }
+                else{
+                  if (!sortBy.equals("date_asc")){
+                    throw new ServletModuleExc("don't know how to sort by: "+ sortBy);
+                  }
+                }
+                ListIterator keyTraverser = keyList.listIterator();
+                while (keyTraverser.hasNext()){
+                  ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));
+                  ListIterator positionsTraverser=positions.listIterator();
+                  while (positionsTraverser.hasNext()){
+                    theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));
+                  }
+                }
+              }
+
+              try{
+                searcher.close();
+              }
+              catch (IOException e){
+                logger.debug("Can't close searcher: " + e.toString());
+                throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
+              }
+
+
+              session.removeAttribute("numberOfHits");
+              session.removeAttribute("theDocumentsSorted");
+              session.removeAttribute("positionInResults");
+
+              session.setAttribute("numberOfHits",new Integer(end));
+              session.setAttribute("theDocumentsSorted",theDocumentsSorted);
+              session.setAttribute("positionInResults",new Integer(0));
+
+            }
+            catch (IOException e){
+              logger.debug("Can't close searcher: " + e.toString());
+              throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
+            }
+          }
+        }
+      }
+
+      try {
+        ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");
+        if (theDocs != null){
+
+          mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());
+          SimpleList theHits = new SimpleList();
+          int pIR=((Integer)session.getAttribute("positionInResults")).intValue();
+          int terminus;
+          int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();
+
+          if (!(pIR+increment>=numHits)){
+            mergeData.put("hasNext","y");
+          }
+          if (pIR>0){
+            mergeData.put("hasPrevious","y");
+          }
+
+          if ((pIR+increment)>numHits){
+            terminus=numHits;
+          }
+          else {
+            terminus=pIR+increment;
+          }
+          for(int i = pIR; i < terminus; i++) {
+            SimpleHash h = new SimpleHash();
+            Document theHit = (Document)theDocs.get(i);
+            whereTerm.returnMeta(h,theHit);
+            creatorTerm.returnMeta(h,theHit);
+            titleTerm.returnMeta(h,theHit);
+            descriptionTerm.returnMeta(h,theHit);
+            dateTerm.returnMeta(h,theHit);
+            imagesTerm.returnMeta(h,theHit);
+            audioTerm.returnMeta(h,theHit);
+            videoTerm.returnMeta(h,theHit);
+            theHits.add(h);
+          }
+          mergeData.put("hits",theHits);
+        }
+      }
+      catch (Throwable e) {
+        logger.error("Can't iterate over hits: " + e.toString());
+
+        throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
+      }
+
+      mergeData.put("queryString",queryString);
+      deliver(req,res,mergeData,searchResultsTemplate);
+    }
+    catch (NullPointerException n){
+      throw new ServletModuleFailure("Null Pointer: "+n.toString(), n);
+    }
+  }
+
+  /*
+   * Method for dynamically generating a pdf from a fo file
+   */
+  public void getpdf(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+    String ID_REQUEST_PARAM = "id";
+    String language = req.getParameter("language");
+    String generateFO=configuration.getString("GenerateFO");
+    String generatePDF=configuration.getString("GeneratePDF");
+
+
+    //don't do anything if we are not making FO files, or if we are
+    //pregenerating PDF's
+    if (generateFO.equals("yes") && generatePDF.equals("no")){
+      //fop complains unless you do the logging this way
+      org.apache.log.Logger log = null;
+      Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
+      log = hierarchy.getLoggerFor("fop");
+      log.setPriority(Priority.WARN);
+
+      String producerStorageRoot=configuration.getString("Producer.StorageRoot");
+      String producerDocRoot=configuration.getString("Producer.DocRoot");
+      //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
+      String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");
+      try {
+        String idParam = req.getParameter(ID_REQUEST_PARAM);
+        if (idParam != null) {
+          EntityContent contentEnt =
+            (EntityContent)contentModule.getById(idParam);
+          String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));
+          String foFile;
+
+          if (language == null){
+            foFile = producerStorageRoot + producerDocRoot + "/"
+              + publishPath  + idParam + ".fo";
+          }
+          else{
+            foFile = producerStorageRoot + producerDocRoot + "/"
+              + language + publishPath  + idParam + ".fo";
+          }
+          logger.debug("USING FILES" + foFile + " and " + xslSheet);
+          XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
+                                                        new File(xslSheet));
+
+          ByteArrayOutputStream out = new ByteArrayOutputStream();
+          res.setContentType("application/pdf");
+
+          Driver driver = new Driver();
+          driver.setLogger(log);
+          driver.setRenderer(Driver.RENDER_PDF);
+          driver.setOutputStream(out);
+          driver.render(input.getParser(), input.getInputSource());
+
+          byte[] content = out.toByteArray();
+          res.setContentLength(content.length);
+          res.getOutputStream().write(content);
+          res.getOutputStream().flush();
+        }
+        else {
+          throw new ServletModuleUserExc("Missing id parameter.");
+        }
+      }
+      catch (Exception ex) {
+        logger.error(ex.toString());
+        throw new ServletModuleFailure(ex);
+      }
+    } else {
+      throw new ServletModuleExc("Can't generate a PDF because the config tells me not to.");
+    }
+  }
+
+  private void _throwBadContentType (String fileName, String contentType)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+
+    logger.error("Wrong file type uploaded!: " + fileName+" "
+                          +contentType);
+    throw new ServletModuleUserExc("The file you uploaded is of the "
+                                         +"following mime-type: "+contentType
+                                         +", we do not support this mime-type. "
+                                         +"Error One or more files of unrecognized type. Sorry");
+  }
+
+  protected String createOneTimePasswd(){
+    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);
+  }
+
+
+  /* this is an overwritten method of ServletModule in order
+     to use different bundles for open and admin */
+  public void deliver(HttpServletRequest req, HttpServletResponse res,
+                      TemplateModelRoot rtm, TemplateModelRoot popups,
+                      String templateFilename) throws ServletModuleFailure
+  {
+    if (rtm == null) rtm = new SimpleHash();
+    try {
+      PrintWriter out = res.getWriter();
+      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,
+                                    getLocale(req), "bundles.open");
+      out.close();
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+}
+
+
+
index 0fe5755..6d4be8e 100755 (executable)
@@ -46,7 +46,6 @@ import mir.generator.Generator;
 import mir.log.LoggerWrapper;
 import mir.producer.ProducerFactory;
 import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
 import mir.servlet.ServletModuleFailure;
 import mir.util.NullWriter;
 import mir.util.ResourceBundleGeneratorFunction;
index 2ba8613..4b16869 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.servlet;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.net.URLEncoder;\r
-import java.util.Map;\r
-\r
-import javax.servlet.ServletContext;\r
-import javax.servlet.ServletOutputStream;\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.Entity;\r
-import mir.entity.EntityList;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaHelper;\r
-import mir.media.MirMedia;\r
-import mir.misc.FileHandler;\r
-import mir.misc.FileHandlerException;\r
-import mir.misc.FileHandlerUserException;\r
-import mir.misc.WebdbMultipartRequest;\r
-import mir.module.ModuleException;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleUserExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.storage.StorageObjectFailure;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUploadedMedia;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.media.MediaRequest;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseMediafolder;\r
-import freemarker.template.SimpleHash;\r
-import freemarker.template.SimpleList;\r
-\r
-/*\r
- *  ServletModuleBilder -\r
- *  liefert HTML fuer Bilder\r
- *\r
- * @version $Id: ServletModuleUploadedMedia.java,v 1.19 2003/03/06 05:40:40 zapata Exp $\r
- * @author RK, the mir-coders group\r
- */\r
-\r
-public abstract class ServletModuleUploadedMedia\r
-        extends mir.servlet.ServletModule {\r
-\r
-  //private static DatabaseRights dbRights;\r
-\r
-  public static ServletModule getInstance() {\r
-    return null;\r
-  }\r
-\r
-  public ServletModuleUploadedMedia() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.UploadedMedia");\r
-  }\r
-\r
-  public void insert(HttpServletRequest req, HttpServletResponse res)\r
-          throws ServletModuleExc, ServletModuleUserExc {\r
-    try {\r
-      EntityUsers user = _getUser(req);\r
-      MediaRequest mediaReq =  new MediaRequest(user.getId(), false);\r
-      WebdbMultipartRequest mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
-      EntityList mediaList = mediaReq.getEntityList();\r
-      String articleid = (String) mp.getParameters().get("articleid");\r
-\r
-      if (articleid!=null) {\r
-        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);\r
-\r
-        mediaList.rewind();\r
-\r
-        while (mediaList.hasNext()) {\r
-          entContent.attach( ( (EntityUploadedMedia) mediaList.next()).getId());\r
-        }\r
-        mediaList.rewind();\r
-\r
-        ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, req, res);\r
-\r
-        return;\r
-      }\r
-\r
-      SimpleHash mergeData = new SimpleHash();\r
-      SimpleHash popups = new SimpleHash();\r
-      mergeData.put("contentlist", mediaList);\r
-      if (mediaList.getOrder() != null) {\r
-        mergeData.put("order", mediaList.getOrder());\r
-        mergeData.put("order_encoded", URLEncoder.encode(mediaList.getOrder()));\r
-      }\r
-      mergeData.put("count", (new Integer(mediaList.getCount())).toString());\r
-      mergeData.put("from", (new Integer(mediaList.getFrom())).toString());\r
-      mergeData.put("to", (new Integer(mediaList.getTo())).toString());\r
-      if (mediaList.hasNextBatch())\r
-        mergeData.put("next", (new Integer(mediaList.getNextBatch())).toString());\r
-      if (mediaList.hasPrevBatch())\r
-        mergeData.put("prev", (new Integer(mediaList.getPrevBatch())).toString());\r
-      //fetch the popups\r
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());\r
-      // raus damit\r
-      deliver(req, res, mergeData, popups, templateListString);\r
-    }\r
-    catch (FileHandlerUserException e) {\r
-      logger.error("ServletModuleUploadedMedia.insert: " + e.getMessage());\r
-      throw new ServletModuleUserExc(e.getMessage());\r
-    }\r
-    catch (FileHandlerException e) {\r
-      throw new ServletModuleFailure("upload -- media handling exception " + e.toString(), e);\r
-    }\r
-    catch (StorageObjectFailure e) {\r
-      throw new ServletModuleFailure("upload -- storageobjectexception " + e.toString(), e);\r
-    }\r
-    catch (IOException e) {\r
-      throw new ServletModuleFailure("upload -- ioexception " + e.toString(), e);\r
-    }\r
-    catch (PropertiesConfigExc e) {\r
-      throw new ServletModuleFailure("upload -- configexception " + e.toString(), e);\r
-    }\r
-    catch (Throwable t) {\r
-      throw new ServletModuleFailure("upload -- exception " + t.toString(), t);\r
-    }\r
-  }\r
-\r
-  public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {\r
-\r
-    try {\r
-      EntityUsers user = _getUser(req);\r
-      WebdbMultipartRequest mp = new WebdbMultipartRequest(req, null);\r
-      Map parameters = mp.getParameters();\r
-\r
-      parameters.put("to_publisher", user.getId());\r
-      parameters.put("is_produced", "0");\r
-      if (!parameters.containsKey("is_published"))\r
-        parameters.put("is_published", "0");\r
-\r
-      String id = mainModule.set(parameters);\r
-      logger.debug("update: media ID = " + id);\r
-      _edit(id, req, res);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);\r
-    }\r
-\r
-  }\r
-\r
-\r
-  public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {\r
-    // Parameter auswerten\r
-    SimpleHash mergeData = new SimpleHash();\r
-    SimpleHash popups = new SimpleHash();\r
-\r
-    String query_text = req.getParameter("query_text");\r
-    mergeData.put("query_text", query_text);\r
-    if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text));\r
-    String query_field = req.getParameter("query_field");\r
-    mergeData.put("query_field", query_field);\r
-    String query_is_published = req.getParameter("query_is_published");\r
-    mergeData.put("query_is_published", query_is_published);\r
-    String query_media_folder = req.getParameter("query_media_folder");\r
-    mergeData.put("query_media_folder", query_media_folder);\r
-    String offset = req.getParameter("offset");\r
-    if (offset == null || offset.equals("")) offset = "0";\r
-    mergeData.put("offset", offset);\r
-\r
-    String order = req.getParameter("order");\r
-    if (order == null || order.equals("")) order = "webdb_lastchange desc";\r
-\r
-    // if in connection mode to content\r
-    String cid = req.getParameter("cid");\r
-    mergeData.put("cid", cid);\r
-\r
-\r
-    // sql basteln\r
-    String whereClause = "";\r
-    boolean isFirst = true;\r
-    if (query_text != null && !query_text.equalsIgnoreCase("")) {\r
-      whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')";\r
-      isFirst = false;\r
-    }\r
-    if (query_is_published != null && !query_is_published.equals("")) {\r
-      if (isFirst == false) whereClause += " and ";\r
-      whereClause += "is_published='" + query_is_published + "'";\r
-      isFirst = false;\r
-    }\r
-    if (query_media_folder != null && !query_media_folder.equals("")) {\r
-      if (isFirst == false) whereClause += " and ";\r
-      whereClause += "to_media_folder='" + query_media_folder + "'";\r
-    }\r
-    //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);\r
-\r
-    // fetch and deliver\r
-    try {\r
-      if (query_text != null || query_is_published != null || query_media_folder != null) {\r
-        EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10);\r
-        if (theList != null) {\r
-          mergeData.put("contentlist", theList);\r
-          if (theList.getOrder() != null) {\r
-            mergeData.put("order", theList.getOrder());\r
-            mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));\r
-          }\r
-          mergeData.put("count", (new Integer(theList.getCount())).toString());\r
-          mergeData.put("from", (new Integer(theList.getFrom())).toString());\r
-          mergeData.put("to", (new Integer(theList.getTo())).toString());\r
-          if (theList.hasNextBatch())\r
-            mergeData.put("next", (new Integer(theList.getNextBatch())).toString());\r
-          if (theList.hasPrevBatch())\r
-            mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());\r
-        }\r
-      }\r
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());\r
-\r
-      deliver(req, res, mergeData, popups, templateListString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-\r
-  public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {\r
-    try {\r
-      SimpleHash mergeData = new SimpleHash();\r
-      SimpleHash popups = new SimpleHash();\r
-      String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems");\r
-      String numOfMedia = req.getParameter("medianum");\r
-\r
-      mergeData.put("new", "1");\r
-      mergeData.put("articleid", req.getParameter("articleid"));\r
-\r
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());\r
-\r
-      if (numOfMedia==null || numOfMedia.equals("")) {\r
-        numOfMedia="1";\r
-      }\r
-      else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
-        numOfMedia = maxMedia;\r
-      }\r
-\r
-      int mediaNum = Integer.parseInt(numOfMedia);\r
-      SimpleList mediaFields = new SimpleList();\r
-      for(int i =0; i<mediaNum;i++){\r
-        Integer mNum = new Integer(i+1);\r
-        mediaFields.add(mNum.toString());\r
-      }\r
-      mergeData.put("medianum",numOfMedia);\r
-      mergeData.put("mediafields",mediaFields);\r
-      deliver(req, res, mergeData, popups, templateObjektString);\r
-    }\r
-    catch (Exception e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {\r
-    String idParam = req.getParameter("id");\r
-    _edit(idParam, req, res);\r
-  }\r
-\r
-  private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {\r
-    if (idParam != null && !idParam.equals("")) {\r
-      try {\r
-        SimpleHash popups = new SimpleHash();\r
-        popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());\r
-        deliver(req, res, mainModule.getById(idParam), popups,\r
-                templateObjektString);\r
-      }\r
-      catch (Throwable e) {\r
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-    else {\r
-      throw new ServletModuleExc("ServletmoduleUploadedMedia :: _edit without id");\r
-    }\r
-  }\r
-\r
-\r
-  /** @todo should be in ServletModule.java */\r
-  private EntityUsers _getUser(HttpServletRequest req) {\r
-    HttpSession session = req.getSession(false);\r
-    return (EntityUsers) session.getAttribute("login.uid");\r
-  }\r
-\r
-  public void getMedia(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String idParam = req.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
-        res.setContentType(ctx.getMimeType(fName));\r
-        //important that before calling this res.getWriter was not called first\r
-        ServletOutputStream out = res.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
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-    else logger.error("id not specified.");\r
-    // no exception allowed\r
-  }\r
-\r
-  public void getIcon(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String idParam = req.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.getIcon(ent);\r
-\r
-        res.setContentType(ctx.getMimeType(fName));\r
-        //important that before calling this res.getWriter was not called first\r
-        ServletOutputStream out = res.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
-        throw new ServletModuleFailure(e);\r
-      }\r
-    }\r
-    else logger.error("getIcon: id not specified.");\r
-    // no exception allowed\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 the com.oreilly.servlet library, 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.IOException;
+import java.io.InputStream;
+import java.net.URLEncoder;
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletOutputStream;
+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.Entity;
+import mir.entity.EntityList;
+import mir.log.LoggerWrapper;
+import mir.media.MediaHelper;
+import mir.media.MirMedia;
+import mir.misc.FileHandler;
+import mir.misc.FileHandlerException;
+import mir.misc.FileHandlerUserException;
+import mir.misc.WebdbMultipartRequest;
+import mir.servlet.ServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.storage.StorageObjectFailure;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUploadedMedia;
+import mircoders.entity.EntityUsers;
+import mircoders.media.MediaRequest;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseMediafolder;
+import freemarker.template.SimpleHash;
+import freemarker.template.SimpleList;
+
+/*
+ *  ServletModuleBilder -
+ *  liefert HTML fuer Bilder
+ *
+ * @version $Id: ServletModuleUploadedMedia.java,v 1.20 2003/03/08 17:18:19 idfx Exp $
+ * @author RK, the mir-coders group
+ */
+
+public abstract class ServletModuleUploadedMedia
+        extends mir.servlet.ServletModule {
+
+  //private static DatabaseRights dbRights;
+
+  public static ServletModule getInstance() {
+    return null;
+  }
+
+  public ServletModuleUploadedMedia() {
+    super();
+    logger = new LoggerWrapper("ServletModule.UploadedMedia");
+  }
+
+  public void insert(HttpServletRequest req, HttpServletResponse res)
+          throws ServletModuleExc, ServletModuleUserExc {
+    try {
+      EntityUsers user = _getUser(req);
+      MediaRequest mediaReq =  new MediaRequest(user.getId(), false);
+      WebdbMultipartRequest mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
+      EntityList mediaList = mediaReq.getEntityList();
+      String articleid = (String) mp.getParameters().get("articleid");
+
+      if (articleid!=null) {
+        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
+
+        mediaList.rewind();
+
+        while (mediaList.hasNext()) {
+          entContent.attach( ( (EntityUploadedMedia) mediaList.next()).getId());
+        }
+        mediaList.rewind();
+
+        ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, req, res);
+
+        return;
+      }
+
+      SimpleHash mergeData = new SimpleHash();
+      SimpleHash popups = new SimpleHash();
+      mergeData.put("contentlist", mediaList);
+      if (mediaList.getOrder() != null) {
+        mergeData.put("order", mediaList.getOrder());
+        mergeData.put("order_encoded", URLEncoder.encode(mediaList.getOrder()));
+      }
+      mergeData.put("count", (new Integer(mediaList.getCount())).toString());
+      mergeData.put("from", (new Integer(mediaList.getFrom())).toString());
+      mergeData.put("to", (new Integer(mediaList.getTo())).toString());
+      if (mediaList.hasNextBatch())
+        mergeData.put("next", (new Integer(mediaList.getNextBatch())).toString());
+      if (mediaList.hasPrevBatch())
+        mergeData.put("prev", (new Integer(mediaList.getPrevBatch())).toString());
+      //fetch the popups
+      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
+      // raus damit
+      deliver(req, res, mergeData, popups, templateListString);
+    }
+    catch (FileHandlerUserException e) {
+      logger.error("ServletModuleUploadedMedia.insert: " + e.getMessage());
+      throw new ServletModuleUserExc(e.getMessage());
+    }
+    catch (FileHandlerException e) {
+      throw new ServletModuleFailure("upload -- media handling exception " + e.toString(), e);
+    }
+    catch (StorageObjectFailure e) {
+      throw new ServletModuleFailure("upload -- storageobjectexception " + e.toString(), e);
+    }
+    catch (IOException e) {
+      throw new ServletModuleFailure("upload -- ioexception " + e.toString(), e);
+    }
+    catch (PropertiesConfigExc e) {
+      throw new ServletModuleFailure("upload -- configexception " + e.toString(), e);
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure("upload -- exception " + t.toString(), t);
+    }
+  }
+
+  public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+
+    try {
+      EntityUsers user = _getUser(req);
+      WebdbMultipartRequest mp = new WebdbMultipartRequest(req, null);
+      Map parameters = mp.getParameters();
+
+      parameters.put("to_publisher", user.getId());
+      parameters.put("is_produced", "0");
+      if (!parameters.containsKey("is_published"))
+        parameters.put("is_published", "0");
+
+      String id = mainModule.set(parameters);
+      logger.debug("update: media ID = " + id);
+      _edit(id, req, res);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);
+    }
+
+  }
+
+
+  public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+    // Parameter auswerten
+    SimpleHash mergeData = new SimpleHash();
+    SimpleHash popups = new SimpleHash();
+
+    String query_text = req.getParameter("query_text");
+    mergeData.put("query_text", query_text);
+    if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text));
+    String query_field = req.getParameter("query_field");
+    mergeData.put("query_field", query_field);
+    String query_is_published = req.getParameter("query_is_published");
+    mergeData.put("query_is_published", query_is_published);
+    String query_media_folder = req.getParameter("query_media_folder");
+    mergeData.put("query_media_folder", query_media_folder);
+    String offset = req.getParameter("offset");
+    if (offset == null || offset.equals("")) offset = "0";
+    mergeData.put("offset", offset);
+
+    String order = req.getParameter("order");
+    if (order == null || order.equals("")) order = "webdb_lastchange desc";
+
+    // if in connection mode to content
+    String cid = req.getParameter("cid");
+    mergeData.put("cid", cid);
+
+
+    // sql basteln
+    String whereClause = "";
+    boolean isFirst = true;
+    if (query_text != null && !query_text.equalsIgnoreCase("")) {
+      whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')";
+      isFirst = false;
+    }
+    if (query_is_published != null && !query_is_published.equals("")) {
+      if (isFirst == false) whereClause += " and ";
+      whereClause += "is_published='" + query_is_published + "'";
+      isFirst = false;
+    }
+    if (query_media_folder != null && !query_media_folder.equals("")) {
+      if (isFirst == false) whereClause += " and ";
+      whereClause += "to_media_folder='" + query_media_folder + "'";
+    }
+    //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
+
+    // fetch and deliver
+    try {
+      if (query_text != null || query_is_published != null || query_media_folder != null) {
+        EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10);
+        if (theList != null) {
+          mergeData.put("contentlist", theList);
+          if (theList.getOrder() != null) {
+            mergeData.put("order", theList.getOrder());
+            mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
+          }
+          mergeData.put("count", (new Integer(theList.getCount())).toString());
+          mergeData.put("from", (new Integer(theList.getFrom())).toString());
+          mergeData.put("to", (new Integer(theList.getTo())).toString());
+          if (theList.hasNextBatch())
+            mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
+          if (theList.hasPrevBatch())
+            mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
+        }
+      }
+      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
+
+      deliver(req, res, mergeData, popups, templateListString);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+
+  public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+    try {
+      SimpleHash mergeData = new SimpleHash();
+      SimpleHash popups = new SimpleHash();
+      String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems");
+      String numOfMedia = req.getParameter("medianum");
+
+      mergeData.put("new", "1");
+      mergeData.put("articleid", req.getParameter("articleid"));
+
+      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
+
+      if (numOfMedia==null || numOfMedia.equals("")) {
+        numOfMedia="1";
+      }
+      else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
+        numOfMedia = maxMedia;
+      }
+
+      int mediaNum = Integer.parseInt(numOfMedia);
+      SimpleList mediaFields = new SimpleList();
+      for(int i =0; i<mediaNum;i++){
+        Integer mNum = new Integer(i+1);
+        mediaFields.add(mNum.toString());
+      }
+      mergeData.put("medianum",numOfMedia);
+      mergeData.put("mediafields",mediaFields);
+      deliver(req, res, mergeData, popups, templateObjektString);
+    }
+    catch (Exception e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+    String idParam = req.getParameter("id");
+    _edit(idParam, req, res);
+  }
+
+  private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
+    if (idParam != null && !idParam.equals("")) {
+      try {
+        SimpleHash popups = new SimpleHash();
+        popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
+        deliver(req, res, mainModule.getById(idParam), popups,
+                templateObjektString);
+      }
+      catch (Throwable e) {
+        throw new ServletModuleFailure(e);
+      }
+    }
+    else {
+      throw new ServletModuleExc("ServletmoduleUploadedMedia :: _edit without id");
+    }
+  }
+
+
+  /** @todo should be in ServletModule.java */
+  private EntityUsers _getUser(HttpServletRequest req) {
+    HttpSession session = req.getSession(false);
+    return (EntityUsers) session.getAttribute("login.uid");
+  }
+
+  public void getMedia(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String idParam = req.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);
+
+        res.setContentType(ctx.getMimeType(fName));
+        //important that before calling this res.getWriter was not called first
+        ServletOutputStream out = res.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 req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String idParam = req.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.getIcon(ent);
+
+        res.setContentType(ctx.getMimeType(fName));
+        //important that before calling this res.getWriter was not called first
+        ServletOutputStream out = res.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("getIcon: id not specified.");
+    // no exception allowed
+  }
+
+}
+
+
index 09b3ebc..1ad22ea 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 the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.servlet;\r
-\r
-import java.util.Map;\r
-\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.module.ModuleException;\r
-import mir.servlet.*;\r
-import mir.storage.StorageObjectFailure;\r
-import mir.util.HTTPRequestParser;\r
-import mircoders.module.ModuleUsers;\r
-import mircoders.storage.DatabaseUsers;\r
-import freemarker.template.SimpleHash;\r
-\r
-/*\r
- *  ServletModuleUsers -\r
- *  liefert HTML fuer Users\r
- *\r
- *\r
- * @author RK\r
- */\r
-\r
-public class ServletModuleUsers extends ServletModule\r
-{\r
-  private static ServletModuleUsers instance = new ServletModuleUsers();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private ServletModuleUsers() {\r
-    super();\r
-    logger = new LoggerWrapper("ServletModule.Users");\r
-\r
-    templateListString = configuration.getString("ServletModule.Users.ListTemplate");\r
-    templateObjektString = configuration.getString("ServletModule.Users.ObjektTemplate");\r
-    templateConfirmString = configuration.getString("ServletModule.Users.ConfirmTemplate");\r
-\r
-    try {\r
-      mainModule = new ModuleUsers(DatabaseUsers.getInstance());\r
-    }\r
-    catch (StorageObjectFailure e) {\r
-      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());\r
-    }\r
-  }\r
-\r
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc\r
-  {\r
-    String idParam = req.getParameter("id");\r
-\r
-    if (idParam == null)\r
-      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");\r
-\r
-    try {\r
-      deliver(req, res, mainModule.getById(idParam), templateObjektString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void add(HttpServletRequest req, HttpServletResponse res)\r
-      throws ServletModuleExc\r
-  {\r
-    try {\r
-      SimpleHash mergeData = new SimpleHash();\r
-      mergeData.put("new", "1");\r
-      deliver(req, res, mergeData, templateObjektString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public String checkPassword(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
-\r
-      if (newPassword.length() == 0 || newPassword2.length() == 0) {\r
-        throw new ServletModuleUserExc("The new password must be entered twice!");\r
-      }\r
-\r
-      if (!newPassword.equals(newPassword2)) {\r
-        throw new ServletModuleUserExc("New password differes from confirmation");\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
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-\r
-      String newPassword=checkPassword(requestParser);\r
-      if (newPassword!=null)\r
-        withValues.put("password", newPassword);\r
-      else\r
-        throw new ServletModuleUserExc("Password is empty");\r
-\r
-      String id = mainModule.add(withValues);\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
-\r
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
-\r
-      String newPassword=checkPassword(requestParser);\r
-      if (newPassword!=null)\r
-        withValues.put("password", newPassword);\r
-\r
-      mainModule.set(withValues);\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
-\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 the com.oreilly.servlet library, 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.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.ServletModuleUserExc;
+import mir.storage.StorageObjectFailure;
+import mir.util.HTTPRequestParser;
+import mircoders.module.ModuleUsers;
+import mircoders.storage.DatabaseUsers;
+import freemarker.template.SimpleHash;
+
+/*
+ *  ServletModuleUsers -
+ *  liefert HTML fuer Users
+ *
+ *
+ * @author RK
+ */
+
+public class ServletModuleUsers extends ServletModule
+{
+  private static ServletModuleUsers instance = new ServletModuleUsers();
+  public static ServletModule getInstance() { return instance; }
+
+  private ServletModuleUsers() {
+    super();
+    logger = new LoggerWrapper("ServletModule.Users");
+
+    templateListString = configuration.getString("ServletModule.Users.ListTemplate");
+    templateObjektString = configuration.getString("ServletModule.Users.ObjektTemplate");
+    templateConfirmString = configuration.getString("ServletModule.Users.ConfirmTemplate");
+
+    try {
+      mainModule = new ModuleUsers(DatabaseUsers.getInstance());
+    }
+    catch (StorageObjectFailure e) {
+      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());
+    }
+  }
+
+  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
+  {
+    String idParam = req.getParameter("id");
+
+    if (idParam == null)
+      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
+
+    try {
+      deliver(req, res, mainModule.getById(idParam), templateObjektString);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void add(HttpServletRequest req, HttpServletResponse res)
+      throws ServletModuleExc
+  {
+    try {
+      SimpleHash mergeData = new SimpleHash();
+      mergeData.put("new", "1");
+      deliver(req, res, mergeData, templateObjektString);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public String checkPassword(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", "");
+
+      if (newPassword.length() == 0 || newPassword2.length() == 0) {
+        throw new ServletModuleUserExc("The new password must be entered twice!");
+      }
+
+      if (!newPassword.equals(newPassword2)) {
+        throw new ServletModuleUserExc("New password differes from confirmation");
+      }
+
+      return newPassword;
+    }
+    else
+      return null;
+  }
+
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+
+      String newPassword=checkPassword(requestParser);
+      if (newPassword!=null)
+        withValues.put("password", newPassword);
+      else
+        throw new ServletModuleUserExc("Password is empty");
+
+      String id = mainModule.add(withValues);
+      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);
+
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+
+      String newPassword=checkPassword(requestParser);
+      if (newPassword!=null)
+        withValues.put("password", newPassword);
+
+      mainModule.set(withValues);
+
+      if (requestParser.hasParameter("returnurl"))
+        redirect(aResponse, requestParser.getParameter("returnurl"));
+      else
+        list(aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+
+}