| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

Last 100 entries

Hilary Mantel: The Assassination of Margaret Thatcher - August 6th 1983; NSA Interceptng Gmail During Delivery; General IIR Filters; What's happening with Scala?; Interesting (But Largely Illegible) Typeface; Retiring Essentialism; Poorest in UK, Poorest in N Europe; I Want To Be A Redneck!; Reverse Racism; The Lost Art Of Nomography; IBM Data Center (Photo); Interesting Account Of Gamma Hack; The Most Interesting Audiophile In The World; How did the first world war actually end?; Ky - Restaurant Santiago; The Black Dork Lives!; The UN Requires Unaninmous Decisions; LPIR - Steganography in Practice; How I Am 6; Clear Explanation of Verizon / Level 3 / Netflix; Teenage Girls; Formalising NSA Attacks; Switching Brakes (Tektro Hydraulic); Naim NAP 100 (Power Amp); AKG 550 First Impressions; Facebook manipulates emotions (no really); Map Reduce "No Longer Used" At Google; Removing RAID metadata; New Bike (Good Bike Shop, Santiago Chile); Removing APE Tags in Linux; Compiling Python 3.0 With GCC 4.8; Maven is Amazing; Generating Docs from a GitHub Wiki; Modular Shelves; Bash Best Practices; Good Emergency Gasfiter (Santiago, Chile); Readings in Recent Architecture; Roger Casement; Integrated Information Theory (Or Not); Possibly undefined macro AC_ENABLE_SHARED; Update on Charges; Sunburst Visualisation; Spectral Embeddings (Distances -> Coordinates); Introduction to Causality; Filtering To Help Colour-Blindness; ASUS 1015E-DS02 Too; Ready Player One; Writing Clear, Fast Julia Code; List of LatAm Novels; Running (for women); Building a Jenkins Plugin and a Jar (for Command Line use); Headphone Test Recordings; Causal Consistency; The Quest for Randomness; Chat Wars; Real-life Financial Co Without ACID Database...; Flexible Muscle-Based Locomotion for Bipedal Creatures; SQL Performance Explained; The Little Manual of API Design; Multiple Word Sizes; CRC - Next Steps; FizzBuzz; Update on CRCs; Decent Links / Discussion Community; Automated Reasoning About LLVM Optimizations and Undefined Behavior; A Painless Guide To CRC Error Detection Algorithms; Tests in Julia; Dave Eggers: what's so funny about peace, love and Starship?; Cello - High Level C Programming; autoreconf needs tar; Will Self Goes To Heathrow; Top 5 BioInformatics Papers; Vasovagal Response; Good Food in Vina; Chilean Drug Criminals Use Subsitution Cipher; Adrenaline; Stiglitz on the Impact of Technology; Why Not; How I Am 5; Lenovo X240 OpenSuse 13.1; NSA and GCHQ - Psychological Trolls; Finite Fields in Julia (Defining Your Own Number Type); Julian Assange; Starting Qemu on OpenSuse; Noisy GAs/TMs; Venezuela; Reinstalling GRUB with EFI; Instructions For Disabling KDE Indexing; Evolving Speakers; Changing Salt Size in Simple Crypt 3.0.0; Logarithmic Map (Moved); More Info; Words Found in Voynich Manuscript; An Inventory Of 3D Space-Filling Curves; Foxes Using Magnetic Fields To Hunt; 5 Rounds RC5 No Rotation; JP Morgan and Madoff; Ori - Secure, Distributed File System; Physical Unclonable Functions (PUFs); Prejudice on Reddit; Recursion OK

© 2006-2013 Andrew Cooke (site) / post authors (content).

Example Controller Code

From: "andrew cooke" <andrew@...>

Date: Wed, 26 Jul 2006 16:26:05 -0400 (CLT)

Some example code from the (private/personal) project I'm working on. 
This is a controller for a complex multi-page form, with forwards/back
buttons (and various other paths), different levels of access depending on
users, etc.

Maybe it looks terribly complex, but I'm having a hard job imagining
anything significantly simpler.  The first section (after various
getter/setters) defines the initial state of the view for various model
states.  The rest is the basic controller logic.  Note how the controller
logic is distributed across various handler (inner) classes according to
the model state.  Which method is called in the control is dynamically
chosen via the user action.

