001/** 002 * 003 * Copyright 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 */ 017package org.jivesoftware.smack; 018 019/** 020 * A handle of a listener, typically added to a connection. This handle implements {@link AutoCloseable}, 021 * allowing the the listener to be added using a try-with-resources statement. 022 */ 023public abstract class ListenerHandle implements AutoCloseable { 024 025 protected final XMPPConnection connection; 026 protected final StanzaListener listener; 027 028 private ListenerHandle(XMPPConnection connection, StanzaListener listener) { 029 this.connection = connection; 030 this.listener = listener; 031 } 032 033 /** 034 * Remove the handle's listener from the connection. 035 * @return true if the stanza listener was removed 036 */ 037 public abstract boolean removeListener(); 038 039 @Override 040 public final void close() { 041 removeListener(); 042 } 043 044 static class StanzaListenerHandle extends ListenerHandle { 045 StanzaListenerHandle(XMPPConnection connection, StanzaListener listener) { 046 super(connection, listener); 047 } 048 049 @Override 050 public boolean removeListener() { 051 return connection.removeStanzaListener(listener); 052 } 053 } 054 055 static class AsyncStanzaListenerHandle extends ListenerHandle { 056 AsyncStanzaListenerHandle(XMPPConnection connection, StanzaListener listener) { 057 super(connection, listener); 058 } 059 060 @Override 061 public boolean removeListener() { 062 return connection.removeAsyncStanzaListener(listener); 063 } 064 } 065 066 static class SyncStanzaListenerHandle extends ListenerHandle { 067 SyncStanzaListenerHandle(XMPPConnection connection, StanzaListener listener) { 068 super(connection, listener); 069 } 070 071 @Override 072 public boolean removeListener() { 073 return connection.removeSyncStanzaListener(listener); 074 } 075 } 076}