001/** 002 * 003 * Copyright 2003-2007 Jive Software, 2016-2024 Florian Schmaus. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.jivesoftware.smack; 019 020import java.util.ArrayDeque; 021import java.util.ArrayList; 022import java.util.List; 023 024import org.jivesoftware.smack.SmackException.NoResponseException; 025import org.jivesoftware.smack.SmackException.NotConnectedException; 026import org.jivesoftware.smack.XMPPException.XMPPErrorException; 027import org.jivesoftware.smack.filter.StanzaFilter; 028import org.jivesoftware.smack.packet.Stanza; 029 030/** 031 * Provides a mechanism to collect Stanzas into a result queue that pass a 032 * specified filter/matcher. The collector lets you perform blocking and polling 033 * operations on the result queue. So, a StanzaCollector is more suitable to 034 * use than a {@link StanzaListener} when you need to wait for a specific 035 * result.<p> 036 * 037 * Each stanza collector will queue up a configured number of packets for processing before 038 * older packets are automatically dropped. The default number is retrieved by 039 * {@link SmackConfiguration#getStanzaCollectorSize()}. 040 * 041 * @see XMPPConnection#createStanzaCollector(StanzaFilter) 042 * @author Matt Tucker 043 */ 044public final class StanzaCollector implements AutoCloseable { 045 046 private final StanzaFilter packetFilter; 047 048 private final ArrayDeque<Stanza> resultQueue; 049 050 private final int maxQueueSize; 051 052 /** 053 * The stanza collector which timeout for the next result will get reset once this collector collects a stanza. 054 */ 055 private final StanzaCollector collectorToReset; 056 057 private final XMPPConnection connection; 058 059 private final Stanza request; 060 061 private volatile boolean cancelled; 062 063 private Exception connectionException; 064 065 /** 066 * Creates a new stanza collector. If the stanza filter is <code>null</code>, then 067 * all packets will match this collector. 068 * 069 * @param connection the connection the collector is tied to. 070 * @param configuration the configuration used to construct this collector 071 */ 072 StanzaCollector(XMPPConnection connection, Configuration configuration) { 073 this.connection = connection; 074 this.packetFilter = configuration.packetFilter; 075 this.resultQueue = new ArrayDeque<>(configuration.size); 076 this.maxQueueSize = configuration.size; 077 this.collectorToReset = configuration.collectorToReset; 078 this.request = configuration.request; 079 } 080 081 /** 082 * Explicitly cancels the stanza collector so that no more results are 083 * queued up. Once a stanza collector has been cancelled, it cannot be 084 * re-enabled. Instead, a new stanza collector must be created. 085 */ 086 public synchronized void cancel() { 087 // If the packet collector has already been cancelled, do nothing. 088 if (cancelled) { 089 return; 090 } 091 092 cancelled = true; 093 connection.removeStanzaCollector(this); 094 notifyAll(); 095 096 if (collectorToReset != null) { 097 collectorToReset.cancel(); 098 } 099 } 100 101 /** 102 * Returns the stanza filter associated with this stanza collector. The stanza 103 * filter is used to determine what stanzas are queued as results. 104 * 105 * @return the stanza filter. 106 */ 107 public StanzaFilter getStanzaFilter() { 108 return packetFilter; 109 } 110 111 /** 112 * Polls to see if a stanza is currently available and returns it, or 113 * immediately returns <code>null</code> if no packets are currently in the 114 * result queue. 115 * 116 * @param <P> type of the result stanza. 117 * @return the next stanza result, or <code>null</code> if there are no more 118 * results. 119 */ 120 @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) 121 public synchronized <P extends Stanza> P pollResult() { 122 return (P) resultQueue.poll(); 123 } 124 125 /** 126 * Polls to see if a stanza is currently available and returns it, or 127 * immediately returns <code>null</code> if no packets are currently in the 128 * result queue. 129 * <p> 130 * Throws an XMPPErrorException in case the polled stanzas did contain an XMPPError. 131 * </p> 132 * 133 * @param <P> type of the result stanza. 134 * @return the next available packet. 135 * @throws XMPPErrorException in case an error response. 136 */ 137 @SuppressWarnings("TypeParameterUnusedInFormals") 138 public <P extends Stanza> P pollResultOrThrow() throws XMPPErrorException { 139 P result = pollResult(); 140 if (result != null) { 141 XMPPErrorException.ifHasErrorThenThrow(result); 142 } 143 return result; 144 } 145 146 /** 147 * Returns the next available packet. The method call will block (not return) until a stanza is 148 * available. 149 * 150 * @param <P> type of the result stanza. 151 * @return the next available packet. 152 * @throws InterruptedException if the calling thread was interrupted. 153 */ 154 @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) 155 // TODO: Consider removing this method as it is hardly ever useful. 156 public synchronized <P extends Stanza> P nextResultBlockForever() throws InterruptedException { 157 throwIfCancelled(); 158 159 while (true) { 160 P res = (P) resultQueue.poll(); 161 if (res != null) { 162 return res; 163 } 164 if (cancelled) { 165 return null; 166 } 167 wait(); 168 } 169 } 170 171 /** 172 * Returns the next available packet. The method call will block until the connection's default 173 * timeout has elapsed. 174 * 175 * @param <P> type of the result stanza. 176 * @return the next available packet. 177 * @throws InterruptedException if the calling thread was interrupted. 178 */ 179 @SuppressWarnings("TypeParameterUnusedInFormals") 180 public <P extends Stanza> P nextResult() throws InterruptedException { 181 return nextResult(connection.getReplyTimeout()); 182 } 183 184 private volatile long waitStart; 185 186 /** 187 * Returns the next available stanza. The method call will block (not return) until a stanza is available or the 188 * <code>timeout</code> has elapsed or if the connection was terminated because of an error. If the timeout elapses without a 189 * result or if there was an connection error, <code>null</code> will be returned. 190 * 191 * @param <P> type of the result stanza. 192 * @param timeout the timeout in milliseconds. 193 * @return the next available stanza or <code>null</code> on timeout or connection error. 194 * @throws InterruptedException if the calling thread was interrupted. 195 */ 196 @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) 197 public <P extends Stanza> P nextResult(long timeout) throws InterruptedException { 198 throwIfCancelled(); 199 P res = null; 200 long remainingWait = timeout; 201 waitStart = System.currentTimeMillis(); 202 while (remainingWait > 0 && connectionException == null && !cancelled) { 203 synchronized (this) { 204 res = (P) resultQueue.poll(); 205 if (res != null) { 206 return res; 207 } 208 wait(remainingWait); 209 } 210 remainingWait = timeout - (System.currentTimeMillis() - waitStart); 211 } 212 return res; 213 } 214 215 /** 216 * Returns the next available stanza. The method in equivalent to 217 * {@link #nextResultOrThrow(long)} where the timeout argument is the default reply timeout of 218 * the connection associated with this collector. 219 * 220 * @param <P> type of the result stanza. 221 * @return the next available stanza. 222 * @throws XMPPErrorException in case an error response was received. 223 * @throws NoResponseException if there was no response from the server. 224 * @throws InterruptedException if the calling thread was interrupted. 225 * @throws NotConnectedException if the XMPP connection is not connected. 226 * @see #nextResultOrThrow(long) 227 */ 228 @SuppressWarnings("TypeParameterUnusedInFormals") 229 public <P extends Stanza> P nextResultOrThrow() throws NoResponseException, XMPPErrorException, 230 InterruptedException, NotConnectedException { 231 return nextResultOrThrow(connection.getReplyTimeout()); 232 } 233 234 /** 235 * Returns the next available stanza. The method call will block until a stanza is 236 * available or the <code>timeout</code> has elapsed. This method does also cancel the 237 * collector in every case. 238 * <p> 239 * Three things can happen when waiting for an response: 240 * </p> 241 * <ol> 242 * <li>A result response arrives.</li> 243 * <li>An error response arrives.</li> 244 * <li>An timeout occurs.</li> 245 * <li>The thread is interrupted</li> 246 * </ol> 247 * <p> 248 * in which this method will 249 * </p> 250 * <ol> 251 * <li>return with the result.</li> 252 * <li>throw an {@link XMPPErrorException}.</li> 253 * <li>throw an {@link NoResponseException}.</li> 254 * <li>throw an {@link InterruptedException}.</li> 255 * </ol> 256 * <p> 257 * Additionally the method will throw a {@link NotConnectedException} if no response was 258 * received and the connection got disconnected. 259 * </p> 260 * 261 * @param timeout the amount of time to wait for the next stanza in milliseconds. 262 * @param <P> type of the result stanza. 263 * @return the next available stanza. 264 * @throws NoResponseException if there was no response from the server. 265 * @throws XMPPErrorException in case an error response was received. 266 * @throws InterruptedException if the calling thread was interrupted. 267 * @throws NotConnectedException if there was no response and the connection got disconnected. 268 */ 269 @SuppressWarnings("TypeParameterUnusedInFormals") 270 public <P extends Stanza> P nextResultOrThrow(long timeout) throws NoResponseException, 271 XMPPErrorException, InterruptedException, NotConnectedException { 272 P result; 273 try { 274 result = nextResult(timeout); 275 } finally { 276 cancel(); 277 } 278 if (result == null) { 279 if (connectionException != null) { 280 throw new NotConnectedException(connection, packetFilter, connectionException); 281 } 282 if (!connection.isConnected()) { 283 throw new NotConnectedException(connection, packetFilter); 284 } 285 throw NoResponseException.newWith(timeout, this, cancelled); 286 } 287 288 XMPPErrorException.ifHasErrorThenThrow(result); 289 290 return result; 291 } 292 293 private List<Stanza> collectedCache; 294 295 /** 296 * Return a list of all collected stanzas. This method must be invoked after the collector has been cancelled. 297 * 298 * @return a list of collected stanzas. 299 * @since 4.3.0 300 */ 301 public List<Stanza> getCollectedStanzasAfterCancelled() { 302 if (!cancelled) { 303 throw new IllegalStateException("Stanza collector was not yet cancelled"); 304 } 305 306 if (collectedCache == null) { 307 collectedCache = new ArrayList<>(getCollectedCount()); 308 collectedCache.addAll(resultQueue); 309 } 310 311 return collectedCache; 312 } 313 314 /** 315 * Get the number of collected stanzas this stanza collector has collected so far. 316 * 317 * @return the count of collected stanzas. 318 * @since 4.1 319 */ 320 public synchronized int getCollectedCount() { 321 return resultQueue.size(); 322 } 323 324 private String stringCache; 325 326 @Override 327 public String toString() { 328 if (stringCache == null) { 329 StringBuilder sb = new StringBuilder(128); 330 sb.append("Stanza Collector filter='").append(packetFilter).append('\''); 331 if (request != null) { 332 sb.append(" request='").append(request).append('\''); 333 } 334 stringCache = sb.toString(); 335 } 336 return stringCache; 337 } 338 339 synchronized void notifyConnectionError(Exception exception) { 340 connectionException = exception; 341 notifyAll(); 342 } 343 344 /** 345 * Processes a stanza to see if it meets the criteria for this stanza collector. 346 * If so, the stanza is added to the result queue. 347 * 348 * @param packet the stanza to process. 349 */ 350 void processStanza(Stanza packet) { 351 if (packetFilter == null || packetFilter.accept(packet)) { 352 synchronized (this) { 353 if (resultQueue.size() == maxQueueSize) { 354 Stanza rolledOverStanza = resultQueue.poll(); 355 assert rolledOverStanza != null; 356 } 357 resultQueue.add(packet); 358 notifyAll(); 359 } 360 if (collectorToReset != null) { 361 collectorToReset.waitStart = System.currentTimeMillis(); 362 } 363 } 364 } 365 366 private void throwIfCancelled() { 367 if (cancelled) { 368 throw new IllegalStateException("Stanza collector already cancelled"); 369 } 370 } 371 372 /** 373 * Get a new stanza collector configuration instance. 374 * 375 * @return a new stanza collector configuration. 376 */ 377 public static Configuration newConfiguration() { 378 return new Configuration(); 379 } 380 381 public static final class Configuration { 382 private StanzaFilter packetFilter; 383 private int size = SmackConfiguration.getStanzaCollectorSize(); 384 private StanzaCollector collectorToReset; 385 private Stanza request; 386 387 private Configuration() { 388 } 389 390 /** 391 * Set the stanza filter used by this collector. If <code>null</code>, then all stanzas will 392 * get collected by this collector. 393 * 394 * @param stanzaFilter TODO javadoc me please 395 * @return a reference to this configuration. 396 */ 397 public Configuration setStanzaFilter(StanzaFilter stanzaFilter) { 398 this.packetFilter = stanzaFilter; 399 return this; 400 } 401 402 /** 403 * Set the maximum size of this collector, i.e. how many stanzas this collector will collect 404 * before dropping old ones. 405 * 406 * @param size TODO javadoc me please 407 * @return a reference to this configuration. 408 */ 409 public Configuration setSize(int size) { 410 this.size = size; 411 return this; 412 } 413 414 /** 415 * Set the collector which timeout for the next result is reset once this collector collects 416 * a packet. 417 * 418 * @param collector TODO javadoc me please 419 * @return a reference to this configuration. 420 */ 421 public Configuration setCollectorToReset(StanzaCollector collector) { 422 this.collectorToReset = collector; 423 return this; 424 } 425 426 public Configuration setRequest(Stanza request) { 427 this.request = request; 428 return this; 429 } 430 } 431 432 @Override 433 public void close() { 434 cancel(); 435 } 436 437}