public class BaseController extends ViewedBeanController {

 public static final String EXCHANGE_PATTERNS =
  "org_acooke_collaborate_exchangePatterns";

 private static final String SAVE = "save";
 private static final String FWD = "fwd";
 enum Modes {EDIT, VIEW, ERROR, CLOSE, CONFIRM};
 private ExchangeDao exchangeDao;
 private String settingsView = "exchange/settings";
 private String participantsView = "exchange/participants";
 private String signupView = "exchange/signup";
 private String groupsView = "exchange/groups";
 private String waitingView = "exchange/waiting";
 private String activeView = "exchange/active";
 private String completeView = "exchange/complete";
 private String closedView = "exchange/closed";

 public void setExchangeDao(ExchangeDao exchangeDao) {
  this.exchangeDao = exchangeDao;
 }
 public ExchangeDao getExchangeDao() {return exchangeDao;}

 public void setSettingsView(String settingsView) {
  this.settingsView = settingsView;
 }
 public String getSettingsView() {return settingsView;}

 public void setParticipantsView(String participantsView) {
  this.participantsView = participantsView;
 }
 public String getParticipantsView() {return participantsView;}

 public void setSignupView(String signupView) {this.signupView =
signupView;}
 public String getSignupView() {return signupView;}

 public void setGroupsView(String groupsView) {this.groupsView =
groupsView;}
 public String getGroupsView() {return groupsView;}

 public void setWaitingView(String waitingView) {
  this.waitingView = waitingView;
 }
 public String getWaitingView() {return waitingView;}

 public void setActiveView(String activeView) {this.activeView =
activeView;}
 public String getActiveView() {return activeView;}

 public void setCompleteView(String completeView) {
  this.completeView = completeView;
 }
 public String getCompleteView() {return completeView;}

 public void setClosedView(String closedView) {
  this.closedView = closedView;
 }
 public String getClosedView() {return closedView;}

 @Override
 protected FormDisplayable newFormBean(HttpServletRequest req)
 throws BadArgumentException {
  ExchangeInfo info =
   SessionUtils.getExchangeFromUrl(getExchangeDao(), getViewer(), req);
  info._setMembers(Modes.class);
  info._setMode(modeFromState(info.getExchangeState()));
  if (DateLogic.filter(info)) {
   getExchangeDao().saveParticipants(getViewer(), info);
  }
  return info;
 }

 private Modes modeFromState(ExchangeState state) {
  switch(state) {
  case SETTINGS:        return Modes.EDIT;
  case SETTINGS_OK:     return Modes.VIEW;
  case PARTICIPANTS:    return Modes.EDIT;
  case PARTICIPANTS_OK: return Modes.VIEW;
  case SIGNUPS:         return Modes.VIEW;
  case GROUPS:          return Modes.EDIT;
  case GROUPS_OK:       return Modes.VIEW;
  case WAITING:         return Modes.VIEW;
  case ACTIVE:          return Modes.VIEW;
  case COMPLETE:        return Modes.VIEW;
  case CLOSED:          return Modes.VIEW;
  default:              return Modes.ERROR;
  }
 }

 @Override
 public String getView(FormDisplayable formBean) {
  ExchangeInfo info = (ExchangeInfo)formBean;
  switch(info.getExchangeState()) {
  case SETTINGS:
  case SETTINGS_OK:     return getSettingsView();
  case PARTICIPANTS:
  case PARTICIPANTS_OK: return getParticipantsView();
  case SIGNUPS:         return getSignupView();
  case GROUPS:
  case GROUPS_OK:       return getGroupsView();
  case WAITING:         return getWaitingView();
  case ACTIVE:          return getActiveView();
  case COMPLETE:        return getCompleteView();
  case CLOSED:          return getClosedView();
  default:              return getErrorView();
  }
 }

