update of the open session system: articles can now also be posted
[mir.git] / source / mircoders / localizer / basic / MirBasicPostingSessionHandler.java
index 921eb09..df23ded 100755 (executable)
  * 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.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.localizer.basic;
@@ -35,7 +35,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Random;
-import java.util.Vector;
+import java.util.*;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.entity.Entity;
@@ -67,11 +67,9 @@ import mircoders.storage.DatabaseContent;
  * @version 1.0
  */
 
-public class MirBasicPostingSessionHandler implements SessionHandler {
+public abstract class MirBasicPostingSessionHandler implements SessionHandler {
   protected LoggerWrapper logger;
   protected MirPropertiesConfiguration configuration;
-  protected ModuleComment commentModule;
-  protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance();
 
   public MirBasicPostingSessionHandler() {
     logger = new LoggerWrapper("Localizer.OpenPosting");
@@ -83,7 +81,6 @@ public class MirBasicPostingSessionHandler implements SessionHandler {
 
       throw new RuntimeException("Cannot load configuration: " + t.toString());
     }
-    commentModule= new ModuleComment(DatabaseComment.getInstance());
   }
 
   public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
@@ -96,242 +93,129 @@ public class MirBasicPostingSessionHandler implements SessionHandler {
     }
   };
 
-  protected Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
-    Map result = new HashMap();
-
-    Iterator i = aStorage.getFields().iterator();
-
-    while (i.hasNext()) {
-      String fieldName = (String) i.next();
-      Object value = aRequest.getParameter(fieldName);
-      if (value != null)
-        result.put(fieldName, value);
-    }
-
-    return result;
+  protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    initializeSession(aRequest, aSession);
+    initializeResponseData(aRequest, aSession, aResponse);
+    makeInitialResponse(aRequest, aSession, aResponse);
   }
 
+  public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    try {
 
-  protected String generateOnetimePassword() {
-    Random r = new Random();
-    int random = r.nextInt();
-
-    long l = System.currentTimeMillis();
-
-    l = (l*l*l*l)/random;
-    if (l<0)
-      l = l * -1;
+      try {
+        List validationErrors = new Vector();
 
-    String returnString = ""+l;
+        if (!shouldProcessRequest(aRequest, aSession, validationErrors)) {
+          initializeResponseData(aRequest, aSession, aResponse);
+          makeResponse(aRequest, aSession, aResponse, validationErrors);
+        }
+        else {
+          preProcessRequest(aRequest, aSession);
+          Iterator i = aRequest.getUploadedFiles().iterator();
+          while (i.hasNext()) {
+            processUploadedFile(aRequest, aSession, (UploadedFile) i.next());
+          }
+          postProcessRequest(aRequest, aSession);
+          initializeResponseData(aRequest, aSession, aResponse);
+          makeFinalResponse(aRequest, aSession, aResponse);
+          aSession.terminate();
+        }
+      }
+      catch (Throwable t) {
+        initializeResponseData(aRequest, aSession, aResponse);
+        makeErrorResponse(aRequest, aSession, aResponse, t);
+        aSession.terminate();
+      }
+    }
+    catch (Throwable t) {
+      aSession.terminate();
 
-    return returnString.substring(5);
+      throw new SessionFailure(t);
+    }
   }
 
-  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+  protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
     if (MirGlobal.abuse().getOpenPostingPassword()) {
       String password = (String) aSession.getAttribute("password");
       if (password==null) {
         password = generateOnetimePassword();
         aSession.setAttribute("password", password);
       }
-      aResponse.setResponseValue("password", password);
     }
     else {
-      aResponse.setResponseValue("password", null);
       aSession.deleteAttribute("password");
     }
 
