| 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.

C-ORM: docs, API.

Last 100 entries

Calling C From Fortran 95; Bjork DJ Set; Z3 Example With Python; Week 1; Useful Guide To Starting With IJulia; UK Election + Media; Review: Reinventing Organizations; Inline Assembly With Julia / LLVM; Against the definition of types; Dumb Crypto Paper; The Search For Quasi-Periodicity...; Is There An Alternative To Processing?; CARDIAC (CARDboard Illustrative Aid to Computation); The Bolivian Case Against Chile At The Hague; Clear, Cogent Economic Arguments For Immigration; A Program To Say If I Am Working; Decent Cards For Ill People; New Photo; Luksic And Barrick Gold; President Bachelet's Speech; Baltimore Primer; libxml2 Parsing Stream; configure.ac Recipe For Library Path; The Davalos Affair For Idiots; Not The Onion: Google Fireside Chat w Kissinger; Bicycle Wheels, Inertia, and Energy; Another Tax Fraud; Google's Borg; A Verion That Redirects To Local HTTP Server; Spanish Accents For Idiots; Aluminium Cans; Advice on Spray Painting; Female View of Online Chat From a Male; UX Reading List; S4 Subgroups - Geometric Interpretation; Fucking Email; The SQM Affair For Idiots; Using Kolmogorov Complexity; Oblique Strategies in bash; Curses Tools; Markov Chain Monte Carlo Without all the Bullshit; Email Para Matias Godoy Mercado; The Penta Affair For Idiots; Example Code To Create numpy Array in C; Good Article on Bias in Graphic Design (NYTimes); Do You Backup github?; Data Mining Books; SimpleDateFormat should be synchronized; British Words; Chinese Govt Intercepts External Web To DDOS github; Numbering Permutations; Teenage Engineering - Low Price Synths; GCHQ Can Do Whatever It Wants; Dublinesque; A Cryptographic SAT Solver; Security Challenges; Word Lists for Crosswords; 3D Printing and Speaker Design; Searchable Snowden Archive; XCode Backdoored; Derived Apps Have Malware (CIA); Rowhammer - Hacking Software Via Hardware (DRAM) Bugs; Immutable SQL Database (Kinda); Tor GPS Tracker; That PyCon Dongle Mess...; ASCII Fluid Dynamics; Brandalism; Table of Shifter, Cassette and Derailleur Compatability; Lenovo Demonstrates How Bad HTTPS Is; Telegraph Owned by HSBC; Smaptop - Sunrise (Music); Equation Group (NSA); UK Torture in NI; And - A Natural Extension To Regexps; This Is The Future Of Religion; The Shazam (Music Matching) Algorithm; Tributes To Lesbian Community From AIDS Survivors; Nice Rust Summary; List of Good Fiction Books; Constructing JSON From Postgres (Part 2); Constructing JSON From Postgres (Part 1); Postgres in Docker; Why Poor Places Are More Diverse; Smart Writing on Graceland; Satire in France; Free Speech in France; MTB Cornering - Where Should We Point Our Thrusters?; Secure Secure Shell; Java Generics over Primitives; 2014 (Charlie Brooker); How I am 7; Neural Nets Applied to Go; Programming, Business, Social Contracts; Distributed Systems for Fun and Profit; XML and Scheme; Internet Radio Stations (Curated List); Solid Data About Placebos; Half of Americans Think Climate Change Is a Sign of the Apocalypse; Saturday Surf Sessions With Juvenile Delinquents; Ssh, tty, stdout and stderr; Feathers falling in a vacuum; Santiago 30m Bike Route

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