 @Override
 protected BaseActionBean newActionBean(FormDisplayable formBean,
   HttpServletRequest req) {
  ExchangeInfo info = (ExchangeInfo)formBean;
  switch(info.getExchangeState()) {
  case SETTINGS:
  case SETTINGS_OK:     return new SettingsActionBean(req);
  case PARTICIPANTS:
  case PARTICIPANTS_OK: return new ParticipantsActionBean(req);
  case SIGNUPS:         return new SignupActionBean(req);
  case GROUPS:
  case GROUPS_OK:       return new GroupsActionBean(req);
  case WAITING:         return new WaitingActionBean(req);
  case ACTIVE:          return new SummaryActionBean(req);
  case COMPLETE:        return new SummaryActionBean(req);
  case CLOSED:          return new ClosedActionBean(req);
  default:              return new ErrorBean(req);
  }
 }

 @Override
 protected void initBinder(HttpServletRequest req,
   ServletRequestDataBinder binder) {
  binder.registerCustomEditor(
    ExchangePattern.class, "exchangePattern",
    new ExchangePatternPropertyEditor());
 }

 @Override
 protected Map buildModel(HttpServletRequest req, FormDisplayable
formBean) {
  addExtra(EXCHANGE_PATTERNS, ExchangePattern.values());
  return super.buildModel(req, formBean);
 }

 @Override
 protected ServletRequestDataBinder bindAndValidateInternal(
   HttpServletRequest request, Object formBean) throws Exception {
  ExchangeInfo info = (ExchangeInfo)formBean;
  boolean validn = additionalValidation(info, request);
  logger.debug("additional validation: " + validn);
  info._setValidateFlag(validn);
  return super.bindAndValidate(request, formBean);
 }

 /*
  * Additional validation required in certain special cases
  */
 private boolean additionalValidation(ExchangeInfo info,
   HttpServletRequest req) {
  String action = SessionUtils.getAction(req);
  switch(info.getExchangeState()) {
  case PARTICIPANTS:
  case SETTINGS:
  case GROUPS:
   return info.isMode(Modes.EDIT) && action.equalsIgnoreCase(SAVE);
  case SIGNUPS:
   return action.equalsIgnoreCase(FWD);
  default:
   return false;
  }
 }

 public class SaveBean extends BaseActionBean {

  public SaveBean(HttpServletRequest req) {super(req);}

  protected void saveExchange(ExchangeInfo info) throws Exception {
   getExchangeDao().saveSettings(getViewer(), info);
   setInit(info);
  }

  protected void saveParticipants(ExchangeInfo info) throws Exception {
   getExchangeDao().saveParticipants(getViewer(), info);
   setInit(info);
  }

 }

 public class SaveCloseBean extends SaveBean {

  public SaveCloseBean(HttpServletRequest req) {super(req);}

  public void setClose(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (info.getExchange().isMutable()) {
    if (formBean.isMode(Modes.VIEW)) {
     formBean._setMode(Modes.CLOSE);
    } else if (formBean.isMode(Modes.CLOSE)) {
     DateLogic.close(info, ExchangeState.CLOSED);
     saveParticipants(info);
    }
   }
  }

 }

 public class SaveEditBean extends SaveCloseBean {

  public SaveEditBean(HttpServletRequest req) {super(req);}

  public void setEdit(FormDisplayable formBean) {
   setEdit(formBean, ((ExchangeInfo)formBean).getExchangeState());
  }

  public void setEdit(FormDisplayable formBean, ExchangeState state) {
   if (formBean.isMode(Modes.VIEW)
     && ((ExchangeInfo)formBean).getExchange().isMutable()) {
    formBean._setMode(Modes.EDIT);
    ((ExchangeInfo)formBean)._setExchangeState(state);
   }
  }

 }

 public class SettingsActionBean extends SaveEditBean {

  public SettingsActionBean(HttpServletRequest req) {super(req);}

  @Override
  public void setEdit(FormDisplayable formBean) {
   setEdit(formBean, ExchangeState.SETTINGS);
  }

  public void setSave(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    info._setExchangeState(ExchangeState.SETTINGS_OK);
    saveExchange(info);
   }
  }

