package commons.command; import basics.unexpected.Failure; import basics.unexpected.Problem; import basics.utl.Empty; import basics.utl.OsUtl; import commons.application.GLOBAL; import commons.engine.AdjustingLoopController; import commons.engine.Command; /** * This service allows for registering and using an adjustment function for a value in the context. * The function is registered for a key (pointing to a caontext value). For registering two keys are * needed. During registration the function class has to be reset. For adjusting a value call adjust * . Since the adjustment function is stateful it knows about it's calls. * @author ks */ public class metaadjust extends Command { private static final String MUSTHAVE = ""; private static final String ARGS = "name:;adj-fun:;adj-reset:;default:"; public void process () throws Problem { String functionName = ctx.env().consume(GLOBAL.CTX_ENVKEY_ARGS, ""); String functionImpl = ctx.consume("impl", ""); boolean reset = ctx.getr("reset", false); // register key and function? if (!Empty.is(functionImpl)) { AdjustingLoopController function = getInstance(functionImpl); ctx.put(functionName, function); OsUtl.trace(functionName + " points to adjusting loop controller " + functionImpl); } // reset? else if (!Empty.is(functionName)) { AdjustingLoopController function = (AdjustingLoopController) ctx.getr(functionName, (AdjustingLoopController) null); if (function == null) { OsUtl.trace("No such Adjusting Controller (" + functionName + ")!"); throw new Problem("No such Adjusting Controller (" + functionName + ")!"); } if (reset) function.reset(); ctx = function.adjust(ctx); } } @SuppressWarnings("unchecked") private AdjustingLoopController getInstance (String className) throws Problem { Class c = null; try { c = Class.forName(className); } catch (Exception e) { throw new Problem(description() + "Can't find class: " + className, e); } if (c == null) throw new Problem(description() + "Can't bind class: " + className); Object object = null; try { object = c.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); throw new Failure(e); } catch (IllegalAccessException e) { e.printStackTrace(); throw new Failure(e); } return (AdjustingLoopController) object; } // ---service---- public void signContract () { demand(MUSTHAVE, null); } public String description () { return implName() + " controls the value adjustment module. " + ARGS; } }