-    aResponse.setResponseValue("errors", null);
-  };
-
-  protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure{
-    Iterator i = DatabaseComment.getInstance().getFields().iterator();
-    while (i.hasNext()) {
-      aResponse.setResponseValue( (String) i.next(), null);
-    }
-
-    String articleId = aRequest.getParameter("to_media");
+    logger.debug("referrer = " + aRequest.getHeader("Referer"));
 
-    if (articleId == null)
-      throw new SessionExc("MirBasicPostingSessionHandler.initialRequest: article id not set!");
-
-    aSession.setAttribute("to_media", articleId);
-
-    initializeResponseData(aRequest, aSession, aResponse);
-
-    try {
-      aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
-    }
-    catch (Throwable e) {
-      throw new SessionFailure("Can't get configuration: " + e.getMessage(), e);
-    }
-
-  }
-
-  protected boolean testFieldEntered(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
-    Object value = aRequest.getParameter(aFieldName);
-    if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {
-      logger.debug("  missing field " + aFieldName + " value = " + value);
-      aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
-      return false;
-    }
-    else
-      return true;
-  }
-
-  protected boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
-    Object value = aRequest.getParameter(aFieldName);
-    if (value!=null) {
-      try {
-        Integer.parseInt((String) value);
-        return true;
-      }
-      catch (Throwable t) {
-        logger.debug("  field not numeric: " + aFieldName + " value = " + value);
-        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
-        return false;
-      }
-    }
-    return true;
+    aSession.setAttribute("referer", aRequest.getHeader("Referer"));
+    aSession.setAttribute("nrmediaitems",
+        new Integer(configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems")));
   }
 
-  public void validate(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
-
-  }
-
-  public List validate(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
-    List result = new Vector();
-
-    testFieldEntered(aRequest, "title", "validationerror.missing", result);
-    testFieldEntered(aRequest, "description", "validationerror.missing", result);
-    testFieldEntered(aRequest, "creator", "validationerror.missing", result);
-
-    return result;
-  }
-
-  public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
-    try {
-      Map commentFields = new HashMap();
-
-      Iterator i = DatabaseContent.getInstance().getFields().iterator();
-      while (i.hasNext()) {
-        String field = (String) i.next();
-        aResponse.setResponseValue(field, aRequest.getParameter(field));
-        if (aRequest.getParameter(field)!=null) {
-          commentFields.put(field, aRequest.getParameter(field));
-        }
-      }
-
-      initializeResponseData(aRequest, aSession, aResponse);
-
-      List validationErrors = validate(aRequest, aSession);
-
-      if (validationErrors != null && validationErrors.size()>0) {
-        returnValidationErrors(aRequest, aSession, aResponse, validationErrors);
-      }
-      else {
-//        finish(aRequest, aSession, aResponse);
-
-        EntityComment comment = (EntityComment) commentModule.createNew ();
-//        comment.setValues(getIntersectingValues(aRequest, ));
-
-        finishComment(aRequest, aSession, comment);
-
-        String id = comment.insert();
-        if(id==null){
-          afterDuplicateCommentPosting(aRequest, aSession, aResponse, comment);
-          logger.info("Dupe comment rejected");
-          aSession.terminate();
-        }
-        else {
-          i = aRequest.getUploadedFiles().iterator();
-          while (i.hasNext()) {
-            UploadedFile file = (UploadedFile) i.next();
-            processMediaFile(aRequest, aSession, comment, file);
-          }
+  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+    int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
+    List mediaItems = new Vector();
+    int i=0;
 
-          afterCommentPosting(aRequest, aSession, aResponse, comment);
-          MirGlobal.abuse().checkComment(comment, aRequest, null);
-          MirGlobal.localizer().openPostings().afterCommentPosting(comment);
-          logger.info("Comment posted");
-          aSession.terminate();
-        }
-      }
+    while (i<nrMediaItems) {
+      i++;
+      mediaItems.add(new Integer(i));
     }
-    catch (Throwable t) {
-      ExceptionFunctions.traceCauseException(t).printStackTrace();
 
-      throw new SessionFailure("MirBasicPostingSessionHandler.subsequentRequest: " + t.getMessage(), t);
-    }
+    aResponse.setResponseValue("nrmediaitems", new Integer(nrMediaItems));
+    aResponse.setResponseValue("mediaitems", mediaItems);
+    aResponse.setResponseValue("password", aSession.getAttribute("password"));
+    aResponse.setResponseValue("referer", aSession.getAttribute("referer"));
+    aResponse.setResponseValue("errors", null);
   }
 
-  public void initializeCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionFailure, SessionExc {
-    String articleId = aRequest.getParameter("to_media");
-    if (articleId==null)
-      articleId = aRequest.getParameter("aid");
+  protected abstract void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure;
+  protected abstract void makeResponse(Request aRequest, Session aSession, Response aResponse, List anErrors) throws SessionExc, SessionFailure;
+  protected abstract void makeFinalResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure;
 
-    if (articleId==null)
-      throw new SessionExc("initializeCommentPosting: article id not set!");
-
-    aSession.setAttribute("to_media", articleId);
-    processCommentPosting(aRequest, aSession, aResponse);
+  protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
   };
-
-  public void returnValidationErrors(Request aRequest, Session aSession, Response aResponse, List aValidationErrors) throws SessionFailure, SessionExc {
-    aResponse.setResponseValue("errors", aValidationErrors);
-    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
+  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
   };
-
-  public void processCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
-    if (MirGlobal.abuse().getOpenPostingPassword()) {
-      String password = generateOnetimePassword();
-      aSession.setAttribute("password", password);
-      aResponse.setResponseValue("password", password);
-      aResponse.setResponseValue("passwd", password);
-    }
-    else {
-      aResponse.setResponseValue("password", null);
-    }
-
-    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
+  protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
   };
 