  public void setFwd(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    info._setExchangeState(ExchangeState.PARTICIPANTS);
    saveExchange(info);
   }
  }

 }

 public class ParticipantsActionBean extends SaveEditBean {

  public ParticipantsActionBean(HttpServletRequest req) {super(req);}

  @Override
  public void setEdit(FormDisplayable formBean) {
   setEdit(formBean, ExchangeState.PARTICIPANTS);
  }

  public void setSave(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    info._setExchangeState(ExchangeState.PARTICIPANTS_OK);
    saveExchange(info);
   }
  }

  public void setReplace(FormDisplayable formBean) {
   if (formBean.isMode(Modes.EDIT)) {
    ExchangeInfo info = (ExchangeInfo)formBean;
    ParticipantLogic.filter(info);
   }
  }

  public void setAllOut(FormDisplayable formBean) {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    ParticipantLogic.allOut(info);
   }
  }

  public void setAllIn(FormDisplayable formBean) {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    ParticipantLogic.allIn(info);
   }
  }

  public void setAllFilter(FormDisplayable formBean) {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    ParticipantLogic.allFilter(info);
   }
  }

  public void setFwd(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    info._setExchangeState(ExchangeState.SIGNUPS);
    saveExchange(info);
   }
  }

  public void setBack(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    info._setExchangeState(ExchangeState.SETTINGS);
    saveExchange(info);
   }
  }

 }

 public class SignupActionBean extends SaveCloseBean {

  public SignupActionBean(HttpServletRequest req) {super(req);}

  public void setEdit(FormDisplayable formBean) throws Exception {
   setInit(formBean);
  }

  public void setSignup(FormDisplayable formBean) throws Exception {
   getParticipant(formBean).setSignup(new CalendarDate());
   getExchangeDao().saveParticipants(getViewer(), (ExchangeInfo)formBean);
  }

  public void setLeave(FormDisplayable formBean) throws Exception {
   getParticipant(formBean).setSignup(null);
   getExchangeDao().saveParticipants(getViewer(), (ExchangeInfo)formBean);
  }

  private Participant getParticipant(FormDisplayable formBean) {
   Participant participant = (Participant)Bk.getProperty(formBean, path);
check(participant.isMutable(), "Participant not mutable");
   return participant;
  }

  public void setBack(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    formBean._setMode(Modes.CONFIRM);
   } else if (formBean.isMode(Modes.CONFIRM)
              && info.getExchange().isMutable()) {
    ParticipantLogic.signdownAll(info);
    info._setExchangeState(ExchangeState.PARTICIPANTS);
    saveParticipants(info);
   }
  }

  public void setFwd(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    GroupLogic.filterFwd(info);
    saveParticipants(info);
   }
  }

 }

 public class GroupsActionBean extends SaveEditBean {

  public GroupsActionBean(HttpServletRequest req) {super(req);}

  @Override
  public void setEdit(FormDisplayable formBean) {
   setEdit(formBean, ExchangeState.GROUPS);
  }

  public void setSave(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.EDIT) && info.getExchange().isMutable()) {
    GroupLogic.setOrder(info.getParticipants());
    info._setExchangeState(ExchangeState.GROUPS_OK);
    saveParticipants(info);
   }
  }

  public void setBack(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    GroupLogic.setOrder(info.getParticipants());
    info._setExchangeState(ExchangeState.SIGNUPS);
    saveExchange(info);
   }
  }

  public void setFwd(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (formBean.isMode(Modes.VIEW) && info.getExchange().isMutable()) {
    GroupLogic.setOrder(info.getParticipants());
    info._setExchangeState(ExchangeState.WAITING);
    saveExchange(info);
   }
  }

}

 public class ClosedActionBean extends SaveBean {

  public ClosedActionBean(HttpServletRequest req) {super(req);}

  @Override
  public void setEdit(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (info.getExchange().isMutable()) {
    DateLogic.close(info, ExchangeState.SETTINGS);
   }
  }

 }

 public class WaitingActionBean extends SaveCloseBean {

  public WaitingActionBean(HttpServletRequest req) {super(req);}

  public void setBack(FormDisplayable formBean) throws Exception {
   ExchangeInfo info = (ExchangeInfo)formBean;
   if (info.getExchange().isMutable()) {
    GroupLogic.filterBack(info);
    saveExchange(info);
   }
  }

 }

 public class SummaryActionBean extends BaseActionBean {
  public SummaryActionBean(HttpServletRequest req) {super(req);}
 }

 public class ErrorBean extends BaseActionBean {
  public ErrorBean(HttpServletRequest req) {super(req);}
 }

}

Comment on this post