Andrew Cooke | Contents | Latest | RSS | 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

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 2006-2017 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