-  public void processMediaFile(Request aRequest, Session aSession, EntityComment aComment, UploadedFile aFile) throws SessionExc, SessionFailure {
+  protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {
+    int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
     try {
-      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, new HashMap());
-      finishMedia(aRequest, aSession, aFile, mediaItem);
-      mediaItem.update();
-      commentToMedia.addMedia(aComment.getId(), mediaItem.getId());
+      nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));
     }
     catch (Throwable t) {
-      throw new SessionFailure(t);
     }
-  }
-
-  public void finishMedia(Request aRequest, Session aSession, UploadedFile aFile, Entity aMedia) throws SessionExc, SessionFailure {
-  }
 
-  public void finishComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure {
-    if (aSession.getAttribute("to_media") == null)
-      throw new SessionExc("missing to_media");
+    aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));
 
-    aComment.setValueForProperty("is_published", "1");
-    aComment.setValueForProperty("to_comment_status", "1");
-    aComment.setValueForProperty("is_html","0");
-    aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media"));
-  };
+    if (aRequest.getParameter("post")==null)
+      return false;
+    else {
+      validate(aValidationErrors, aRequest, aSession);
+      return (aValidationErrors == null || aValidationErrors.size() == 0);
+    }
+  }
 
-  public void addMedia(Request aRequest, Session aSession, EntityComment aComment)  throws SessionExc, SessionFailure {
+  protected void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
   }
 
-  public void afterCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {
-    DatabaseContent.getInstance().setUnproduced("id=" + aComment.getValue("to_media"));
-    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DoneTemplate"));
+  protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.ErrorTemplate"));
   };
 
-  public void afterDuplicateCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {
-    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DupeTemplate"));
-  };
+  /**
+   * Class that represents a validation error
+   *
+   * <p>Title: </p>
+   * <p>Description: </p>
+   * <p>Copyright: Copyright (c) 2003</p>
+   * <p>Company: </p>
+   * @author not attributable
+   * @version 1.0
+   */
 
   public class ValidationError {
     private String field;
@@ -365,6 +249,94 @@ public class MirBasicPostingSessionHandler implements SessionHandler {
     }
   }
 
+  /**
+   * Convenience validation method to test wether a field has been filled in
+   *
+   * @param aRequest
+   * @param aFieldName
+   * @param anErrorMessageResource
+   * @param aValidationResults
+   * @return
+   */
+
+  protected boolean testFieldEntered(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
+    Object value = aRequest.getParameter(aFieldName);
+    if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {
+      aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
+      return false;
+    }
+    else
+      return true;
+  }
+
+  /**
+   * Convenience validation method to test wether a field is numeric
 
+   * @param aRequest
+   * @param aFieldName
+   * @param anErrorMessageResource
+   * @param aValidationResults
+   * @return
+   */
+
+  protected boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
+    Object value = aRequest.getParameter(aFieldName);
+    if (value!=null) {
+      try {
+        Integer.parseInt((String) value);
+        return true;
+      }
+      catch (Throwable t) {
+        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Method to generate a one-time password
+   *
+   * @return a password, to be used once
+   */
+  protected String generateOnetimePassword() {
+    Random r = new Random();
+    int random = r.nextInt();
+
+    long l = System.currentTimeMillis();
+
+    l = (l*l*l*l)/random;
+    if (l<0)
+      l = l * -1;
+
+    String returnString = ""+l;
+
+    return returnString.substring(5);
+  }
+
+
+  /**
+   *
+   * @param aRequest
+   * @param aStorage
+   * @return
+   * @throws SessionExc
+   * @throws SessionFailure
+   */
+
+  protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
+    Map result = new HashMap();
+
+    Iterator i = aStorage.getFields().iterator();
+
+    while (i.hasNext()) {
+      String fieldName = (String) i.next();
+      Object value = aRequest.getParameter(fieldName);
+      if (value != null)
+        result.put(fieldName, value);
+    }
+
+    return result;
+  }
 
 }