| 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

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; Optimizing Julia Code; Cash Handouts in Brazil; Couple Nice Music Videos; It Also Works!; Adaptive Plaintext; It Works!; RC5 Without Rotation (2); 8 Years...; Attack Against Encrypted Linux Disks; Pushing Back On NSA At IETF; Summary of Experimental Ethics; Very Good Talk On Security, Snowden; Locusts are Grasshoppers!; Vagrant (OpenSuse and IDEs); Interesting Take On Mandela's Context; Haskell Cabal O(n^2) / O(n) Fix; How I Am 4; Chilean Charity Supporting Women; Doing SSH right; Festival of Urban Intervention; Neat Idea - Wormholes Provide Entanglement; And a Link....; Simple Encryption for Python 2.7; OpenSuse 13.1 Is Better!; Little Gain...; More Details on Technofull Damage; Palmrest Cracked Too....; Tecnofull (Lenovo Support) Is Fucking Useless; The Neuroscientist Who Discovered He Was a Psychopath; Interpolating Polynomials; Bottlehead Crack as Pre-amp; Ooops K702!; Bottlehead Crack, AKG K701; Breaking RC5 Without Rotation; Great post thank you; Big Balls of Mud; Phabricator - Tools for working together; Amazing Julia RC5 Code Parameterized By Word Size; Chi-Square Can Be Two-Sided; Why Do Brits Accept Surveillance?; Statistics Done Wrong; Mesas Trape from Bravo; European Report on Crypto Primitives and Protocols; Interesting Omissions; Oryx And Crake (Margaret Atwood); Music and Theory; My Arduino Programs; Elliptic Curve Crypto; Re: Licensing Interpreted Code; Licensing Interpreted Code; ASUS 1015E-DS03 OpenSuse 12.3 SSD; translating lettuce feature files into stub steps files; Re: translating lettuce feature files into stub steps files; A Tale of Two Psychiatrists; The Real Reason the Poor Go Without Bank Accounts; The Rational Choices of Crack Addicts

© 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