View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.net;
15  
16  import ch.qos.logback.core.spi.ContextAwareBase;
17  import ch.qos.logback.core.spi.LifeCycle;
18  
19  /**
20   * An abstract base for components that receive logging events from a remote
21   * peer and log according to local policy
22   *
23   * @author Carl Harris
24   */
25  public abstract class ReceiverBase extends ContextAwareBase implements LifeCycle {
26  
27      private boolean started;
28  
29      /**
30       * {@inheritDoc}
31       */
32      public final void start() {
33          if (isStarted())
34              return;
35          if (getContext() == null) {
36              throw new IllegalStateException("context not set");
37          }
38          if (shouldStart()) {
39              getContext().getScheduledExecutorService().execute(getRunnableTask());
40              started = true;
41          }
42      }
43  
44      /**
45       * {@inheritDoc}
46       */
47      public final void stop() {
48          if (!isStarted())
49              return;
50          try {
51              onStop();
52          } catch (RuntimeException ex) {
53              addError("on stop: " + ex, ex);
54          }
55          started = false;
56      }
57  
58      /**
59       * {@inheritDoc}
60       */
61      public final boolean isStarted() {
62          return started;
63      }
64  
65      /**
66       * Determines whether this receiver should start.
67       * <p>
68       * Subclasses will implement this method to do any subclass-specific
69       * validation.  The subclass's {@link #getRunnableTask()} method will be 
70       * invoked (and the task returned will be submitted to the executor)
71       * if and only if this method returns {@code true} 
72       * @return flag indicating whether this receiver should start
73       */
74      protected abstract boolean shouldStart();
75  
76      /**
77       * Allows a subclass to participate in receiver shutdown.
78       */
79      protected abstract void onStop();
80  
81      /**
82       * Provides the runnable task this receiver will execute.
83       * @return runnable task
84       */
85      protected abstract Runnable getRunnableTask();
86  
87  }