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.query;
19  
20  import java.text.MessageFormat;
21  import java.util.concurrent.atomic.AtomicBoolean;
22  import org.apache.log4j.Logger;
23  import org.osgi.framework.BundleActivator;
24  import org.osgi.framework.BundleContext;
25  import at.ac.tuwien.infosys.sm4all.copal.api.event.ContextEvent;
26  import at.ac.tuwien.infosys.sm4all.copal.api.event.ContextEventType;
27  import at.ac.tuwien.infosys.sm4all.copal.api.listener.ContextListener;
28  import at.ac.tuwien.infosys.sm4all.copal.api.util.BaseObservable;
29  
30  /**
31   * This class is used by the {@link ContextListener}s to tell on which
32   * {@link ContextEvent}s the listeners are interested in. Two properties are
33   * used to select {@link ContextEvent}s:
34   * <ul>
35   * <li>
36   * <code>eventName</code> - the name of the event (see
37   * {@link ContextEventType#getName()})</li>
38   * <li><code>criteria</code> - the logical expression using event's properties
39   * to further separate events of interest</li>
40   * </ul>
41   * 
42   * @author fei
43   * @author sanjin
44   */
45  public abstract class ContextQuery extends
46          BaseObservable<QueryState, ContextQuery, QueryObserver> implements
47          BundleActivator {
48  
49      private static final Logger LOGGER = Logger.getLogger(ContextQuery.class);
50  
51      private final String name;
52      private final String listenedType;
53      private final String criteria;
54      private final AtomicBoolean destroyed = new AtomicBoolean(false);
55  
56      /**
57       * Creates an instance of query. The <code>name</code> should be globally
58       * unique, meaning that if two {@link ContextQuery}s have same
59       * <code>name</code> then their <code>listenedType</code>s and
60       * <code>criteria</code>s are equal. The <code>listenedType</code> is name
61       * of {@link ContextEventType} on which <code>criteria</code> is executed.
62       * The <code>criteria</code> is the logical statement which further
63       * separates the events of interest. If {@link ContextQuery} should catch
64       * all <code>listenedType</code> events, we set <code>criteria</code> to be
65       * <code>null</code> or blank string or use
66       * {@link ContextQuery#ContextQuery(String, String) ContextQuery(String,
67       * String)} constructor.
68       * 
69       * @param name the globally unique name of the {@link ContextQuery}.
70       * @param listenedType the name of listened {@link ContextEventType}.
71       * @param criteria the logical expression of the {@link ContextQuery}.
72       * @throws NullPointerException if specified name or listened type is
73       *         <code>null</code>.
74       * @throws IllegalArgumentException if specified name or listened type is an
75       *         empty or blank string.
76       */
77      protected ContextQuery(final String name, final String listenedType,
78              final String criteria) {
79          super();
80  
81          if (null == name) {
82              throw new NullPointerException("Name cannot be null.");
83          }
84          if (name.trim().isEmpty()) {
85              throw new IllegalArgumentException(
86                      "Name cannot be an empty or blank string.");
87          }
88          if (null == listenedType) {
89              throw new NullPointerException("Listened type cannot be null.");
90          }
91          if (listenedType.trim().isEmpty()) {
92              throw new IllegalArgumentException(
93                      "Listened type cannot be an empty or blank string.");
94          }
95  
96          this.name = name;
97          this.listenedType = listenedType;
98          if ((null == criteria) || (criteria.trim().isEmpty())) {
99              this.criteria = null;
100         } else {
101             this.criteria = criteria;
102         }
103 
104         if (LOGGER.isDebugEnabled()) {
105             LOGGER.debug(MessageFormat.format("Created query ''{0}''.",
106                     this.name));
107         }
108     }
109 
110     /**
111      * Create instance of query. The <code>name</code> should be globally
112      * unique, meaning that if two {@link ContextQuery}s have same
113      * <code>name</code> then their <code>listenedType</code>s and
114      * <code>criteria</code>s are equal. The <code>listenedType</code> is name
115      * of {@link ContextEventType} to be caught.
116      * 
117      * @param name the globally unique name of the {@link ContextQuery}.
118      * @param listenedType the name of listened {@link ContextEventType}.
119      * @throws NullPointerException if specified name or listened type is
120      *         <code>null</code>.
121      * @throws IllegalArgumentException if specified name or listened type is an
122      *         empty or blank string.
123      */
124     protected ContextQuery(final String name, final String listenedType) {
125         this(name, listenedType, null);
126     }
127 
128     /**
129      * Returns the globally unique name of this {@link ContextQuery}.
130      * 
131      * @return the globally unique name of this {@link ContextQuery}.
132      */
133     public String getName() {
134         return this.name;
135     }
136 
137     /**
138      * Returns the name of listened {@link ContextEventType}.
139      * 
140      * @return the name of listened {@link ContextEventType}.
141      * @see ContextEventType#getName()
142      */
143     public String getListenedType() {
144         return this.listenedType;
145     }
146 
147     /**
148      * Returns the logical expression this {@link ContextQuery}.
149      * 
150      * @return the logical expression this {@link ContextQuery}.
151      */
152     public String getCriteria() {
153         return this.criteria;
154     }
155 
156     /**
157      * Returns if this {@link ContextQuery} has the criteria defined.
158      * 
159      * @return if this {@link ContextQuery} has the criteria defined.
160      */
161     public boolean hasCriteria() {
162         return null != this.criteria;
163     }
164 
165     /**
166      * Returns if this {@link ContextQuery} is destroyed.
167      * 
168      * @return if this {@link ContextQuery} is destroyed.
169      */
170     public boolean isDestroyed() {
171         return this.destroyed.get();
172     }
173 
174     @Override
175     public abstract void start(BundleContext bundleContext);
176 
177     @Override
178     public abstract void stop(BundleContext bundleContext);
179 
180     /**
181      * Destroys this {@link ContextQuery}. All registered
182      * {@link ContextListener}s will be unregistered and any future registration
183      * of a {@link ContextListener} and receiving of events will not be
184      * possible.
185      * 
186      * @throws QueryDestroyedException if {@link ContextQuery} has been already
187      *         destroyed.
188      */
189     public void destroy() throws QueryDestroyedException {
190         if (this.destroyed.getAndSet(true)) {
191             throw new QueryDestroyedException(this);
192         }
193 
194         if (LOGGER.isDebugEnabled()) {
195             LOGGER.debug(MessageFormat.format("Destroying ''{0}'' query.",
196                     this.name));
197         }
198 
199         notifyAll(QueryState.Destroyed, this);
200         detachAll();
201 
202         if (LOGGER.isInfoEnabled()) {
203             LOGGER.info(MessageFormat.format("''{0}'' query destroyed!",
204                     this.name));
205         }
206     }
207 
208     /**
209      * This method is called when a {@link ContextEvent} with same event name
210      * occurs for which the criteria is satisfied. This method in return calls
211      * all registered {@link ContextListener}s with specified
212      * {@link ContextEvent}.
213      * 
214      * @param event the occurred {@link ContextEvent}.
215      * @throws QueryDestroyedException if {@link ContextQuery} has been
216      *         previously destroyed.
217      */
218     public abstract void onEvent(final ContextEvent event)
219             throws QueryDestroyedException;
220 
221     /**
222      * Attach specified {@link QueryObserver} so it will in future receive
223      * {@link QueryState} change notifications of this {@link ContextQuery}.
224      * 
225      * @param observer the {@link QueryObserver}.
226      */
227     @Override
228     public void attach(final QueryObserver observer) {
229         if (!this.destroyed.get()) {
230             super.attach(observer);
231             observer.update(QueryState.Created, this);
232         }
233     }
234 
235     /**
236      * Returns hash code for this {@link ContextQuery}. The hash code for a
237      * {@link ContextQuery} object is computed as:
238      * 
239      * <pre>
240      * name * 31 + listened type
241      * </pre>
242      * 
243      * using integer arithmetic.
244      * 
245      * @return a hash code value for this {@link ContextQuery}.
246      */
247     @Override
248     public int hashCode() {
249         return (this.name.hashCode() * 31) + this.listenedType.hashCode();
250     }
251 
252     /**
253      * Compares this {@link ContextQuery} to the specified {@link Object}. The
254      * result is <code>true</code> if and only if the argument is not
255      * <code>null</code> and is a {@link ContextQuery} object that has same
256      * name, listened type and criteria as this {@link ContextQuery}.
257      * 
258      * @param obj the {@link Object} to compare this {@link ContextQuery}
259      *        against.
260      * @return <code>true</code> if {@link ContextQuery}s are equal;
261      *         <code>false</code> otherwise.
262      */
263     @Override
264     public boolean equals(final Object obj) {
265         boolean result = false;
266 
267         if (null != obj) {
268             if (this == obj) {
269                 result = true;
270             } else if (obj instanceof ContextQuery) {
271                 final ContextQuery other = (ContextQuery) obj;
272 
273                 result = this.name.equals(other.name)
274                         && this.listenedType.equals(other.listenedType);
275                 result = result
276                         && ((hasCriteria() && this.criteria.equals(other.criteria)) || (!hasCriteria() && !other.hasCriteria()));
277             }
278         }
279 
280         return result;
281     }
282 }