reintroduced StringUtil.regexpReplace
[mir.git] / source / mir / servlet / ServletModule.java
index 13553f3..624db7a 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.servlet;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityAdapterEngine;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.storage.Database;
-import mir.util.HTTPRequestParser;
-import mir.util.URLBuilder;
-import mircoders.global.MirGlobal;
-import mircoders.localizer.MirLocalizerExc;
-import mircoders.servlet.ServletHelper;
-
-/**
- *
- */
-
-public abstract class ServletModule {
-  public String defaultAction;
-  protected LoggerWrapper logger;
-  protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
-  private static Locale fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");
-
-  protected AbstractModule mainModule;
-  protected String definition;
-  protected EntityAdapterModel model;
-
-  protected String listGenerator;
-  protected String editGenerator;
-  protected String deleteConfirmationGenerator;
-  protected int nrEntitiesPerListPage;
-
-  /** the list of parameters that need to be propagated in the list */
-  protected List propagatedParameters = new ArrayList();
-
-  public ServletModule(){
-    propagatedParameters.add("searchfield");
-    propagatedParameters.add("searchtext");
-    propagatedParameters.add("searchispublished");
-    propagatedParameters.add("searchstatus");
-    propagatedParameters.add("searchorder");
-
-    definition = null;
-    try {
-      model = MirGlobal.localizer().dataModel().adapterModel();
-    }
-    catch (MirLocalizerExc e) {
-      logger.error("Can't create model: " + e.toString());
-      throw new ServletModuleFailure("Can't retrieve model", e);
-    }
-
-    listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate");
-    editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate");
-    deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate");
-    nrEntitiesPerListPage =
-        configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize",
-        configuration.getInt("ServletModule.Default.ListSize", 20));
-
-  }
-
-
-  public void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {
-    MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + anObject, aDescription);
-  }
-
-  /**
-   * Singleton instance retrievel method. MUST be overridden in subclasses.
-   *
-   * @return ServletModule the single instance of the servletmodule class
-   */
-  public static ServletModule getInstance() {
-    return null;
-  }
-
-  /**
-   * Return the module name
-   */
-  protected String getOperationModuleName() {
-    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
-  }
-
-  public static Locale[] getLocales(HttpServletRequest aRequest) {
-    return new Locale[] { getLocale(aRequest), fallbackLocale };
-  }
-
-  /**
-   * Return the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public static Locale getLocale(HttpServletRequest aRequest) {
-    Locale locale = null;
-    HttpSession session = aRequest.getSession(false);
-    if (session != null) {
-      // session can be null in case of logout
-      locale = (Locale) session.getAttribute("locale");
-    }
-    // if there is nothing in the session get it fron the accept-language
-    if (locale == null) {
-      locale = aRequest.getLocale();
-    }
-    return locale;
-  }
-
-  /**
-   * get the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public Locale getFallbackLocale(HttpServletRequest aRequest) {
-    return fallbackLocale;
-  }
-
-  /**
-   * Function to specify the default ordering for lists. May be overridden.
-   *
-   *
-   * @return
-   */
-  public String getDefaultListOrdering() {
-
-    if (mainModule!=null && mainModule.getStorageObject()!=null) {
-      if (mainModule.getStorageObject().getFieldNames().contains("webdb_create"))
-        return "webdb_create desc";
-    }
-
-    return "id asc";
-  }
-
-  /**
-   * Generic list servlet method
-   */
-
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String where = requestParser.getParameter("where");
-    String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());
-    int offset = requestParser.getIntegerWithDefault("offset", 0);
-
-    returnList(aRequest, aResponse, where, order, offset);
-  }
-
-
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
-    returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, Collections.EMPTY_MAP);
-  }
-
-  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
-     String aWhereClause, String anOrderByClause, int anOffset, Map anOverridingRequestParameters) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest, anOverridingRequestParameters);
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      List list =
-         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
-
-      responseData.put("nexturl", null);
-      responseData.put("prevurl", null);
-      responseData.put("module", getOperationModuleName());
-
-      urlBuilder.setValue("module", getOperationModuleName());
-      urlBuilder.setValue("do", "list");
-      urlBuilder.setValue("where", aWhereClause);
-      urlBuilder.setValue("order", anOrderByClause);
-
-
-      urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
-      responseData.put("thisurl" , urlBuilder.getQuery());
-
-      propagateFields(requestParser, urlBuilder, responseData);
-
-      if (list.size()>=nrEntitiesPerListPage) {
-        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
-        responseData.put("nexturl" , urlBuilder.getQuery());
-      }
-
-      if (anOffset>0) {
-        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
-        responseData.put("prevurl" , urlBuilder.getQuery());
-      }
-
-      responseData.put("entities", list);
-      responseData.put("from" , Integer.toString(anOffset+1));
-      responseData.put("count", "?");
-      responseData.put("to", Integer.toString(anOffset+list.size()-1));
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {
-    try {
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      responseData.put("module", getOperationModuleName());
-      responseData.put("entity", anObject);
-      responseData.put("new", new Boolean(anIsNew));
-
-
-      urlBuilder.setValue("module", getOperationModuleName());
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
-      if (anIsNew)
-        urlBuilder.setValue("do", "add");
-      else {
-        urlBuilder.setValue("id", anId);
-        urlBuilder.setValue("do", "edit");
-      }
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic add servlet method
-   */
-  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-
-    Map object = new HashMap();
-
-    Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
-
-    while (i.hasNext())
-      object.put(i.next(), "");
-
-    initializeNewObject(object, aRequest, aResponse);
-
-    editObject(aRequest, aResponse, object, true, null);
-  }
-
-  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-  }
-
-  /**
-   * Generic edit servlet method
-   */
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    edit(aRequest, aResponse, aRequest.getParameter("id"));
-  }
-
-  /**
-   */
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic update servlet method
-   */
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      String id = aRequest.getParameter("id");
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
-      mainModule.set(withValues);
-
-      logAdminUsage(aRequest, id, "object modified");
-
-      String returnUrl = requestParser.getParameter("returnurl");
-
-      if (returnUrl!=null) {
-        ServletHelper.redirect(aResponse, returnUrl);
-      }
-      else {
-        edit(aRequest, aResponse, id);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * Generic insert servlet method
-   */
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());
-
-      String id = processInstertedObject(object, aRequest, aResponse);
-
-      logAdminUsage(aRequest, id, "object inserted");
-
-      String returnUrl = requestParser.getParameter("returnurl");
-
-      if (returnUrl!=null) {
-        ServletHelper.redirect(aResponse, returnUrl);
-      }
-      else {
-        edit(aRequest, aResponse, id);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *
-   */
-  public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      return mainModule.add(anObject);
-    }
-    catch (ModuleExc t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   * Generic delete confirmation servlet method
-   */
-  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      String idParam = aRequest.getParameter("id");
-      String confirmParam = aRequest.getParameter("confirm");
-
-      if (confirmParam != null && !confirmParam.equals("")) {
-        mainModule.deleteById(idParam);
-        logAdminUsage(aRequest, idParam, "object deleted");
-        ServletHelper.redirect(aResponse, aRequest.getParameter("okurl"));
-      }
-      else
-        ServletHelper.redirect(aResponse, aRequest.getParameter("cancelurl"));
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   * Generic delete servlet method
-   */
-  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      String idParam = aRequest.getParameter("id");
-
-      if (idParam == null)
-        throw new ServletModuleExc("Invalid call to delete: no id supplied");
-
-      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
-      responseData.put("module", getOperationModuleName());
-      responseData.put("id", idParam);
-      responseData.put("cancelurl", aRequest.getParameter("cancelurl"));
-      responseData.put("okurl", aRequest.getParameter("okurl"));
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   */
-  public String defaultAction() {
-    return defaultAction;
-  }
-
-  /**
-   * Gets the fields from a httprequest and matches them with the metadata from
-   * the database object. Returns the keys that match, with their values.
-   *
-   * @return Map with the values
-   */
-  public Map getIntersectingValues(HttpServletRequest aRequest, Database theStorage)
-      throws ServletModuleExc, ServletModuleFailure {
-
-    HTTPRequestParser parser;
-    List theFieldList;
-
-    parser = new HTTPRequestParser(aRequest);
-
-    theFieldList = theStorage.getFieldNames();
-
-    Map withValues = new HashMap();
-    String aField, aValue;
-
-    for (int i = 0; i < theFieldList.size(); i++) {
-      aField = (String) theFieldList.get(i);
-
-      aValue = parser.getParameter(aField);
-      if (aValue != null)
-        withValues.put(aField, aValue);
-    }
-    return withValues;
-  }
-
-  private void propagateFields(HTTPRequestParser aRequest, URLBuilder aUrlBuilder, Map aResponseData) {
-    Iterator i = propagatedParameters.iterator();
-    while (i.hasNext()) {
-      String parameter = (String) i.next();
-      String value = aRequest.getParameter(parameter);
-      aUrlBuilder.setValue(parameter, value);
-      aResponseData.put(parameter, value);
-    }
-  }
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.config.MirPropertiesConfiguration;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+import java.lang.reflect.Method;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Locale;\r
+\r
+public abstract class ServletModule {\r
+  private LoggerWrapper logger = new LoggerWrapper("ServletModule." + getName());\r
+  private MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
+  private final Locale fallbackLocale = new Locale(\r
+      getConfiguration().getString("Mir.Admin.FallbackLanguage", "en"), "");\r
+\r
+  protected ServletModule() {\r
+  }\r
+\r
+  /**\r
+   * Return the name of this module\r
+   */\r
+  protected String getName() {\r
+    return getClass().getName().substring("mircoders.servlet.ServletModule".length());\r
+  }\r
+\r
+  /**\r
+   * Return the logger for this module\r
+   */\r
+  protected LoggerWrapper getLogger() {\r
+    return logger;\r
+  }\r
+\r
+  /**\r
+   * Return the global mir configuration\r
+   */\r
+  protected MirPropertiesConfiguration getConfiguration() {\r
+    return configuration;\r
+  }\r
+\r
+  /**\r
+   * signature of request handling methods\r
+   */\r
+  private static final Class[] HANDLER_METHOD_SIGNATURE = {\r
+      HttpServletRequest.class, HttpServletResponse.class\r
+  };\r
+\r
+  protected void defaultAction(HttpServletRequest aRequest,\r
+                               HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleFailure, ServletModuleUserExc {\r
+    throw new ServletModuleExc("default action not defined for module " + getName());\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  protected Locale getFallbackLocale(HttpServletRequest aRequest) {\r
+    return fallbackLocale;\r
+  }\r
+\r
+  public Locale[] getLocales(HttpServletRequest aRequest) {\r
+    return new Locale[] { getLocale(aRequest), fallbackLocale };\r
+  }\r
+\r
+  /**\r
+   * Return the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public static Locale getLocale(HttpServletRequest aRequest) {\r
+    Locale locale = null;\r
+    HttpSession session = aRequest.getSession(false);\r
+    if (session != null) {\r
+      // session can be null in case of logout\r
+      locale = (Locale) session.getAttribute("locale");\r
+    }\r
+    // if there is nothing in the session get it fron the accept-language\r
+    if (locale == null) {\r
+      locale = aRequest.getLocale();\r
+    }\r
+    return locale;\r
+  }\r
+\r
+  public void handleRequest(HttpServletRequest aRequest,\r
+                            HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {\r
+    // look for requested method's name in the "do" http request param,\r
+    // if not present, use default action\r
+    String handlerName = aRequest.getParameter("do");\r
+    getLogger().debug("ServletModuleDispatch: " + getClass().getName() + "." + handlerName);\r
+\r
+    if (handlerName ==null) {\r
+      handlerName = "defaultAction";\r
+    }\r
+\r
+    Method method;\r
+    try {\r
+      method = getClass().getMethod(handlerName, HANDLER_METHOD_SIGNATURE);\r
+    }\r
+    catch (NoSuchMethodException e) {\r
+      throw new ServletModuleFailure("No handler found", e);\r
+    }\r
+\r
+    // ok, we have the method's name, now call it\r
+    try {\r
+        method.invoke(this, new Object[] { aRequest,aResponse });\r
+    }\r
+    catch (InvocationTargetException e) {\r
+      getLogger().error("Error while dispatching: " + e.getTargetException().getMessage(),\r
+          e.getTargetException());\r
+\r
+      throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());\r
+    }\r
+    catch (IllegalAccessException e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+}\r