1 package ch.qos.logback.core.model.processor; 2 3 import ch.qos.logback.core.Context; 4 import ch.qos.logback.core.model.Model; 5 import ch.qos.logback.core.model.StatusListenerModel; 6 import ch.qos.logback.core.spi.ContextAware; 7 import ch.qos.logback.core.spi.LifeCycle; 8 import ch.qos.logback.core.status.StatusListener; 9 import ch.qos.logback.core.util.OptionHelper; 10 11 public class StatusListenerModelHandler extends ModelHandlerBase { 12 13 boolean inError = false; 14 Boolean effectivelyAdded = null; 15 StatusListener statusListener = null; 16 17 public StatusListenerModelHandler(Context context) { 18 super(context); 19 } 20 21 static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) { 22 return new StatusListenerModelHandler(context); 23 } 24 25 @Override 26 protected Class<StatusListenerModel> getSupportedModelClass() { 27 return StatusListenerModel.class; 28 } 29 30 @Override 31 public void handle(ModelInterpretationContext ic, Model model) throws ModelHandlerException { 32 33 StatusListenerModel slModel = (StatusListenerModel) model; 34 35 String className = slModel.getClassName(); 36 37 if (OptionHelper.isNullOrEmptyOrAllSpaces(className)) { 38 addError("Empty class name for StatusListener"); 39 inError = true; 40 return; 41 } else { 42 className = ic.getImport(className); 43 } 44 45 try { 46 statusListener = (StatusListener) OptionHelper.instantiateByClassName(className, StatusListener.class, 47 context); 48 effectivelyAdded = ic.getContext().getStatusManager().add(statusListener); 49 if (statusListener instanceof ContextAware) { 50 ((ContextAware) statusListener).setContext(context); 51 } 52 addInfo("Added status listener of type [" + slModel.getClassName() + "]"); 53 ic.pushObject(statusListener); 54 } catch (Exception e) { 55 inError = true; 56 addError("Could not create an StatusListener of type [" + slModel.getClassName() + "].", e); 57 throw new ModelHandlerException(e); 58 } 59 } 60 61 @Override 62 public void postHandle(ModelInterpretationContext mic, Model m) { 63 if (inError) { 64 return; 65 } 66 67 if (isEffectivelyAdded() && statusListener instanceof LifeCycle) { 68 ((LifeCycle) statusListener).start(); 69 } 70 Object o = mic.peekObject(); 71 if (o != statusListener) { 72 addWarn("The object at the of the stack is not the statusListener pushed earlier."); 73 } else { 74 mic.popObject(); 75 } 76 } 77 78 private boolean isEffectivelyAdded() { 79 if (effectivelyAdded == null) 80 return false; 81 return effectivelyAdded; 82 } 83 }