View Javadoc

1   /* This file is part of COPAL (COntext Provisioning for All).
2    *
3    * COPAL is a part of SM4All (Smart hoMes for All) project.
4    *
5    * COPAL is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU Lesser General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * COPAL is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU Lesser General Public License for more details.
14   *
15   * You should have received a copy of the GNU Lesser General Public License
16   * along with COPAL. If not, see <http://www.gnu.org/licenses/>.
17   */
18  package at.ac.tuwien.infosys.sm4all.copal.api.osgi;
19  
20  import java.util.concurrent.atomic.AtomicReference;
21  import org.osgi.framework.BundleActivator;
22  
23  /**
24   * Abstract helper class to be used as a {@link BundleActivator} for bundles
25   * that require a service.
26   * 
27   * @param <T> the type of service.
28   * @author sanjin
29   */
30  public class Tracker<T> extends GenericActivator {
31  
32      private final AtomicReference<T> serviceRef = new AtomicReference<T>();
33      private final String name;
34  
35      /**
36       * Creates instance of {@link BundleActivator} for bundles that require a
37       * service with specified name.
38       * 
39       * @param name the name of service.
40       */
41      public Tracker(final String name) {
42          super(name);
43  
44          this.name = name;
45      }
46  
47      /**
48       * Called when service becomes available.
49       * 
50       * @param service the service.
51       */
52      protected void start(final T service) {
53          /* do nothing */
54      }
55  
56      /**
57       * Called when service becomes unavailable.
58       * 
59       * @param service the service.
60       */
61      protected void stop(final T service) {
62          /* do nothing */
63      }
64  
65      /**
66       * Returns the currently available service or <code>null</code> if service
67       * is unavailable.
68       * 
69       * @return the currently available service.
70       */
71      public T getService() {
72          return this.serviceRef.get();
73      }
74  
75      @SuppressWarnings("unchecked")
76      @Override
77      protected void start() {
78          final T service = (T) getDependency(this.name);
79  
80          this.serviceRef.set(service);
81          start(service);
82      }
83  
84      @Override
85      protected void stop() {
86          stop(this.serviceRef.getAndSet(null));
87      }
88  }