diff --git a/.travis.yml b/.travis.yml index a371c394f..5b6c55b30 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,6 @@ android: - android-8 jdk: - oraclejdk8 - - oraclejdk7 sudo: false cache: directories: diff --git a/build.gradle b/build.gradle index 5cfd4ad21..f4e013e2e 100644 --- a/build.gradle +++ b/build.gradle @@ -170,7 +170,7 @@ allprojects { // version 52.0" error messages caused by the errorprone javac. // See https://github.com/tbroyer/gradle-errorprone-plugin/issues/18 for more information. configurations.errorprone { - resolutionStrategy.force 'com.google.errorprone:error_prone_core:2.0.5' + resolutionStrategy.force 'com.google.errorprone:error_prone_core:2.0.15' } } diff --git a/config/checkstyle.xml b/config/checkstyle.xml index 08703c562..ce2345c20 100644 --- a/config/checkstyle.xml +++ b/config/checkstyle.xml @@ -35,10 +35,6 @@ - - - - @@ -89,6 +85,10 @@ + + + + diff --git a/smack-android-extensions/src/main/java/org/jivesoftware/smackx/ping/android/ServerPingWithAlarmManager.java b/smack-android-extensions/src/main/java/org/jivesoftware/smackx/ping/android/ServerPingWithAlarmManager.java index 6d9fe943b..054bc0418 100644 --- a/smack-android-extensions/src/main/java/org/jivesoftware/smackx/ping/android/ServerPingWithAlarmManager.java +++ b/smack-android-extensions/src/main/java/org/jivesoftware/smackx/ping/android/ServerPingWithAlarmManager.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2014 Florian Schmaus + * Copyright © 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,116 +63,116 @@ import android.os.SystemClock; */ public final class ServerPingWithAlarmManager extends Manager { - private static final Logger LOGGER = Logger.getLogger(ServerPingWithAlarmManager.class - .getName()); + private static final Logger LOGGER = Logger.getLogger(ServerPingWithAlarmManager.class + .getName()); - private static final String PING_ALARM_ACTION = "org.igniterealtime.smackx.ping.ACTION"; + private static final String PING_ALARM_ACTION = "org.igniterealtime.smackx.ping.ACTION"; - private static final Map INSTANCES = new WeakHashMap(); + private static final Map INSTANCES = new WeakHashMap(); - static { - XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { - @Override - public void connectionCreated(XMPPConnection connection) { - getInstanceFor(connection); - } - }); - } + static { + XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override + public void connectionCreated(XMPPConnection connection) { + getInstanceFor(connection); + } + }); + } - public static synchronized ServerPingWithAlarmManager getInstanceFor(XMPPConnection connection) { - ServerPingWithAlarmManager serverPingWithAlarmManager = INSTANCES.get(connection); - if (serverPingWithAlarmManager == null) { - serverPingWithAlarmManager = new ServerPingWithAlarmManager(connection); - INSTANCES.put(connection, serverPingWithAlarmManager); - } - return serverPingWithAlarmManager; - } + public static synchronized ServerPingWithAlarmManager getInstanceFor(XMPPConnection connection) { + ServerPingWithAlarmManager serverPingWithAlarmManager = INSTANCES.get(connection); + if (serverPingWithAlarmManager == null) { + serverPingWithAlarmManager = new ServerPingWithAlarmManager(connection); + INSTANCES.put(connection, serverPingWithAlarmManager); + } + return serverPingWithAlarmManager; + } - private boolean mEnabled = true; + private boolean mEnabled = true; - private ServerPingWithAlarmManager(XMPPConnection connection) { - super(connection); - } + private ServerPingWithAlarmManager(XMPPConnection connection) { + super(connection); + } /** * If enabled, ServerPingWithAlarmManager will call {@link PingManager#pingServerIfNecessary()} * for the connection of this instance every half hour. - * + * * @param enabled */ - public void setEnabled(boolean enabled) { - mEnabled = enabled; - } + public void setEnabled(boolean enabled) { + mEnabled = enabled; + } - public boolean isEnabled() { - return mEnabled; - } + public boolean isEnabled() { + return mEnabled; + } - private static final BroadcastReceiver ALARM_BROADCAST_RECEIVER = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - LOGGER.fine("Ping Alarm broadcast received"); - Set> managers; - synchronized (ServerPingWithAlarmManager.class) { - // Make a copy to avoid ConcurrentModificationException when - // iterating directly over INSTANCES and the Set is modified - // concurrently by creating a new ServerPingWithAlarmManager. - managers = new HashSet<>(INSTANCES.entrySet()); - } - for (Entry entry : managers) { - XMPPConnection connection = entry.getKey(); - if (entry.getValue().isEnabled()) { - LOGGER.fine("Calling pingServerIfNecessary for connection " - + connection); - final PingManager pingManager = PingManager.getInstanceFor(connection); - // Android BroadcastReceivers have a timeout of 60 seconds. - // The connections reply timeout may be higher, which causes - // timeouts of the broadcast receiver and a subsequent ANR - // of the App of the broadcast receiver. We therefore need - // to call pingServerIfNecessary() in a new thread to avoid - // this. It could happen that the device gets back to sleep - // until the Thread runs, but that's a risk we are willing - // to take into account as it's unlikely. - Async.go(new Runnable() { - @Override - public void run() { - pingManager.pingServerIfNecessary(); - } - }, "PingServerIfNecessary (" + connection.getConnectionCounter() + ')'); - } else { - LOGGER.fine("NOT calling pingServerIfNecessary (disabled) on connection " - + connection.getConnectionCounter()); - } - } - } - }; + private static final BroadcastReceiver ALARM_BROADCAST_RECEIVER = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + LOGGER.fine("Ping Alarm broadcast received"); + Set> managers; + synchronized (ServerPingWithAlarmManager.class) { + // Make a copy to avoid ConcurrentModificationException when + // iterating directly over INSTANCES and the Set is modified + // concurrently by creating a new ServerPingWithAlarmManager. + managers = new HashSet<>(INSTANCES.entrySet()); + } + for (Entry entry : managers) { + XMPPConnection connection = entry.getKey(); + if (entry.getValue().isEnabled()) { + LOGGER.fine("Calling pingServerIfNecessary for connection " + + connection); + final PingManager pingManager = PingManager.getInstanceFor(connection); + // Android BroadcastReceivers have a timeout of 60 seconds. + // The connections reply timeout may be higher, which causes + // timeouts of the broadcast receiver and a subsequent ANR + // of the App of the broadcast receiver. We therefore need + // to call pingServerIfNecessary() in a new thread to avoid + // this. It could happen that the device gets back to sleep + // until the Thread runs, but that's a risk we are willing + // to take into account as it's unlikely. + Async.go(new Runnable() { + @Override + public void run() { + pingManager.pingServerIfNecessary(); + } + }, "PingServerIfNecessary (" + connection.getConnectionCounter() + ')'); + } else { + LOGGER.fine("NOT calling pingServerIfNecessary (disabled) on connection " + + connection.getConnectionCounter()); + } + } + } + }; - private static Context sContext; - private static PendingIntent sPendingIntent; - private static AlarmManager sAlarmManager; + private static Context sContext; + private static PendingIntent sPendingIntent; + private static AlarmManager sAlarmManager; /** * Register a pending intent with the AlarmManager to be broadcasted every half hour and * register the alarm broadcast receiver to receive this intent. The receiver will check all * known questions if a ping is Necessary when invoked by the alarm intent. - * + * * @param context */ - public static void onCreate(Context context) { - sContext = context; - context.registerReceiver(ALARM_BROADCAST_RECEIVER, new IntentFilter(PING_ALARM_ACTION)); - sAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - sPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(PING_ALARM_ACTION), 0); - sAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, - SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_HALF_HOUR, - AlarmManager.INTERVAL_HALF_HOUR, sPendingIntent); - } + public static void onCreate(Context context) { + sContext = context; + context.registerReceiver(ALARM_BROADCAST_RECEIVER, new IntentFilter(PING_ALARM_ACTION)); + sAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + sPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(PING_ALARM_ACTION), 0); + sAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_HALF_HOUR, + AlarmManager.INTERVAL_HALF_HOUR, sPendingIntent); + } /** * Unregister the alarm broadcast receiver and cancel the alarm. */ - public static void onDestroy() { - sContext.unregisterReceiver(ALARM_BROADCAST_RECEIVER); - sAlarmManager.cancel(sPendingIntent); - } + public static void onDestroy() { + sContext.unregisterReceiver(ALARM_BROADCAST_RECEIVER); + sAlarmManager.cancel(sPendingIntent); + } } diff --git a/smack-android/src/main/java/org/jivesoftware/smack/android/AndroidSmackInitializer.java b/smack-android/src/main/java/org/jivesoftware/smack/android/AndroidSmackInitializer.java index bae2beb93..b58f8679c 100644 --- a/smack-android/src/main/java/org/jivesoftware/smack/android/AndroidSmackInitializer.java +++ b/smack-android/src/main/java/org/jivesoftware/smack/android/AndroidSmackInitializer.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2014 Florian Schmaus + * Copyright © 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,12 +28,12 @@ import org.jivesoftware.smack.util.stringencoder.android.AndroidBase64UrlSafeEnc public class AndroidSmackInitializer implements SmackInitializer { - @Override - public List initialize() { - SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier()); - Base64.setEncoder(AndroidBase64Encoder.getInstance()); - Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance()); - return null; - } + @Override + public List initialize() { + SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier()); + Base64.setEncoder(AndroidBase64Encoder.getInstance()); + Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance()); + return null; + } } diff --git a/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/BOSHConfiguration.java b/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/BOSHConfiguration.java index 92615f32e..252a49a43 100644 --- a/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/BOSHConfiguration.java +++ b/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/BOSHConfiguration.java @@ -55,6 +55,7 @@ public final class BOSHConfiguration extends ConnectionConfiguration { return proxy != null; } + @Override public ProxyInfo getProxyInfo() { return proxy; } diff --git a/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/XMPPBOSHConnection.java b/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/XMPPBOSHConnection.java index f88cc7c3e..abf9105f6 100644 --- a/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/XMPPBOSHConnection.java +++ b/smack-bosh/src/main/java/org/jivesoftware/smack/bosh/XMPPBOSHConnection.java @@ -203,11 +203,13 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { saslFeatureReceived.reportSuccess(); } + @Override public boolean isSecureConnection() { // TODO: Implement SSL usage return false; } + @Override public boolean isUsingCompression() { // TODO: Implement compression return false; @@ -313,16 +315,25 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { /** * Initialize the SmackDebugger which allows to log and debug XML traffic. */ + @Override protected void initDebugger() { // TODO: Maybe we want to extend the SmackDebugger for simplification // and a performance boost. // Initialize a empty writer which discards all data. writer = new Writer() { - public void write(char[] cbuf, int off, int len) { /* ignore */} - public void close() { /* ignore */ } - public void flush() { /* ignore */ } - }; + @Override + public void write(char[] cbuf, int off, int len) { + /* ignore */} + + @Override + public void close() { + /* ignore */ } + + @Override + public void flush() { + /* ignore */ } + }; // Initialize a pipe for received raw data. try { @@ -338,6 +349,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { // Add listeners for the received and sent raw data. client.addBOSHClientResponseListener(new BOSHClientResponseListener() { + @Override public void responseReceived(BOSHMessageEvent event) { if (event.getBody() != null) { try { @@ -350,6 +362,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { } }); client.addBOSHClientRequestListener(new BOSHClientRequestListener() { + @Override public void requestSent(BOSHMessageEvent event) { if (event.getBody() != null) { try { @@ -366,6 +379,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { private Thread thread = this; private int bufferLength = 1024; + @Override public void run() { try { char[] cbuf = new char[bufferLength]; @@ -406,6 +420,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { * Process the connection listeners and try to login if the * connection was formerly authenticated and is now reconnected. */ + @Override public void connectionEvent(BOSHClientConnEvent connEvent) { try { if (connEvent.isConnected()) { @@ -463,6 +478,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { * * @param event the BOSH client response which includes the received packet. */ + @Override public void responseReceived(BOSHMessageEvent event) { AbstractBody body = event.getBody(); if (body != null) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java b/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java index b75e937a5..eab2710c2 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java @@ -1494,6 +1494,12 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { final StanzaListener packetListener = new StanzaListener() { @Override public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException { + boolean removed = removeAsyncStanzaListener(this); + if (!removed) { + // We lost a race against the "no response" handling runnable. Avoid calling the callback, as the + // exception callback will be invoked (if any). + return; + } try { XMPPErrorException.ifHasErrorThenThrow(packet); callback.processStanza(packet); @@ -1503,9 +1509,6 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { exceptionCallback.processException(e); } } - finally { - removeAsyncStanzaListener(this); - } } }; removeCallbacksService.schedule(new Runnable() { @@ -1613,6 +1616,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { private long lastStanzaReceived; + @Override public long getLastStanzaReceived() { return lastStanzaReceived; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java b/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java index 79ef71e67..a5b12da29 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java @@ -576,14 +576,17 @@ public abstract class ConnectionConfiguration { } /** - * Set the resource to use. + * Set the resource we are requesting from the server. *

- * If resource is null, then the server will automatically create a resource for the - * client. Default resource is "Smack". + * If resource is null, the default, then the server will automatically create a + * resource for the client. Note that XMPP clients only suggest this resource to the server. XMPP servers are + * allowed to ignore the client suggested resource and instead assign a completely different + * resource (see RFC 6120 § 7.7.1). *

* * @param resource the resource to use. * @return a reference to this builder. + * @see RFC 6120 § 7.7.1 */ public B setResource(Resourcepart resource) { this.resource = resource; @@ -591,7 +594,7 @@ public abstract class ConnectionConfiguration { } /** - * Set the resource to use. + * Set the resource we are requesting from the server. * * @param resource the non-null CharSequence to use a resource. * @return a reference ot this builder. diff --git a/smack-core/src/main/java/org/jivesoftware/smack/ReconnectionManager.java b/smack-core/src/main/java/org/jivesoftware/smack/ReconnectionManager.java index 90a5f9a6a..4430b1f9e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/ReconnectionManager.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/ReconnectionManager.java @@ -70,6 +70,7 @@ public final class ReconnectionManager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { if (connection instanceof AbstractXMPPConnection) { ReconnectionManager.getInstanceFor((AbstractXMPPConnection) connection); @@ -204,6 +205,7 @@ public final class ReconnectionManager { /** * The process will try the reconnection until the connection succeed or the user cancel it */ + @Override public void run() { final AbstractXMPPConnection connection = weakRefConnection.get(); if (connection == null) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java b/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java index 74f8d49fb..7bdb8e18a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java @@ -37,6 +37,7 @@ import org.jivesoftware.smack.sasl.core.SASLXOauth2Mechanism; import org.jivesoftware.smack.sasl.core.SCRAMSHA1Mechanism; import org.jivesoftware.smack.sasl.core.ScramSha1PlusMechanism; import org.jivesoftware.smack.util.FileUtils; +import org.jivesoftware.smack.util.StringUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; @@ -60,7 +61,7 @@ public final class SmackInitialization { static { String smackVersion; try { - BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtils.getStreamForUrl("classpath:org.jivesoftware.smack/version", null))); + BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtils.getStreamForUrl("classpath:org.jivesoftware.smack/version", null), StringUtils.UTF8)); smackVersion = reader.readLine(); try { reader.close(); @@ -232,7 +233,7 @@ public final class SmackInitialization { } } if (SmackInitializer.class.isAssignableFrom(initClass)) { - SmackInitializer initializer = (SmackInitializer) initClass.newInstance(); + SmackInitializer initializer = (SmackInitializer) initClass.getConstructor().newInstance(); List exceptions = initializer.initialize(); if (exceptions == null || exceptions.size() == 0) { LOGGER.log(Level.FINE, "Loaded SmackInitializer " + className); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/debugger/AbstractDebugger.java b/smack-core/src/main/java/org/jivesoftware/smack/debugger/AbstractDebugger.java index a7940fe08..7a58e64cb 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/debugger/AbstractDebugger.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/debugger/AbstractDebugger.java @@ -49,6 +49,7 @@ public abstract class AbstractDebugger implements SmackDebugger { // Create a special Reader that wraps the main Reader and logs data to the GUI. this.reader = new ObservableReader(reader); readerListener = new ReaderListener() { + @Override public void read(String str) { log("RECV (" + connection.getConnectionCounter() + "): " + str); } @@ -58,6 +59,7 @@ public abstract class AbstractDebugger implements SmackDebugger { // Create a special Writer that wraps the main Writer and logs data to the GUI. this.writer = new ObservableWriter(writer); writerListener = new WriterListener() { + @Override public void write(String str) { log("SENT (" + connection.getConnectionCounter() + "): " + str); } @@ -68,6 +70,7 @@ public abstract class AbstractDebugger implements SmackDebugger { // the GUI. This is what we call "interpreted" packet data, since it's the packet // data as Smack sees it and not as it's coming in as raw XML. listener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { if (printInterpreted) { log("RCV PKT (" + connection.getConnectionCounter() + "): " + packet.toXML()); @@ -76,10 +79,12 @@ public abstract class AbstractDebugger implements SmackDebugger { }; connListener = new ConnectionListener() { + @Override public void connected(XMPPConnection connection) { log("XMPPConnection connected (" + connection + ")"); } + @Override public void authenticated(XMPPConnection connection, boolean resumed) { String logString = "XMPPConnection authenticated (" + connection + ")"; if (resumed) { @@ -87,6 +92,7 @@ public abstract class AbstractDebugger implements SmackDebugger { } log(logString); } + @Override public void connectionClosed() { log( "XMPPConnection closed (" + @@ -94,24 +100,28 @@ public abstract class AbstractDebugger implements SmackDebugger { ")"); } + @Override public void connectionClosedOnError(Exception e) { log( "XMPPConnection closed due to an exception (" + connection + ")", e); } + @Override public void reconnectionFailed(Exception e) { log( "Reconnection failed due to an exception (" + connection + ")", e); } + @Override public void reconnectionSuccessful() { log( "XMPPConnection reconnected (" + connection + ")"); } + @Override public void reconnectingIn(int seconds) { log( "XMPPConnection (" + @@ -125,6 +135,7 @@ public abstract class AbstractDebugger implements SmackDebugger { protected abstract void log(String logMessage, Throwable throwable); + @Override public Reader newConnectionReader(Reader newReader) { reader.removeReaderListener(readerListener); ObservableReader debugReader = new ObservableReader(newReader); @@ -133,6 +144,7 @@ public abstract class AbstractDebugger implements SmackDebugger { return reader; } + @Override public Writer newConnectionWriter(Writer newWriter) { writer.removeWriterListener(writerListener); ObservableWriter debugWriter = new ObservableWriter(newWriter); @@ -159,18 +171,22 @@ public abstract class AbstractDebugger implements SmackDebugger { connection.addConnectionListener(connListener); } + @Override public Reader getReader() { return reader; } + @Override public Writer getWriter() { return writer; } + @Override public StanzaListener getReaderListener() { return listener; } + @Override public StanzaListener getWriterListener() { return null; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractFromToMatchesFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractFromToMatchesFilter.java new file mode 100644 index 000000000..d9b5605e0 --- /dev/null +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractFromToMatchesFilter.java @@ -0,0 +1,72 @@ +/** + * + * Copyright 2017 Florian Schmaus. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.filter; + +import org.jivesoftware.smack.packet.Stanza; +import org.jxmpp.jid.Jid; + +public abstract class AbstractFromToMatchesFilter implements StanzaFilter { + + private final Jid address; + + /** + * Flag that indicates if the checking will be done against bare JID addresses or full JIDs. + */ + private final boolean ignoreResourcepart; + + /** + * Creates a filter matching on the address returned by {@link #getAddressToCompare(Stanza)}. The address must be + * the same as the filter address. The second parameter specifies whether the full or the bare addresses are + * compared. + * + * @param address The address to filter for. If null is given, then + * {@link #getAddressToCompare(Stanza)} must also return null to match. + * @param ignoreResourcepart + */ + protected AbstractFromToMatchesFilter(Jid address, boolean ignoreResourcepart) { + if (address != null && ignoreResourcepart) { + this.address = address.asBareJid(); + } + else { + this.address = address; + } + this.ignoreResourcepart = ignoreResourcepart; + } + + @Override + public final boolean accept(final Stanza stanza) { + Jid stanzaAddress = getAddressToCompare(stanza); + + if (stanzaAddress == null) { + return address == null; + } + + if (ignoreResourcepart) { + stanzaAddress = stanzaAddress.asBareJid(); + } + + return stanzaAddress.equals(address); + } + + protected abstract Jid getAddressToCompare(Stanza stanza); + + @Override + public final String toString() { + String matchMode = ignoreResourcepart ? "ignoreResourcepart" : "full"; + return getClass().getSimpleName() + " (" + matchMode + "): " + address; + } +} diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/AndFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/AndFilter.java index a1a5749fc..216c3ddde 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/AndFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/AndFilter.java @@ -44,6 +44,7 @@ public class AndFilter extends AbstractListFilter implements StanzaFilter { super(filters); } + @Override public boolean accept(Stanza packet) { for (StanzaFilter filter : filters) { if (!filter.accept(packet)) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/FromMatchesFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/FromMatchesFilter.java index 08b7f2c89..1e46de307 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/FromMatchesFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/FromMatchesFilter.java @@ -1,6 +1,6 @@ /** * - * Copyright 2003-2014 Jive Software. + * Copyright 2003-2014 Jive Software, 2017 Florian Schmaus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.jivesoftware.smack.filter; import org.jivesoftware.smack.packet.Stanza; @@ -28,14 +27,9 @@ import org.jxmpp.jid.Jid; * * @author Gaston Dombiak */ -public class FromMatchesFilter implements StanzaFilter { +public final class FromMatchesFilter extends AbstractFromToMatchesFilter { - private final Jid address; - - /** - * Flag that indicates if the checking will be done against bare JID addresses or full JIDs. - */ - private final boolean ignoreResourcepart; + public final static FromMatchesFilter MATCH_NO_FROM_SET = create(null); /** * Creates a filter matching on the "from" field. The from address must be the same as the @@ -47,13 +41,7 @@ public class FromMatchesFilter implements StanzaFilter { * @param ignoreResourcepart */ public FromMatchesFilter(Jid address, boolean ignoreResourcepart) { - if (address != null && ignoreResourcepart) { - this.address = address.asBareJid(); - } - else { - this.address = address; - } - this.ignoreResourcepart = ignoreResourcepart; + super(address, ignoreResourcepart); } /** @@ -61,51 +49,38 @@ public class FromMatchesFilter implements StanzaFilter { * the filter address with the bare from address. Otherwise, compares the filter address * with the full from address. * - * @param address The address to filter for. If null is given, the stanza(/packet) must not + * @param address The address to filter for. If null is given, the stanza must not * have a from address. */ public static FromMatchesFilter create(Jid address) { - return new FromMatchesFilter(address, address.hasNoResource()) ; + return new FromMatchesFilter(address, address != null ? address.hasNoResource() : false) ; } /** * Creates a filter matching on the "from" field. Compares the bare version of from and filter * address. * - * @param address The address to filter for. If null is given, the stanza(/packet) must not + * @param address The address to filter for. If null is given, the stanza must not * have a from address. */ public static FromMatchesFilter createBare(Jid address) { - address = (address == null) ? null : address; return new FromMatchesFilter(address, true); } - /** - * Creates a filter matching on the "from" field. Compares the full version of from and filter + * Creates a filter matching on the "from" field. Compares the full version, if available, of from and filter * address. * - * @param address The address to filter for. If null is given, the stanza(/packet) must not + * @param address The address to filter for. If null is given, the stanza must not * have a from address. */ public static FromMatchesFilter createFull(Jid address) { return new FromMatchesFilter(address, false); } - public boolean accept(Stanza packet) { - Jid from = packet.getFrom(); - if (from == null) { - return address == null; - } - - if (ignoreResourcepart) { - from = from.asBareJid(); - } - return from.equals(address); + @Override + protected Jid getAddressToCompare(Stanza stanza) { + return stanza.getFrom(); } - public String toString() { - String matchMode = ignoreResourcepart ? "ignoreResourcepart" : "full"; - return getClass().getSimpleName() + " (" + matchMode + "): " + address; - } } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/IQTypeFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/IQTypeFilter.java index f84bdadb2..fe50083df 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/IQTypeFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/IQTypeFilter.java @@ -35,12 +35,12 @@ public final class IQTypeFilter extends FlexibleStanzaTypeFilter { public static final StanzaFilter ERROR = new IQTypeFilter(Type.error); public static final StanzaFilter GET_OR_SET = new OrFilter(GET, SET); - private final IQ.Type type; + private final IQ.Type type; - private IQTypeFilter(IQ.Type type) { + private IQTypeFilter(IQ.Type type) { super(IQ.class); - this.type = Objects.requireNonNull(type, "Type must not be null"); - } + this.type = Objects.requireNonNull(type, "Type must not be null"); + } @Override protected boolean acceptSpecific(IQ iq) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/NotFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/NotFilter.java index e657cf4eb..c836be1c1 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/NotFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/NotFilter.java @@ -39,6 +39,7 @@ public class NotFilter implements StanzaFilter { this.filter = Objects.requireNonNull(filter, "Parameter must not be null."); } + @Override public boolean accept(Stanza packet) { return !filter.accept(packet); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketExtensionFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketExtensionFilter.java index f6458194f..82c1016c0 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketExtensionFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketExtensionFilter.java @@ -67,6 +67,7 @@ public class PacketExtensionFilter implements StanzaFilter { this(packetExtension.getElementName(), packetExtension.getNamespace()); } + @Override public boolean accept(Stanza packet) { return packet.hasExtension(elementName, namespace); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketIDFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketIDFilter.java index e4ea23248..d596f9ef9 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketIDFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketIDFilter.java @@ -54,10 +54,12 @@ public class PacketIDFilter implements StanzaFilter { this.packetID = packetID; } + @Override public boolean accept(Stanza packet) { return packetID.equals(packet.getStanzaId()); } + @Override public String toString() { return getClass().getSimpleName() + ": id=" + packetID; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketTypeFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketTypeFilter.java index f20fdeac1..8b254f56e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketTypeFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/PacketTypeFilter.java @@ -51,6 +51,7 @@ public class PacketTypeFilter implements StanzaFilter { this.packetType = packetType; } + @Override public boolean accept(Stanza packet) { return packetType.isInstance(packet); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaExtensionFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaExtensionFilter.java index e8fb46d46..f7f810e82 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaExtensionFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaExtensionFilter.java @@ -65,6 +65,7 @@ public class StanzaExtensionFilter implements StanzaFilter { this(packetExtension.getElementName(), packetExtension.getNamespace()); } + @Override public boolean accept(Stanza packet) { return packet.hasExtension(elementName, namespace); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaIdFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaIdFilter.java index 3cc9740a1..0e6b0f404 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaIdFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaIdFilter.java @@ -47,10 +47,12 @@ public class StanzaIdFilter implements StanzaFilter { this.stanzaId = StringUtils.requireNotNullOrEmpty(stanzaID, "Stanza ID must not be null or empty."); } + @Override public boolean accept(Stanza stanza) { return stanzaId.equals(stanza.getStanzaId()); } + @Override public String toString() { return getClass().getSimpleName() + ": id=" + stanzaId; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaTypeFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaTypeFilter.java index 8b8971cda..156a7914e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaTypeFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaTypeFilter.java @@ -51,6 +51,7 @@ public final class StanzaTypeFilter implements StanzaFilter { this.packetType = packetType; } + @Override public boolean accept(Stanza packet) { return packetType.isInstance(packet); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/ToFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/ToFilter.java index 115c30f15..d8964b5f1 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/ToFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/ToFilter.java @@ -19,6 +19,12 @@ package org.jivesoftware.smack.filter; import org.jivesoftware.smack.packet.Stanza; import org.jxmpp.jid.Jid; +/** + * Match based on the 'to' attribute of a Stanza. + * + * @deprecated use {@link ToMatchesFilter} instead. + */ +@Deprecated public class ToFilter implements StanzaFilter { private final Jid to; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/ToMatchesFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/ToMatchesFilter.java new file mode 100644 index 000000000..99ca2a762 --- /dev/null +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/ToMatchesFilter.java @@ -0,0 +1,69 @@ +/** + * + * Copyright 2017 Florian Schmaus. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.filter; + +import org.jivesoftware.smack.packet.Stanza; +import org.jxmpp.jid.Jid; + +public final class ToMatchesFilter extends AbstractFromToMatchesFilter { + + public static final ToMatchesFilter MATCH_NO_TO_SET = create(null); + + public ToMatchesFilter(Jid address, boolean ignoreResourcepart) { + super(address, ignoreResourcepart); + } + + /** + * Creates a filter matching on the "to" field. If the filter address is bare, compares + * the filter address with the bare from address. Otherwise, compares the filter address + * with the full from address. + * + * @param address The address to filter for. If null is given, the stanza must not + * have a from address. + */ + public static ToMatchesFilter create(Jid address) { + return new ToMatchesFilter(address, address != null ? address.hasNoResource() : false) ; + } + + /** + * Creates a filter matching on the "to" field. Compares the bare version of to and filter + * address. + * + * @param address The address to filter for. If null is given, the stanza must not + * have a from address. + */ + public static ToMatchesFilter createBare(Jid address) { + return new ToMatchesFilter(address, true); + } + + /** + * Creates a filter matching on the "to" field. Compares the full version, if available, of to and filter + * address. + * + * @param address The address to filter for. If null is given, the stanza must not + * have a from address. + */ + public static ToMatchesFilter createFull(Jid address) { + return new ToMatchesFilter(address, false); + } + + @Override + protected Jid getAddressToCompare(Stanza stanza) { + return stanza.getTo(); + } + +} diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/DefaultExtensionElement.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/DefaultExtensionElement.java index 88166db43..e51b5b4ee 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/packet/DefaultExtensionElement.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/DefaultExtensionElement.java @@ -70,6 +70,7 @@ public class DefaultExtensionElement implements ExtensionElement { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return elementName; } @@ -79,6 +80,7 @@ public class DefaultExtensionElement implements ExtensionElement { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return namespace; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java index e0ec0ce82..ebf18faef 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java @@ -570,6 +570,7 @@ public final class Message extends Stanza implements TypedCloneable { } + @Override public int hashCode() { final int prime = 31; int result = 1; @@ -578,6 +579,7 @@ public final class Message extends Stanza implements TypedCloneable { return result; } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -632,6 +634,7 @@ public final class Message extends Stanza implements TypedCloneable { return message; } + @Override public int hashCode() { final int prime = 31; int result = 1; @@ -640,6 +643,7 @@ public final class Message extends Stanza implements TypedCloneable { return result; } + @Override public boolean equals(Object obj) { if (this == obj) { return true; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/provider/IntrospectionProvider.java b/smack-core/src/main/java/org/jivesoftware/smack/provider/IntrospectionProvider.java index 88549db4f..e51033f43 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/provider/IntrospectionProvider.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/provider/IntrospectionProvider.java @@ -78,7 +78,7 @@ public class IntrospectionProvider{ IOException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { ParserUtils.assertAtStartTag(parser); - Object object = objectClass.newInstance(); + Object object = objectClass.getConstructor().newInstance(); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/provider/ProviderFileLoader.java b/smack-core/src/main/java/org/jivesoftware/smack/provider/ProviderFileLoader.java index 2090401cc..bee798fb0 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/provider/ProviderFileLoader.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/provider/ProviderFileLoader.java @@ -83,7 +83,8 @@ public class ProviderFileLoader implements ProviderLoader { // reflection later to create instances of the class. // Add the provider to the map. if (IQProvider.class.isAssignableFrom(provider)) { - iqProviders.add(new IQProviderInfo(elementName, namespace, (IQProvider) provider.newInstance())); + IQProvider iqProvider = (IQProvider) provider.getConstructor().newInstance(); + iqProviders.add(new IQProviderInfo(elementName, namespace, iqProvider)); } else { exceptions.add(new IllegalArgumentException(className + " is not a IQProvider")); @@ -96,7 +97,9 @@ public class ProviderFileLoader implements ProviderLoader { // then we'll use reflection later to create instances // of the class. if (ExtensionElementProvider.class.isAssignableFrom(provider)) { - extProviders.add(new ExtensionProviderInfo(elementName, namespace, (ExtensionElementProvider) provider.newInstance())); + ExtensionElementProvider extensionElementProvider = (ExtensionElementProvider) provider.getConstructor().newInstance(); + extProviders.add(new ExtensionProviderInfo(elementName, namespace, + extensionElementProvider)); } else { exceptions.add(new IllegalArgumentException(className @@ -104,9 +107,10 @@ public class ProviderFileLoader implements ProviderLoader { } break; case "streamFeatureProvider": + ExtensionElementProvider streamFeatureProvider = (ExtensionElementProvider) provider.getConstructor().newInstance(); sfProviders.add(new StreamFeatureProviderInfo(elementName, namespace, - (ExtensionElementProvider) provider.newInstance())); + streamFeatureProvider)); break; default: LOGGER.warning("Unknown provider type: " + typeName); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks4ProxySocketConnection.java b/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks4ProxySocketConnection.java index 40ef48215..65a54059a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks4ProxySocketConnection.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks4ProxySocketConnection.java @@ -23,6 +23,8 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; +import org.jivesoftware.smack.util.StringUtils; + /** * Socket factory for socks4 proxy. * @@ -89,7 +91,8 @@ public class Socks4ProxySocketConnection implements ProxySocketConnection { if(user!=null) { - System.arraycopy(user.getBytes(), 0, buf, index, user.length()); + byte[] userBytes = user.getBytes(StringUtils.UTF8); + System.arraycopy(userBytes, 0, buf, index, user.length()); index+=user.length(); } buf[index++]=0; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks5ProxySocketConnection.java b/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks5ProxySocketConnection.java index d7b71802e..3e54f877c 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks5ProxySocketConnection.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/proxy/Socks5ProxySocketConnection.java @@ -22,6 +22,8 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; +import org.jivesoftware.smack.util.StringUtils; + /** * Socket factory for Socks5 proxy. * @@ -132,11 +134,13 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { index=0; buf[index++]=1; buf[index++]=(byte)(user.length()); - System.arraycopy(user.getBytes(), 0, buf, index, + byte[] userBytes = user.getBytes(StringUtils.UTF8); + System.arraycopy(userBytes, 0, buf, index, user.length()); index+=user.length(); - buf[index++]=(byte)(passwd.length()); - System.arraycopy(passwd.getBytes(), 0, buf, index, + byte[] passwordBytes = user.getBytes(StringUtils.UTF8); + buf[index++]=(byte)(passwordBytes.length); + System.arraycopy(passwordBytes, 0, buf, index, passwd.length()); index+=passwd.length(); @@ -210,7 +214,7 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { buf[index++]=1; // CONNECT buf[index++]=0; - byte[] hostb= host.getBytes(); + byte[] hostb= host.getBytes(StringUtils.UTF8); int len=hostb.length; buf[index++]=3; // DOMAINNAME buf[index++]=(byte)(len); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java b/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java index dce630b8c..c2cc66e3a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java @@ -265,8 +265,11 @@ public abstract class SASLMechanism implements Comparable { return null; } + @Override public final int compareTo(SASLMechanism other) { - return getPriority() - other.getPriority(); + // Switch to Integer.compare(int, int) once Smack is on Android 19 or higher. + Integer ourPriority = getPriority(); + return ourPriority.compareTo(other.getPriority()); } /** @@ -298,7 +301,7 @@ public abstract class SASLMechanism implements Comparable { } /** - * SASLprep the given String. + * SASLprep the given String. The resulting String is in UTF-8. * * @param string the String to sasl prep. * @return the given String SASL preped diff --git a/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/SASLAnonymous.java b/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/SASLAnonymous.java index 7f99b5ef8..509104d2b 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/SASLAnonymous.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/SASLAnonymous.java @@ -30,6 +30,7 @@ public class SASLAnonymous extends SASLMechanism { public static final String NAME = "ANONYMOUS"; + @Override public String getName() { return NAME; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/ScramMechanism.java b/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/ScramMechanism.java index a59b40815..08a1f6aab 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/ScramMechanism.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/sasl/core/ScramMechanism.java @@ -16,6 +16,7 @@ */ package org.jivesoftware.smack.sasl.core; +import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.SecureRandom; import java.util.Collections; @@ -105,7 +106,15 @@ public abstract class ScramMechanism extends SASLMechanism { @Override protected byte[] evaluateChallenge(byte[] challenge) throws SmackException { - final String challengeString = new String(challenge); + String challengeString; + try { + // TODO: Where is it specified that this is an UTF-8 encoded string? + challengeString = new String(challenge, StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + switch (state) { case AUTH_TEXT_SENT: final String serverFirstMessage = challengeString; @@ -358,14 +367,21 @@ public abstract class ScramMechanism extends SASLMechanism { * (PRF) and with dkLen == output length of HMAC() == output length of H(). *

* - * @param str + * @param normalizedPassword the normalized password. * @param salt * @param iterations * @return the result of the Hi function. * @throws SmackException */ - private byte[] hi(String str, byte[] salt, int iterations) throws SmackException { - byte[] key = str.getBytes(); + private byte[] hi(String normalizedPassword, byte[] salt, int iterations) throws SmackException { + byte[] key; + try { + // According to RFC 5802 § 2.2, the resulting string of the normalization is also in UTF-8. + key = normalizedPassword.getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(); + } // U1 := HMAC(str, salt + INT(1)) byte[] u = hmac(key, ByteUtils.concact(salt, ONE)); byte[] res = u.clone(); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/ArrayBlockingQueueWithShutdown.java b/smack-core/src/main/java/org/jivesoftware/smack/util/ArrayBlockingQueueWithShutdown.java index a24c06d49..742b34cf1 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/ArrayBlockingQueueWithShutdown.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/ArrayBlockingQueueWithShutdown.java @@ -240,6 +240,7 @@ public class ArrayBlockingQueueWithShutdown extends AbstractQueue implemen * @param e the element to add. * @throws InterruptedException if interrupted while waiting or if the queue was shut down. */ + @Override public void put(E e) throws InterruptedException { checkNotNull(e); lock.lockInterruptibly(); @@ -452,6 +453,7 @@ public class ArrayBlockingQueueWithShutdown extends AbstractQueue implemen } } + @Override public boolean hasNext() { return nextIndex >= 0; } @@ -469,6 +471,7 @@ public class ArrayBlockingQueueWithShutdown extends AbstractQueue implemen } } + @Override public E next() { lock.lock(); try { @@ -486,6 +489,7 @@ public class ArrayBlockingQueueWithShutdown extends AbstractQueue implemen } } + @Override public void remove() { lock.lock(); try { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java b/smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java index ebe709a06..60cfd8af3 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java @@ -185,7 +185,7 @@ public class DNSUtil { } List srvRecords = dnsResolver.lookupSRVRecords(srvDomain, failedAddresses, dnssecMode); - if (srvRecords != null) { + if (srvRecords != null && !srvRecords.isEmpty()) { if (LOGGER.isLoggable(Level.FINE)) { String logMessage = "Resolved SRV RR for " + srvDomain + ":"; for (SRVRecord r : srvRecords) @@ -194,6 +194,8 @@ public class DNSUtil { } List sortedRecords = sortSRVRecords(srvRecords); addresses.addAll(sortedRecords); + } else { + LOGGER.info("Could not resolve DNS SRV resource records for " + srvDomain + ". Consider adding those."); } int defaultPort = -1; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/FileUtils.java b/smack-core/src/main/java/org/jivesoftware/smack/util/FileUtils.java index 395fdf846..8fa5bb557 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/FileUtils.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/FileUtils.java @@ -87,7 +87,8 @@ public final class FileUtils { public static boolean addLines(String url, Set set) throws MalformedURLException, IOException { InputStream is = getStreamForUrl(url, null); if (is == null) return false; - BufferedReader br = new BufferedReader(new InputStreamReader(is)); + InputStreamReader sr = new InputStreamReader(is, StringUtils.UTF8); + BufferedReader br = new BufferedReader(sr); String line; while ((line = br.readLine()) != null) { set.add(line); @@ -102,6 +103,7 @@ public final class FileUtils { * @return the content of file or null in case of an error * @throws IOException */ + @SuppressWarnings("DefaultCharset") public static String readFileOrThrow(File file) throws FileNotFoundException, IOException { Reader reader = null; try { @@ -132,6 +134,7 @@ public final class FileUtils { return null; } + @SuppressWarnings("DefaultCharset") public static void writeFileOrThrow(File file, CharSequence content) throws IOException { FileWriter writer = new FileWriter(file, false); try { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableReader.java b/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableReader.java index 3cd27ff2f..43713261a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableReader.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableReader.java @@ -37,6 +37,7 @@ public class ObservableReader extends Reader { this.wrappedReader = wrappedReader; } + @Override public int read(char[] cbuf, int off, int len) throws IOException { int count = wrappedReader.read(cbuf, off, len); if (count > 0) { @@ -54,34 +55,42 @@ public class ObservableReader extends Reader { return count; } + @Override public void close() throws IOException { wrappedReader.close(); } + @Override public int read() throws IOException { return wrappedReader.read(); } + @Override public int read(char[] cbuf) throws IOException { return wrappedReader.read(cbuf); } + @Override public long skip(long n) throws IOException { return wrappedReader.skip(n); } + @Override public boolean ready() throws IOException { return wrappedReader.ready(); } + @Override public boolean markSupported() { return wrappedReader.markSupported(); } + @Override public void mark(int readAheadLimit) throws IOException { wrappedReader.mark(readAheadLimit); } + @Override public void reset() throws IOException { wrappedReader.reset(); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableWriter.java b/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableWriter.java index 8a7a754de..a92d00c28 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableWriter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/ObservableWriter.java @@ -38,36 +38,43 @@ public class ObservableWriter extends Writer { this.wrappedWriter = wrappedWriter; } + @Override public void write(char[] cbuf, int off, int len) throws IOException { wrappedWriter.write(cbuf, off, len); String str = new String(cbuf, off, len); maybeNotifyListeners(str); } + @Override public void flush() throws IOException { notifyListeners(); wrappedWriter.flush(); } + @Override public void close() throws IOException { wrappedWriter.close(); } + @Override public void write(int c) throws IOException { wrappedWriter.write(c); } + @Override public void write(char[] cbuf) throws IOException { wrappedWriter.write(cbuf); String str = new String(cbuf); maybeNotifyListeners(str); } + @Override public void write(String str) throws IOException { wrappedWriter.write(str); maybeNotifyListeners(str); } + @Override public void write(String str, int off, int len) throws IOException { wrappedWriter.write(str, off, len); str = str.substring(off, off + len); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java b/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java index f702052fd..4c9ce0699 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java @@ -290,8 +290,6 @@ public class PacketParserUtils { break outerloop; } break; - case XmlPullParser.TEXT: - throw new IllegalStateException("Invalid Stanza: Must not contain text or mixed content as direct child of "); } } @@ -592,8 +590,6 @@ public class PacketParserUtils { break outerloop; } break; - case XmlPullParser.TEXT: - throw new IllegalStateException("Invalid Stanza: Must not contain text or mixed content as direct child of "); } } return presence; @@ -650,8 +646,6 @@ public class PacketParserUtils { break outerloop; } break; - case XmlPullParser.TEXT: - throw new IllegalStateException("Invalid Stanza: Must not contain text or mixed content as direct child of "); } } // Decide what to do when an IQ packet was not understood diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/ParserUtils.java b/smack-core/src/main/java/org/jivesoftware/smack/util/ParserUtils.java index bd4c722fc..5a67c720e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/ParserUtils.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/ParserUtils.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2014 Florian Schmaus + * Copyright © 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import java.util.Locale; import org.jivesoftware.smack.SmackException; import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.EntityFullJid; +import org.jxmpp.jid.EntityJid; import org.jxmpp.jid.Jid; import org.jxmpp.jid.impl.JidCreate; import org.jxmpp.jid.parts.Resourcepart; @@ -98,6 +99,24 @@ public class ParserUtils { return JidCreate.entityFullFrom(jidString); } + public static EntityJid getEntityJidAttribute(XmlPullParser parser, String name) throws XmppStringprepException { + final String jidString = parser.getAttributeValue("", name); + if (jidString == null) { + return null; + } + Jid jid = JidCreate.from(jidString); + + if (!jid.hasLocalpart()) return null; + + EntityFullJid fullJid = jid.asEntityFullJidIfPossible(); + if (fullJid != null) { + return fullJid; + } + + EntityBareJid bareJid = jid.asEntityBareJidIfPossible(); + return bareJid; + } + public static Resourcepart getResourcepartAttribute(XmlPullParser parser, String name) throws XmppStringprepException { final String resourcepartString = parser.getAttributeValue("", name); if (resourcepartString == null) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/dns/DNSResolver.java b/smack-core/src/main/java/org/jivesoftware/smack/util/dns/DNSResolver.java index 79de3e08a..f5e4518f9 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/dns/DNSResolver.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/dns/DNSResolver.java @@ -20,6 +20,7 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; +import java.util.logging.Logger; import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode; @@ -29,6 +30,8 @@ import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode; */ public abstract class DNSResolver { + protected static final Logger LOGGER = Logger.getLogger(DNSResolver.class.getName()); + private final boolean supportsDnssec; protected DNSResolver(boolean supportsDnssec) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/stringencoder/Base32.java b/smack-core/src/main/java/org/jivesoftware/smack/util/stringencoder/Base32.java index 3a373671a..8e2f27f14 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/stringencoder/Base32.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/stringencoder/Base32.java @@ -20,6 +20,9 @@ package org.jivesoftware.smack.util.stringencoder; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import org.jivesoftware.smack.util.StringUtils; /** * Base32 string encoding is useful for when filenames case-insensitive filesystems are encoded. @@ -53,7 +56,13 @@ public class Base32 { public static String decode(String str) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); - byte[] raw = str.getBytes(); + byte[] raw; + try { + raw = str.getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } for (int i = 0; i < raw.length; i++) { char c = (char) raw[i]; if (!Character.isWhitespace(c)) { @@ -106,11 +115,24 @@ public class Base32 { } } - return new String(bs.toByteArray()); + String res; + try { + res = new String(bs.toByteArray(), StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + return res; } public static String encode(String str) { - byte[] b = str.getBytes(); + byte[] b; + try { + b = str.getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } ByteArrayOutputStream os = new ByteArrayOutputStream(); for (int i = 0; i < (b.length + 4) / 5; i++) { @@ -153,7 +175,14 @@ public class Base32 { os.write(c); } } - return new String(os.toByteArray()); + String res; + try { + res = new String(os.toByteArray(), StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + return res; } private static int lenToPadding(int blocklen) { diff --git a/smack-core/src/test/java/org/jivesoftware/smack/DummyConnection.java b/smack-core/src/test/java/org/jivesoftware/smack/DummyConnection.java index 1bd11e119..40f9b4e7a 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/DummyConnection.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/DummyConnection.java @@ -180,6 +180,7 @@ public class DummyConnection extends AbstractXMPPConnection { * * @param packet the stanza(/packet) to process. */ + @Override public void processStanza(Stanza packet) { invokeStanzaCollectorsAndNotifyRecvListeners(packet); } diff --git a/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java b/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java index be4f771f0..4120f4529 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java @@ -26,190 +26,190 @@ import org.junit.Test; public class StanzaCollectorTest { - @Test - public void verifyRollover() throws InterruptedException - { - TestStanzaCollector collector = new TestStanzaCollector(null, new OKEverything(), 5); + @Test + public void verifyRollover() throws InterruptedException + { + TestStanzaCollector collector = new TestStanzaCollector(null, new OKEverything(), 5); - for (int i=0; i<6; i++) - { - Stanza testPacket = new TestPacket(i); - collector.processStanza(testPacket); - } + for (int i=0; i<6; i++) + { + Stanza testPacket = new TestPacket(i); + collector.processStanza(testPacket); + } - // Assert that '0' has rolled off - assertEquals("1", collector.nextResultBlockForever().getStanzaId()); - assertEquals("2", collector.nextResultBlockForever().getStanzaId()); - assertEquals("3", collector.nextResultBlockForever().getStanzaId()); - assertEquals("4", collector.nextResultBlockForever().getStanzaId()); - assertEquals("5", collector.pollResult().getStanzaId()); - assertNull(collector.pollResult()); + // Assert that '0' has rolled off + assertEquals("1", collector.nextResultBlockForever().getStanzaId()); + assertEquals("2", collector.nextResultBlockForever().getStanzaId()); + assertEquals("3", collector.nextResultBlockForever().getStanzaId()); + assertEquals("4", collector.nextResultBlockForever().getStanzaId()); + assertEquals("5", collector.pollResult().getStanzaId()); + assertNull(collector.pollResult()); - for (int i=10; i<15; i++) - { - Stanza testPacket = new TestPacket(i); - collector.processStanza(testPacket); - } + for (int i=10; i<15; i++) + { + Stanza testPacket = new TestPacket(i); + collector.processStanza(testPacket); + } - assertEquals("10", collector.nextResultBlockForever().getStanzaId()); - assertEquals("11", collector.nextResultBlockForever().getStanzaId()); - assertEquals("12", collector.nextResultBlockForever().getStanzaId()); - assertEquals("13", collector.nextResultBlockForever().getStanzaId()); - assertEquals("14", collector.pollResult().getStanzaId()); - assertNull(collector.pollResult()); + assertEquals("10", collector.nextResultBlockForever().getStanzaId()); + assertEquals("11", collector.nextResultBlockForever().getStanzaId()); + assertEquals("12", collector.nextResultBlockForever().getStanzaId()); + assertEquals("13", collector.nextResultBlockForever().getStanzaId()); + assertEquals("14", collector.pollResult().getStanzaId()); + assertNull(collector.pollResult()); - assertNull(collector.nextResult(1000)); - } + assertNull(collector.nextResult(1000)); + } /** * Although this doesn't guarentee anything due to the nature of threading, it can potentially * catch problems. */ - @Test - public void verifyThreadSafety() - { - int insertCount = 500; - final TestStanzaCollector collector = new TestStanzaCollector(null, new OKEverything(), insertCount); + @Test + public void verifyThreadSafety() + { + int insertCount = 500; + final TestStanzaCollector collector = new TestStanzaCollector(null, new OKEverything(), insertCount); - Thread consumer1 = new Thread(new Runnable() - { - @Override - public void run() - { - try - { - while (true) - { - try - { - Thread.sleep(3); - } - catch (InterruptedException e) - { - } - @SuppressWarnings("unused") - Stanza packet = collector.nextResultBlockForever(); -// System.out.println(Thread.currentThread().getName() + " packet: " + packet); - } - } + Thread consumer1 = new Thread(new Runnable() + { + @Override + public void run() + { + try + { + while (true) + { + try + { + Thread.sleep(3); + } + catch (InterruptedException e) + { + } + @SuppressWarnings("unused") + Stanza packet = collector.nextResultBlockForever(); +// System.out.println(Thread.currentThread().getName() + " packet: " + packet); + } + } catch (InterruptedException e) { throw new RuntimeException(e); } - } - }); - consumer1.setName("consumer 1"); + } + }); + consumer1.setName("consumer 1"); - Thread consumer2 = new Thread(new Runnable() - { - @Override - public void run() - { - Stanza p = null; + Thread consumer2 = new Thread(new Runnable() + { + @Override + public void run() + { + Stanza p = null; - do - { - try - { - Thread.sleep(3); - } - catch (InterruptedException e) - { - } - try { + do + { + try + { + Thread.sleep(3); + } + catch (InterruptedException e) + { + } + try { p = collector.nextResult(1); } catch (InterruptedException e) { throw new RuntimeException(e); } -// System.out.println(Thread.currentThread().getName() + " packet: " + p); - } - while (p != null); - } - }); - consumer2.setName("consumer 2"); +// System.out.println(Thread.currentThread().getName() + " packet: " + p); + } + while (p != null); + } + }); + consumer2.setName("consumer 2"); - Thread consumer3 = new Thread(new Runnable() - { - @Override - public void run() - { - Stanza p = null; + Thread consumer3 = new Thread(new Runnable() + { + @Override + public void run() + { + Stanza p = null; - do - { - try - { - Thread.sleep(3); - } - catch (InterruptedException e) - { - } - p = collector.pollResult(); -// System.out.println(Thread.currentThread().getName() + " packet: " + p); - } - while (p != null); - } - }); - consumer3.setName("consumer 3"); + do + { + try + { + Thread.sleep(3); + } + catch (InterruptedException e) + { + } + p = collector.pollResult(); +// System.out.println(Thread.currentThread().getName() + " packet: " + p); + } + while (p != null); + } + }); + consumer3.setName("consumer 3"); - consumer1.start(); - consumer2.start(); - consumer3.start(); + consumer1.start(); + consumer2.start(); + consumer3.start(); - for(int i=0; i" + getStanzaId() + ""; - } + @Override + public String toXML() + { + return "" + getStanzaId() + ""; + } @Override public String toString() { return toXML(); } - } + } } diff --git a/smack-core/src/test/java/org/jivesoftware/smack/sasl/DigestMd5SaslTest.java b/smack-core/src/test/java/org/jivesoftware/smack/sasl/DigestMd5SaslTest.java index 5855aba7f..9e1862b11 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/sasl/DigestMd5SaslTest.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/sasl/DigestMd5SaslTest.java @@ -19,6 +19,7 @@ package org.jivesoftware.smack.sasl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; @@ -38,14 +39,14 @@ public class DigestMd5SaslTest extends AbstractSaslTest { super(saslMechanism); } - protected void runTest(boolean useAuthzid) throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException { + protected void runTest(boolean useAuthzid) throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException, UnsupportedEncodingException { EntityBareJid authzid = null; if (useAuthzid) { authzid = JidCreate.entityBareFrom("shazbat@xmpp.org"); } saslMechanism.authenticate("florian", "irrelevant", JidCreate.domainBareFrom("xmpp.org"), "secret", authzid, null); byte[] response = saslMechanism.evaluateChallenge(challengeBytes); - String responseString = new String(response); + String responseString = new String(response, StringUtils.UTF8); String[] responseParts = responseString.split(","); Map responsePairs = new HashMap(); for (String part : responseParts) { diff --git a/smack-core/src/test/java/org/jivesoftware/smack/util/PacketParserUtilsTest.java b/smack-core/src/test/java/org/jivesoftware/smack/util/PacketParserUtilsTest.java index e24196d15..b988a3e3a 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/util/PacketParserUtilsTest.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/util/PacketParserUtilsTest.java @@ -710,8 +710,8 @@ public class PacketParserUtilsTest { try { PacketParserUtils.parseMessage(PacketParserUtils.getParserFor(invalidControl)); fail("Exception should be thrown"); - } catch(IllegalStateException e) { - assertTrue(e.getMessage().contains("Invalid Stanza")); + } catch(XmlPullParserException e) { + assertTrue(e.getMessage().contains("end tag name ")); } invalidControl = validControl.replace("Good Message Body", "Bad Body"); @@ -851,6 +851,7 @@ public class PacketParserUtilsTest { XmlUnitUtils.assertSimilar(saslFailureString, saslFailure.toXML()); } + @SuppressWarnings("ReferenceEquality") private static String determineNonDefaultLanguage() { String otherLanguage = "jp"; Locale[] availableLocales = Locale.getAvailableLocales(); diff --git a/smack-core/src/test/java/org/jivesoftware/smack/util/SHA1Test.java b/smack-core/src/test/java/org/jivesoftware/smack/util/SHA1Test.java index b9fc3818d..ada3d4d99 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/util/SHA1Test.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/util/SHA1Test.java @@ -28,7 +28,7 @@ import org.junit.Test; */ public class SHA1Test { - @Test + @Test public void testHash() { // Test null // @TODO - should the StringUtils.hash(String) method be fixed to handle null input? diff --git a/smack-core/src/test/java/org/jivesoftware/smack/util/StringUtilsTest.java b/smack-core/src/test/java/org/jivesoftware/smack/util/StringUtilsTest.java index bd0d5ad05..0cff5a730 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/util/StringUtilsTest.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/util/StringUtilsTest.java @@ -21,13 +21,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.io.UnsupportedEncodingException; + import org.junit.Test; /** * A test case for the StringUtils class. */ public class StringUtilsTest { - @Test + @Test public void testEscapeForXml() { String input = null; @@ -67,24 +69,24 @@ public class StringUtilsTest { assertCharSequenceEquals("It's a good day today", StringUtils.escapeForXml(input)); } - public static void assertCharSequenceEquals(CharSequence expected, CharSequence actual) { + public static void assertCharSequenceEquals(CharSequence expected, CharSequence actual) { assertEquals(expected.toString(), actual.toString()); - } + } - @Test - public void testEncodeHex() { + @Test + public void testEncodeHex() throws UnsupportedEncodingException { String input = ""; String output = ""; - assertEquals(new String(StringUtils.encodeHex(input.getBytes())), - new String(output.getBytes())); + assertEquals(new String(StringUtils.encodeHex(input.getBytes(StringUtils.UTF8))), + output); input = "foo bar 123"; output = "666f6f2062617220313233"; - assertEquals(new String(StringUtils.encodeHex(input.getBytes())), - new String(output.getBytes())); + assertEquals(new String(StringUtils.encodeHex(input.getBytes(StringUtils.UTF8))), + output); } - @Test + @Test public void testRandomString() { // Boundary test String result = StringUtils.randomString(-1); diff --git a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingConnectionListener.java b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingConnectionListener.java index ec25f3639..a0161f3e6 100644 --- a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingConnectionListener.java +++ b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingConnectionListener.java @@ -40,22 +40,27 @@ class SLF4JLoggingConnectionListener implements ConnectionListener { logger.debug("({}) Connection authenticated as {}", connection.hashCode(), connection.getUser()); } + @Override public void connectionClosed() { logger.debug("({}) Connection closed", connection.hashCode()); } + @Override public void connectionClosedOnError(Exception e) { logger.debug("({}) Connection closed due to an exception: {}", connection.hashCode(), e); } + @Override public void reconnectionFailed(Exception e) { logger.debug("({}) Reconnection failed due to an exception: {}", connection.hashCode(), e); } + @Override public void reconnectionSuccessful() { logger.debug("({}) Connection reconnected", connection.hashCode()); } + @Override public void reconnectingIn(int seconds) { logger.debug("({}) Connection will reconnect in {}", connection.hashCode(), seconds); } diff --git a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingPacketListener.java b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingPacketListener.java index 4021e3d66..2b651dfc5 100644 --- a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingPacketListener.java +++ b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JLoggingPacketListener.java @@ -31,6 +31,7 @@ class SLF4JLoggingPacketListener implements StanzaListener { this.prefix = Validate.notNull(prefix); } + @Override public void processStanza(Stanza packet) { if (SLF4JSmackDebugger.printInterpreted.get() && logger.isDebugEnabled()) { logger.debug("{}: PKT [{}] '{}'", prefix, packet.getClass().getName(), packet.toXML()); diff --git a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JRawXmlListener.java b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JRawXmlListener.java index c44bbcd2f..c013a18b6 100644 --- a/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JRawXmlListener.java +++ b/smack-debug-slf4j/src/main/java/org/jivesoftware/smackx/debugger/slf4j/SLF4JRawXmlListener.java @@ -28,10 +28,12 @@ class SLF4JRawXmlListener implements ReaderListener, WriterListener { this.logger = Validate.notNull(logger); } + @Override public void read(String str) { logger.debug("{}: {}", SLF4JSmackDebugger.RECEIVED_TAG, str); } + @Override public void write(String str) { logger.debug("{}: {}", SLF4JSmackDebugger.SENT_TAG, str); } diff --git a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java index d4f744dd7..9802bd4c3 100644 --- a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java +++ b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java @@ -208,8 +208,10 @@ public class EnhancedDebugger implements SmackDebugger { packetReaderListener = new StanzaListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss:SS"); + @Override public void processStanza(final Stanza packet) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { addReadPacketToTable(dateFormatter, packet); } @@ -223,8 +225,10 @@ public class EnhancedDebugger implements SmackDebugger { packetWriterListener = new StanzaListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss:SS"); + @Override public void processStanza(final Stanza packet) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { addSentPacketToTable(dateFormatter, packet); } @@ -235,8 +239,10 @@ public class EnhancedDebugger implements SmackDebugger { // Create a thread that will listen for any connection closed event connListener = new AbstractConnectionListener() { + @Override public void connectionClosed() { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { statusField.setValue("Closed"); EnhancedDebuggerWindow.connectionClosed(EnhancedDebugger.this); @@ -245,8 +251,10 @@ public class EnhancedDebugger implements SmackDebugger { } + @Override public void connectionClosedOnError(final Exception e) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { statusField.setValue("Closed due to an exception"); EnhancedDebuggerWindow.connectionClosedOnError(EnhancedDebugger.this, e); @@ -254,16 +262,20 @@ public class EnhancedDebugger implements SmackDebugger { }); } + @Override public void reconnectingIn(final int seconds){ SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { statusField.setValue("Attempt to reconnect in " + seconds + " seconds"); } }); } + @Override public void reconnectionSuccessful() { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { statusField.setValue("Reconnection stablished"); EnhancedDebuggerWindow.connectionEstablished(EnhancedDebugger.this); @@ -271,8 +283,10 @@ public class EnhancedDebugger implements SmackDebugger { }); } + @Override public void reconnectionFailed(Exception e) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { statusField.setValue("Reconnection failed"); } @@ -291,11 +305,13 @@ public class EnhancedDebugger implements SmackDebugger { 0) { // CHECKSTYLE:OFF private static final long serialVersionUID = 8136121224474217264L; - public boolean isCellEditable(int rowIndex, int mColIndex) { + @Override + public boolean isCellEditable(int rowIndex, int mColIndex) { // CHECKSTYLE:ON return false; } + @Override public Class getColumnClass(int columnIndex) { if (columnIndex == 2 || columnIndex == 3) { return Icon.class; @@ -344,6 +360,7 @@ public class EnhancedDebugger implements SmackDebugger { JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -391,6 +408,7 @@ public class EnhancedDebugger implements SmackDebugger { menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -401,6 +419,7 @@ public class EnhancedDebugger implements SmackDebugger { JMenuItem menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { sentText.setText(""); } @@ -426,6 +445,7 @@ public class EnhancedDebugger implements SmackDebugger { menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -436,6 +456,7 @@ public class EnhancedDebugger implements SmackDebugger { menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { receivedText.setText(""); } @@ -449,8 +470,10 @@ public class EnhancedDebugger implements SmackDebugger { // Create a special Reader that wraps the main Reader and logs data to the GUI. ObservableReader debugReader = new ObservableReader(reader); readerListener = new ReaderListener() { + @Override public void read(final String str) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { if (EnhancedDebuggerWindow.PERSISTED_DEBUGGER && !EnhancedDebuggerWindow.getInstance().isVisible()) { @@ -487,8 +510,10 @@ public class EnhancedDebugger implements SmackDebugger { // Create a special Writer that wraps the main Writer and logs data to the GUI. ObservableWriter debugWriter = new ObservableWriter(writer); writerListener = new WriterListener() { + @Override public void write(final String str) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { if (EnhancedDebuggerWindow.PERSISTED_DEBUGGER && !EnhancedDebuggerWindow.getInstance().isVisible()) { @@ -536,6 +561,7 @@ public class EnhancedDebugger implements SmackDebugger { JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Message"); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { adhocMessages.setText( ""); @@ -579,6 +608,7 @@ public class EnhancedDebugger implements SmackDebugger { menuItem = new JMenuItem("Send"); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if (!"".equals(adhocMessages.getText())) { AdHocPacket packetToSend = new AdHocPacket(adhocMessages.getText()); @@ -595,6 +625,7 @@ public class EnhancedDebugger implements SmackDebugger { menuItem = new JMenuItem("Clear"); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { adhocMessages.setText(null); } @@ -709,7 +740,8 @@ public class EnhancedDebugger implements SmackDebugger { new Object[]{"Type", "Received", "Sent"}) { // CHECKSTYLE:OFF private static final long serialVersionUID = -6793886085109589269L; - public boolean isCellEditable(int rowIndex, int mColIndex) { + @Override + public boolean isCellEditable(int rowIndex, int mColIndex) { // CHECKSTYLE:ON return false; } @@ -726,6 +758,7 @@ public class EnhancedDebugger implements SmackDebugger { tabbedPane.setToolTipTextAt(4, "Information and statistics about the debugged connection"); } + @Override public Reader newConnectionReader(Reader newReader) { ((ObservableReader) reader).removeReaderListener(readerListener); ObservableReader debugReader = new ObservableReader(newReader); @@ -734,6 +767,7 @@ public class EnhancedDebugger implements SmackDebugger { return reader; } + @Override public Writer newConnectionWriter(Writer newWriter) { ((ObservableWriter) writer).removeWriterListener(writerListener); ObservableWriter debugWriter = new ObservableWriter(newWriter); @@ -746,6 +780,7 @@ public class EnhancedDebugger implements SmackDebugger { public void userHasLogged(final EntityFullJid user) { final EnhancedDebugger debugger = this; SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { userField.setText(user.toString()); EnhancedDebuggerWindow.userHasLogged(debugger, user.toString()); @@ -757,18 +792,22 @@ public class EnhancedDebugger implements SmackDebugger { } + @Override public Reader getReader() { return reader; } + @Override public Writer getWriter() { return writer; } + @Override public StanzaListener getReaderListener() { return packetReaderListener; } + @Override public StanzaListener getWriterListener() { return packetWriterListener; } @@ -801,6 +840,7 @@ public class EnhancedDebugger implements SmackDebugger { */ private void addReadPacketToTable(final SimpleDateFormat dateFormatter, final Stanza packet) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { String messageType; Jid from = packet.getFrom(); @@ -862,6 +902,7 @@ public class EnhancedDebugger implements SmackDebugger { */ private void addSentPacketToTable(final SimpleDateFormat dateFormatter, final Stanza packet) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { String messageType; Jid to = packet.getTo(); @@ -978,9 +1019,9 @@ public class EnhancedDebugger implements SmackDebugger { * The whole text to send must be passed to the constructor. This implies that the client of * this class is responsible for sending a valid text to the constructor. */ - private class AdHocPacket extends Stanza { + private static class AdHocPacket extends Stanza { - private String text; + private final String text; /** * Create a new AdHocPacket with the text to send. The passed text must be a valid text to @@ -992,6 +1033,7 @@ public class EnhancedDebugger implements SmackDebugger { this.text = text; } + @Override public String toXML() { return text; } @@ -1006,7 +1048,7 @@ public class EnhancedDebugger implements SmackDebugger { /** * Listens for debug window popup dialog events. */ - private class PopupListener extends MouseAdapter { + private static class PopupListener extends MouseAdapter { JPopupMenu popup; @@ -1014,10 +1056,12 @@ public class EnhancedDebugger implements SmackDebugger { popup = popupMenu; } + @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } + @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } @@ -1039,6 +1083,7 @@ public class EnhancedDebugger implements SmackDebugger { this.table = table; } + @Override public void valueChanged(ListSelectionEvent e) { if (table.getSelectedRow() == -1) { // Clear the messageTextArea since there is none packet selected diff --git a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java index d5ec26ec8..f246d1f51 100644 --- a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java +++ b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java @@ -203,13 +203,14 @@ public final class EnhancedDebuggerWindow { * a tab panel for each connection that is being debugged. */ @SuppressWarnings({ "rawtypes", "unchecked" }) - private void createDebug() { + private void createDebug() { frame = new JFrame("Smack Debug Window"); if (!PERSISTED_DEBUGGER) { // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent evt) { rootWindowClosing(evt); } @@ -280,6 +281,7 @@ public final class EnhancedDebuggerWindow { // Add a menu item that allows to close the current selected tab JMenuItem menuItem = new JMenuItem("Close"); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Remove the selected tab pane if it's not the Smack info pane if (tabbedPane.getSelectedIndex() < tabbedPane.getComponentCount() - 1) { @@ -301,6 +303,7 @@ public final class EnhancedDebuggerWindow { // Add a menu item that allows to close all the tabs that have their connections closed menuItem = new JMenuItem("Close All Not Active"); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { ArrayList debuggersToRemove = new ArrayList(); // Remove all the debuggers of which their connections are no longer valid @@ -348,7 +351,7 @@ public final class EnhancedDebuggerWindow { debugger.cancel(); } // Release any reference to the debuggers - debuggers.removeAll(debuggers); + debuggers.clear(); // Release the default instance instance = null; } @@ -356,7 +359,7 @@ public final class EnhancedDebuggerWindow { /** * Listens for debug window popup dialog events. */ - private class PopupListener extends MouseAdapter { + private static class PopupListener extends MouseAdapter { JPopupMenu popup; @@ -364,10 +367,12 @@ public final class EnhancedDebuggerWindow { popup = popupMenu; } + @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } + @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } diff --git a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/LiteDebugger.java b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/LiteDebugger.java index e8571b2e1..ea0fed8b9 100644 --- a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/LiteDebugger.java +++ b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/LiteDebugger.java @@ -86,6 +86,7 @@ public class LiteDebugger implements SmackDebugger { // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent evt) { rootWindowClosing(evt); } @@ -114,6 +115,7 @@ public class LiteDebugger implements SmackDebugger { JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -124,6 +126,7 @@ public class LiteDebugger implements SmackDebugger { JMenuItem menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { sentText1.setText(""); sentText2.setText(""); @@ -151,6 +154,7 @@ public class LiteDebugger implements SmackDebugger { menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -161,6 +165,7 @@ public class LiteDebugger implements SmackDebugger { menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { receivedText1.setText(""); receivedText2.setText(""); @@ -188,6 +193,7 @@ public class LiteDebugger implements SmackDebugger { menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); @@ -198,6 +204,7 @@ public class LiteDebugger implements SmackDebugger { menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { interpretedText1.setText(""); interpretedText2.setText(""); @@ -219,6 +226,7 @@ public class LiteDebugger implements SmackDebugger { // Create a special Reader that wraps the main Reader and logs data to the GUI. ObservableReader debugReader = new ObservableReader(reader); readerListener = new ReaderListener() { + @Override public void read(String str) { int index = str.lastIndexOf(">"); if (index != -1) { @@ -242,6 +250,7 @@ public class LiteDebugger implements SmackDebugger { // Create a special Writer that wraps the main Writer and logs data to the GUI. ObservableWriter debugWriter = new ObservableWriter(writer); writerListener = new WriterListener() { + @Override public void write(String str) { sentText1.append(str); sentText2.append(str); @@ -262,6 +271,7 @@ public class LiteDebugger implements SmackDebugger { // the GUI. This is what we call "interpreted" packet data, since it's the packet // data as Smack sees it and not as it's coming in as raw XML. listener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { interpretedText1.append(packet.toXML().toString()); interpretedText2.append(packet.toXML().toString()); @@ -286,17 +296,19 @@ public class LiteDebugger implements SmackDebugger { /** * Listens for debug window popup dialog events. */ - private class PopupListener extends MouseAdapter { + private static class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } + @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } + @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } @@ -308,6 +320,7 @@ public class LiteDebugger implements SmackDebugger { } } + @Override public Reader newConnectionReader(Reader newReader) { ((ObservableReader)reader).removeReaderListener(readerListener); ObservableReader debugReader = new ObservableReader(newReader); @@ -316,6 +329,7 @@ public class LiteDebugger implements SmackDebugger { return reader; } + @Override public Writer newConnectionWriter(Writer newWriter) { ((ObservableWriter)writer).removeWriterListener(writerListener); ObservableWriter debugWriter = new ObservableWriter(newWriter); @@ -332,18 +346,22 @@ public class LiteDebugger implements SmackDebugger { frame.setTitle(title); } + @Override public Reader getReader() { return reader; } + @Override public Writer getWriter() { return writer; } + @Override public StanzaListener getReaderListener() { return listener; } + @Override public StanzaListener getWriterListener() { return null; } diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonCopyReceivedListener.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonCopyReceivedListener.java new file mode 100644 index 000000000..25a82be4b --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonCopyReceivedListener.java @@ -0,0 +1,33 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.carbons; + +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smackx.carbons.packet.CarbonExtension.Direction; + +public interface CarbonCopyReceivedListener { + + /** + * Invoked when a new carbon copy was received. + * + * @param direction the direction of the carbon copy. + * @param carbonCopy the carbon copy itself. + * @param wrappingMessage the message wrapping the carbon copy. + */ + void onCarbonCopyReceived(Direction direction, Message carbonCopy, Message wrappingMessage); + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java index b3aad0277..d023b0ce6 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2013-2014 Georg Lukas + * Copyright 2013-2014 Georg Lukas, 2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,37 +17,54 @@ package org.jivesoftware.smackx.carbons; import java.util.Map; +import java.util.Set; import java.util.WeakHashMap; +import java.util.concurrent.CopyOnWriteArraySet; -import org.jivesoftware.smack.ExceptionCallback; import org.jivesoftware.smack.AbstractConnectionListener; +import org.jivesoftware.smack.ConnectionCreationListener; +import org.jivesoftware.smack.ExceptionCallback; +import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NotConnectedException; -import org.jivesoftware.smack.XMPPConnection; -import org.jivesoftware.smack.ConnectionCreationListener; -import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.StanzaListener; +import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnectionRegistry; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.filter.AndFilter; +import org.jivesoftware.smack.filter.FromMatchesFilter; +import org.jivesoftware.smack.filter.OrFilter; +import org.jivesoftware.smack.filter.StanzaExtensionFilter; +import org.jivesoftware.smack.filter.StanzaFilter; +import org.jivesoftware.smack.filter.StanzaTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Stanza; -import org.jivesoftware.smackx.carbons.packet.CarbonExtension; import org.jivesoftware.smackx.carbons.packet.Carbon; +import org.jivesoftware.smackx.carbons.packet.CarbonExtension; +import org.jivesoftware.smackx.carbons.packet.CarbonExtension.Direction; import org.jivesoftware.smackx.carbons.packet.CarbonExtension.Private; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; +import org.jivesoftware.smackx.forward.packet.Forwarded; +import org.jxmpp.jid.EntityFullJid; /** - * Stanza(/Packet) extension for XEP-0280: Message Carbons. This class implements - * the manager for registering {@link CarbonExtension} support, enabling and disabling - * message carbons. - * - * You should call enableCarbons() before sending your first undirected - * presence. + * Manager for XEP-0280: Message Carbons. This class implements the manager for registering {@link CarbonExtension} + * support, enabling and disabling message carbons, and for {@link CarbonCopyReceivedListener}. + *

+ * Note that it is important to match the 'from' attribute of the message wrapping a carbon copy, as otherwise it would + * may be possible for others to impersonate users. Smack's CarbonManager takes care of that in + * {@link CarbonCopyReceivedListener}s which where registered with + * {@link #addCarbonCopyReceivedListener(CarbonCopyReceivedListener)}. + *

+ *

+ * You should call enableCarbons() before sending your first undirected presence (aka. the "initial presence"). + *

* * @author Georg Lukas + * @author Florian Schmaus */ public final class CarbonManager extends Manager { @@ -55,18 +72,49 @@ public final class CarbonManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } }); } + private static final StanzaFilter CARBON_EXTENSION_FILTER = + // @formatter:off + new AndFilter( + new OrFilter( + new StanzaExtensionFilter(CarbonExtension.Direction.sent.name(), CarbonExtension.NAMESPACE), + new StanzaExtensionFilter(CarbonExtension.Direction.received.name(), CarbonExtension.NAMESPACE) + ), + StanzaTypeFilter.MESSAGE + ); + // @formatter:on + + private final Set listeners = new CopyOnWriteArraySet<>(); + private volatile boolean enabled_state = false; + private final StanzaListener carbonsListener; + private CarbonManager(XMPPConnection connection) { super(connection); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); sdm.addFeature(CarbonExtension.NAMESPACE); + + carbonsListener = new StanzaListener() { + @Override + public void processStanza(final Stanza stanza) throws NotConnectedException, InterruptedException { + final Message wrappingMessage = (Message) stanza; + final CarbonExtension carbonExtension = CarbonExtension.from(wrappingMessage); + final Direction direction = carbonExtension.getDirection(); + final Forwarded forwarded = carbonExtension.getForwarded(); + final Message carbonCopy = (Message) forwarded.getForwardedStanza(); + for (CarbonCopyReceivedListener listener : listeners) { + listener.onCarbonCopyReceived(direction, carbonCopy, wrappingMessage); + } + } + }; + connection.addConnectionListener(new AbstractConnectionListener() { @Override public void connectionClosed() { @@ -74,6 +122,8 @@ public final class CarbonManager extends Manager { // because we also reset in authenticated() if the stream got not resumed, but for maximum correctness, // also reset here. enabled_state = false; + boolean removed = connection().removeSyncStanzaListener(carbonsListener); + assert(removed); } @Override public void authenticated(XMPPConnection connection, boolean resumed) { @@ -81,8 +131,27 @@ public final class CarbonManager extends Manager { // Non-resumed XMPP sessions always start with disabled carbons enabled_state = false; } + addCarbonsListener(connection); } }); + + addCarbonsListener(connection); + } + + private void addCarbonsListener(XMPPConnection connection) { + EntityFullJid localAddress = connection.getUser(); + if (localAddress == null) { + // We where not connected yet and thus we don't know our XMPP address at the moment, which we need to match incoming + // carbons securely. Abort here. The ConnectionListener above will eventually setup the carbons listener. + return; + } + + // XEP-0280 § 11. Security Considerations "Any forwarded copies received by a Carbons-enabled client MUST be + // from that user's bare JID; any copies that do not meet this requirement MUST be ignored." Otherwise, if + // those copies do not get ignored, malicious users may be able to impersonate other users. That is why the + // 'from' matcher is important here. + connection.addSyncStanzaListener(carbonsListener, new AndFilter(CARBON_EXTENSION_FILTER, + FromMatchesFilter.createBare(localAddress))); } /** @@ -113,6 +182,28 @@ public final class CarbonManager extends Manager { return request; } + /** + * Add a carbon copy received listener. + * + * @param listener the listener to register. + * @return true if the filter was not already registered. + * @since 4.2 + */ + public boolean addCarbonCopyReceivedListener(CarbonCopyReceivedListener listener) { + return listeners.add(listener); + } + + /** + * Remove a carbon copy received listener. + * + * @param listener the listener to register. + * @return true if the filter was registered. + * @since 4.2 + */ + public boolean removeCarbonCopyReceivedListener(CarbonCopyReceivedListener listener) { + return listeners.remove(listener); + } + /** * Returns true if XMPP Carbons are supported by the server. * @@ -181,6 +272,7 @@ public final class CarbonManager extends Manager { try { connection().sendIqWithResponseCallback(setIQ, new StanzaListener() { + @Override public void processStanza(Stanza packet) { enabled_state = use; } diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hoxt/packet/AbstractHttpOverXmpp.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hoxt/packet/AbstractHttpOverXmpp.java index a7ac49d8c..c4eccfdf9 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/hoxt/packet/AbstractHttpOverXmpp.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hoxt/packet/AbstractHttpOverXmpp.java @@ -44,6 +44,7 @@ public abstract class AbstractHttpOverXmpp extends IQ { this.version = Objects.requireNonNull(builder.version, "version must not be null"); } + @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { IQChildElementXmlStringBuilder builder = getIQHoxtChildElementBuilder(xml); builder.optAppend(headers); diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/IoTSetRequest.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/IoTSetRequest.java index b77787f98..052cb07c1 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/IoTSetRequest.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/IoTSetRequest.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2016 Florian Schmaus + * Copyright © 2016-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package org.jivesoftware.smackx.iot.control.element; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -31,7 +32,21 @@ public class IoTSetRequest extends IQ { public IoTSetRequest(Collection setData) { super(ELEMENT, NAMESPACE); setType(Type.set); - this.setData = Collections.unmodifiableCollection(setData); + + /* + * Ugly workaround for the following error prone false positive: + * + * IoTSetRequest.java:34: error: incompatible types: Collection cannot be converted to Collection + * this.setData = Collections.unmodifiableCollection(setDataA); + * ^ + * where CAP#1 is a fresh type-variable: + * CAP#1 extends SetData from capture of ? extends SetData + */ + Collection tmp = new ArrayList<>(setData.size()); + for (SetData data : setData) { + tmp.add(data); + } + this.setData = Collections.unmodifiableCollection(tmp); } public Collection getSetData() { diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/SetData.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/SetData.java index 1e7505a83..4d9e29286 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/SetData.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/control/element/SetData.java @@ -30,7 +30,7 @@ public abstract class SetData implements NamedElement { DOUBLE, ; - private String toStringCache; + private final String toStringCache; private Type() { toStringCache = this.name().toLowerCase(Locale.US); diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/data/IoTDataManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/data/IoTDataManager.java index 6e4b6f63d..78268a159 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/data/IoTDataManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/data/IoTDataManager.java @@ -61,6 +61,7 @@ public final class IoTDataManager extends IoTManager { // Ensure a IoTDataManager exists for every connection. static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { if (!isAutoEnableActive()) return; getInstanceFor(connection); diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java index 2fa512911..e81a41818 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java @@ -74,6 +74,7 @@ public final class IoTDiscoveryManager extends Manager { // Ensure a IoTProvisioningManager exists for every connection. static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { if (!IoTManager.isAutoEnableActive()) return; getInstanceFor(connection); diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/element/NodeInfo.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/element/NodeInfo.java index 08ce2db11..85412a126 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/element/NodeInfo.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/element/NodeInfo.java @@ -62,6 +62,7 @@ public final class NodeInfo { } @Override + @SuppressWarnings("ReferenceEquality") public int hashCode() { if (this == EMPTY) { return 0; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/IoTProvisioningManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/IoTProvisioningManager.java index 3fc6c6741..42a53e6c0 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/IoTProvisioningManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/IoTProvisioningManager.java @@ -82,6 +82,7 @@ public final class IoTProvisioningManager extends Manager { // Ensure a IoTProvisioningManager exists for every connection. static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { if (!IoTManager.isAutoEnableActive()) return; getInstanceFor(connection); diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java index e14f9df11..93796738a 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java @@ -267,7 +267,7 @@ public class MultiUserChatLight { try { connection.createStanzaCollectorAndSend(createMUCLightIQ).nextResultOrThrow(); - } catch (InterruptedException | NoResponseException | XMPPErrorException e) { + } catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) { removeConnectionCallbacks(); throw e; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smack/chat2/ChatManager.java b/smack-extensions/src/main/java/org/jivesoftware/smack/chat2/ChatManager.java index b19dd290f..9e8ab2410 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smack/chat2/ChatManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smack/chat2/ChatManager.java @@ -53,6 +53,7 @@ import org.jxmpp.jid.Jid; * * @see XEP-0296: Best Practices for Resource Locking */ +@SuppressWarnings("FunctionalInterfaceClash") public final class ChatManager extends Manager { private static final Map INSTANCES = new WeakHashMap<>(); @@ -69,7 +70,7 @@ public final class ChatManager extends Manager { // @FORMATTER:OFF private static final StanzaFilter MESSAGE_FILTER = new AndFilter( MessageTypeFilter.NORMAL_OR_CHAT, - new OrFilter(MessageWithBodiesFilter.INSTANCE), new StanzaExtensionFilter(XHTMLExtension.ELEMENT, XHTMLExtension.NAMESPACE) + new OrFilter(MessageWithBodiesFilter.INSTANCE, new StanzaExtensionFilter(XHTMLExtension.ELEMENT, XHTMLExtension.NAMESPACE)) ); private static final StanzaFilter OUTGOING_MESSAGE_FILTER = new AndFilter( @@ -188,22 +189,84 @@ public final class ChatManager extends Manager { return true; } - public boolean addListener(IncomingChatMessageListener listener) { + /** + * Add a new listener for incoming chat messages. + * + * @param listener the listener to add. + * @return true if the listener was not already added. + */ + public boolean addIncomingListener(IncomingChatMessageListener listener) { return incomingListeners.add(listener); } + /** + * Add a new listener for incoming chat messages. + * + * @param listener the listener to add. + * @return true if the listener was not already added. + */ + @Deprecated + @SuppressWarnings("FunctionalInterfaceClash") + public boolean addListener(IncomingChatMessageListener listener) { + return addIncomingListener(listener); + } + + /** + * Remove an incoming chat message listener. + * + * @param listener the listener to remove. + * @return true if the listener was active and got removed. + */ + @SuppressWarnings("FunctionalInterfaceClash") public boolean removeListener(IncomingChatMessageListener listener) { return incomingListeners.remove(listener); } - public boolean addListener(OutgoingChatMessageListener listener) { + /** + * Add a new listener for outgoing chat messages. + * + * @param listener the listener to add. + * @return true if the listener was not already added. + */ + public boolean addOutgoingListener(OutgoingChatMessageListener listener) { return outgoingListeners.add(listener); } - public boolean removeOutoingLIstener(OutgoingChatMessageListener listener) { + /** + * Add a new listener for incoming chat messages. + * + * @param listener the listener to add. + * @return true if the listener was not already added. + * @deprecated use {@link #addOutgoingListener(OutgoingChatMessageListener)} instead. + */ + @Deprecated + @SuppressWarnings("FunctionalInterfaceClash") + public boolean addListener(OutgoingChatMessageListener listener) { + return addOutgoingListener(listener); + } + + /** + * Remove an outgoing chat message listener. + * + * @param listener the listener to remove. + * @return true if the listener was active and got removed. + */ + public boolean removeListener(OutgoingChatMessageListener listener) { return outgoingListeners.remove(listener); } + /** + * Remove an outgoing chat message listener. + * + * @param listener the listener to remove. + * @return true if the listener was active and got removed. + * @deprecated use {@link #removeListener(OutgoingChatMessageListener)} instead. + */ + @Deprecated + public boolean removeOutoingLIstener(OutgoingChatMessageListener listener) { + return removeListener(listener); + } + /** * Start a new or retrieve the existing chat with jid. * diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java index 20d8c887d..8800268c8 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java @@ -40,6 +40,7 @@ public class AMPManager { // The ServiceDiscoveryManager class should have been already initialized static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { AMPManager.setServiceEnabled(connection, true); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/attention/packet/AttentionExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/attention/packet/AttentionExtension.java index 8fe39bdc7..18869392a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/attention/packet/AttentionExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/attention/packet/AttentionExtension.java @@ -47,6 +47,7 @@ public class AttentionExtension implements ExtensionElement { * * @see org.jivesoftware.smack.packet.PacketExtension#getElementName() */ + @Override public String getElementName() { return ELEMENT_NAME; } @@ -56,6 +57,7 @@ public class AttentionExtension implements ExtensionElement { * * @see org.jivesoftware.smack.packet.PacketExtension#getNamespace() */ + @Override public String getNamespace() { return NAMESPACE; } @@ -65,6 +67,7 @@ public class AttentionExtension implements ExtensionElement { * * @see org.jivesoftware.smack.packet.PacketExtension#toXML() */ + @Override public String toXML() { final StringBuilder sb = new StringBuilder(); sb.append('<').append(getElementName()).append(" xmlns=\"").append( diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/AllJidsUnblockedListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/AllJidsUnblockedListener.java new file mode 100644 index 000000000..27b1f477c --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/AllJidsUnblockedListener.java @@ -0,0 +1,23 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.blocking; + +public interface AllJidsUnblockedListener { + + void onAllJidsUnblocked(); + +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/BlockingCommandManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/BlockingCommandManager.java index 78b27c7f7..c67b82692 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/BlockingCommandManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/BlockingCommandManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016 Fernando Ramirez, Florian Schmaus + * Copyright 2016-2017 Fernando Ramirez, Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.WeakHashMap; +import java.util.concurrent.CopyOnWriteArraySet; import org.jivesoftware.smack.AbstractConnectionListener; import org.jivesoftware.smack.ConnectionCreationListener; @@ -82,6 +84,12 @@ public final class BlockingCommandManager extends Manager { return blockingCommandManager; } + private final Set allJidsUnblockedListeners = new CopyOnWriteArraySet<>(); + + private final Set jidsBlockedListeners = new CopyOnWriteArraySet<>(); + + private final Set jidsUnblockedListeners = new CopyOnWriteArraySet<>(); + private BlockingCommandManager(XMPPConnection connection) { super(connection); @@ -99,6 +107,10 @@ public final class BlockingCommandManager extends Manager { List blockedJids = blockContactIQ.getJids(); blockListCached.addAll(blockedJids); + for (JidsBlockedListener listener : jidsBlockedListeners) { + listener.onJidsBlocked(blockedJids); + } + return IQ.createResultIQ(blockContactIQ); } }); @@ -117,8 +129,14 @@ public final class BlockingCommandManager extends Manager { List unblockedJids = unblockContactIQ.getJids(); if (unblockedJids == null) { // remove all blockListCached.clear(); + for (AllJidsUnblockedListener listener : allJidsUnblockedListeners) { + listener.onAllJidsUnblocked(); + } } else { // remove only some blockListCached.removeAll(unblockedJids); + for (JidsUnblockedListener listener : jidsUnblockedListeners) { + listener.onJidsUnblocked(unblockedJids); + } } return IQ.createResultIQ(unblockContactIQ); @@ -216,4 +234,27 @@ public final class BlockingCommandManager extends Manager { connection().createStanzaCollectorAndSend(unblockContactIQ).nextResultOrThrow(); } + public void addJidsBlockedListener(JidsBlockedListener jidsBlockedListener) { + jidsBlockedListeners.add(jidsBlockedListener); + } + + public void removeJidsBlockedListener(JidsBlockedListener jidsBlockedListener) { + jidsBlockedListeners.remove(jidsBlockedListener); + } + + public void addJidsUnblockedListener(JidsUnblockedListener jidsUnblockedListener) { + jidsUnblockedListeners.add(jidsUnblockedListener); + } + + public void removeJidsUnblockedListener(JidsUnblockedListener jidsUnblockedListener) { + jidsUnblockedListeners.remove(jidsUnblockedListener); + } + + public void addAllJidsUnblockedListener(AllJidsUnblockedListener allJidsUnblockedListener) { + allJidsUnblockedListeners.add(allJidsUnblockedListener); + } + + public void removeAllJidsUnblockedListener(AllJidsUnblockedListener allJidsUnblockedListener) { + allJidsUnblockedListeners.remove(allJidsUnblockedListener); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsBlockedListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsBlockedListener.java new file mode 100644 index 000000000..e4b1a086e --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsBlockedListener.java @@ -0,0 +1,27 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.blocking; + +import java.util.List; + +import org.jxmpp.jid.Jid; + +public interface JidsBlockedListener { + + void onJidsBlocked(List blockedJids); + +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsUnblockedListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsUnblockedListener.java new file mode 100644 index 000000000..139a9117c --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/JidsUnblockedListener.java @@ -0,0 +1,27 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.blocking; + +import java.util.List; + +import org.jxmpp.jid.Jid; + +public interface JidsUnblockedListener { + + void onJidsUnblocked(List unblockedJids); + +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/BlockContactsIQ.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/BlockContactsIQ.java index 19ca0eb72..7a137668a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/BlockContactsIQ.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/BlockContactsIQ.java @@ -16,6 +16,7 @@ */ package org.jivesoftware.smackx.blocking.element; +import java.util.Collections; import java.util.List; import org.jivesoftware.smack.packet.IQ; @@ -51,7 +52,7 @@ public class BlockContactsIQ extends IQ { public BlockContactsIQ(List jids) { super(ELEMENT, NAMESPACE); this.setType(Type.set); - this.jids = jids; + this.jids = Collections.unmodifiableList(jids); } /** diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/UnblockContactsIQ.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/UnblockContactsIQ.java index 5b2260b37..73d36ff9e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/UnblockContactsIQ.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/element/UnblockContactsIQ.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016 Fernando Ramirez, Florian Schmaus + * Copyright 2016-2017 Fernando Ramirez, Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package org.jivesoftware.smackx.blocking.element; +import java.util.Collections; import java.util.List; import org.jivesoftware.smack.packet.IQ; @@ -52,7 +53,11 @@ public class UnblockContactsIQ extends IQ { public UnblockContactsIQ(List jids) { super(ELEMENT, NAMESPACE); this.setType(Type.set); - this.jids = jids; + if (jids != null) { + this.jids = Collections.unmodifiableList(jids); + } else { + this.jids = null; + } } /** @@ -63,9 +68,9 @@ public class UnblockContactsIQ extends IQ { } /** - * Get the JIDs. + * Get the JIDs. This may return null, which means that all JIDs should be or where unblocked. * - * @return the list of JIDs + * @return the list of JIDs or null. */ public List getJids() { return jids; @@ -73,14 +78,16 @@ public class UnblockContactsIQ extends IQ { @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { - xml.rightAngleBracket(); + if (jids == null) { + xml.setEmptyElement(); + return xml; + } - if (jids != null) { - for (Jid jid : jids) { - xml.halfOpenElement("item"); - xml.attribute("jid", jid); - xml.closeEmptyElement(); - } + xml.rightAngleBracket(); + for (Jid jid : jids) { + xml.halfOpenElement("item"); + xml.attribute("jid", jid); + xml.closeEmptyElement(); } return xml; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/provider/BlockContactsIQProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/provider/BlockContactsIQProvider.java index ad45f5c4b..5e443c4c7 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/provider/BlockContactsIQProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/provider/BlockContactsIQProvider.java @@ -20,9 +20,9 @@ import java.util.ArrayList; import java.util.List; import org.jivesoftware.smack.provider.IQProvider; +import org.jivesoftware.smack.util.ParserUtils; import org.jivesoftware.smackx.blocking.element.BlockContactsIQ; import org.jxmpp.jid.Jid; -import org.jxmpp.jid.impl.JidCreate; import org.xmlpull.v1.XmlPullParser; /** @@ -36,7 +36,7 @@ public class BlockContactsIQProvider extends IQProvider { @Override public BlockContactsIQ parse(XmlPullParser parser, int initialDepth) throws Exception { - List jids = null; + List jids = new ArrayList<>(); outerloop: while (true) { int eventType = parser.next(); @@ -45,10 +45,8 @@ public class BlockContactsIQProvider extends IQProvider { case XmlPullParser.START_TAG: if (parser.getName().equals("item")) { - if (jids == null) { - jids = new ArrayList<>(); - } - jids.add(JidCreate.from(parser.getAttributeValue("", "jid"))); + Jid jid = ParserUtils.getJidAttribute(parser); + jids.add(jid); } break; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedConference.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedConference.java index f08e3c0a2..fa1a4f1d8 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedConference.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedConference.java @@ -131,6 +131,7 @@ public class BookmarkedConference implements SharedBookmark { this.isShared = isShared; } + @Override public boolean isShared() { return isShared; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedURL.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedURL.java index 0a521bcdf..55f30bfa0 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedURL.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkedURL.java @@ -102,6 +102,7 @@ public class BookmarkedURL implements SharedBookmark { this.isShared = shared; } + @Override public boolean isShared() { return isShared; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/Bookmarks.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/Bookmarks.java index b176e3576..d196f23c4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/Bookmarks.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/Bookmarks.java @@ -151,6 +151,7 @@ public class Bookmarks implements PrivateData { * * @return the element name. */ + @Override public String getElementName() { return ELEMENT; } @@ -160,6 +161,7 @@ public class Bookmarks implements PrivateData { * * @return the namespace. */ + @Override public String getNamespace() { return NAMESPACE; } @@ -218,6 +220,7 @@ public class Bookmarks implements PrivateData { super(); } + @Override public PrivateData parsePrivateData(XmlPullParser parser) throws XmlPullParserException, IOException { Bookmarks storage = new Bookmarks(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamListener.java index d5a49cc98..cc69e7e74 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamListener.java @@ -34,6 +34,7 @@ public abstract class InBandBytestreamListener implements BytestreamListener { + @Override public void incomingBytestreamRequest(BytestreamRequest request) { incomingBytestreamRequest((InBandBytestreamRequest) request); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManager.java index e823c2cc7..e8f28404b 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManager.java @@ -103,6 +103,7 @@ public final class InBandBytestreamManager implements BytestreamManager { */ static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(final XMPPConnection connection) { // create the manager for this connection InBandBytestreamManager.getByteStreamManager(connection); @@ -236,6 +237,7 @@ public final class InBandBytestreamManager implements BytestreamManager { * * @param listener the listener to register */ + @Override public void addIncomingBytestreamListener(BytestreamListener listener) { this.allRequestListeners.add(listener); } @@ -246,6 +248,7 @@ public final class InBandBytestreamManager implements BytestreamManager { * * @param listener the listener to remove */ + @Override public void removeIncomingBytestreamListener(BytestreamListener listener) { this.allRequestListeners.remove(listener); } @@ -268,6 +271,7 @@ public final class InBandBytestreamManager implements BytestreamManager { * @param listener the listener to register * @param initiatorJID the JID of the user that wants to establish an In-Band Bytestream */ + @Override public void addIncomingBytestreamListener(BytestreamListener listener, Jid initiatorJID) { this.userListeners.put(initiatorJID, listener); } @@ -277,6 +281,9 @@ public final class InBandBytestreamManager implements BytestreamManager { * * @param initiatorJID the JID of the user the listener should be removed */ + @Override + // TODO: Change argument to Jid in Smack 4.3. + @SuppressWarnings("CollectionIncompatibleType") public void removeIncomingBytestreamListener(String initiatorJID) { this.userListeners.remove(initiatorJID); } @@ -402,6 +409,7 @@ public final class InBandBytestreamManager implements BytestreamManager { * @throws SmackException if there was no response from the server. * @throws InterruptedException */ + @Override public InBandBytestreamSession establishSession(Jid targetJID) throws XMPPException, SmackException, InterruptedException { String sessionID = getNextSessionID(); return establishSession(targetJID, sessionID); @@ -420,6 +428,7 @@ public final class InBandBytestreamManager implements BytestreamManager { * @throws NotConnectedException * @throws InterruptedException */ + @Override public InBandBytestreamSession establishSession(Jid targetJID, String sessionID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Open byteStreamRequest = new Open(sessionID, this.defaultBlockSize, this.stanza); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamRequest.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamRequest.java index 8040416d7..e9b846326 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamRequest.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamRequest.java @@ -50,6 +50,7 @@ public class InBandBytestreamRequest implements BytestreamRequest { * * @return the sender of the In-Band Bytestream open request */ + @Override public Jid getFrom() { return this.byteStreamRequest.getFrom(); } @@ -59,6 +60,7 @@ public class InBandBytestreamRequest implements BytestreamRequest { * * @return the session ID of the In-Band Bytestream open request */ + @Override public String getSessionID() { return this.byteStreamRequest.getSessionID(); } @@ -71,6 +73,7 @@ public class InBandBytestreamRequest implements BytestreamRequest { * @throws NotConnectedException * @throws InterruptedException */ + @Override public InBandBytestreamSession accept() throws NotConnectedException, InterruptedException { XMPPConnection connection = this.manager.getConnection(); @@ -92,6 +95,7 @@ public class InBandBytestreamRequest implements BytestreamRequest { * @throws NotConnectedException * @throws InterruptedException */ + @Override public void reject() throws NotConnectedException, InterruptedException { this.manager.replyRejectPacket(this.byteStreamRequest); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSession.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSession.java index 40f185af1..b87443887 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSession.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSession.java @@ -109,18 +109,22 @@ public class InBandBytestreamSession implements BytestreamSession { } + @Override public InputStream getInputStream() { return this.inputStream; } + @Override public OutputStream getOutputStream() { return this.outputStream; } + @Override public int getReadTimeout() { return this.inputStream.readTimeout; } + @Override public void setReadTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("Timeout must be >= 0"); @@ -151,6 +155,7 @@ public class InBandBytestreamSession implements BytestreamSession { this.closeBothStreamsEnabled = closeBothStreamsEnabled; } + @Override public void close() throws IOException { closeByLocal(true); // close input stream closeByLocal(false); // close output stream @@ -224,7 +229,9 @@ public class InBandBytestreamSession implements BytestreamSession { this.inputStream.cleanup(); // remove session from manager - InBandBytestreamManager.getByteStreamManager(this.connection).getSessions().remove(this); + // Thanks Google Error Prone for finding the bug where remove() was called with 'this' as argument. Changed + // now to remove(byteStreamRequest.getSessionID). + InBandBytestreamManager.getByteStreamManager(this.connection).getSessions().remove(byteStreamRequest.getSessionID()); } } @@ -283,6 +290,7 @@ public class InBandBytestreamSession implements BytestreamSession { */ protected abstract StanzaFilter getDataPacketFilter(); + @Override public synchronized int read() throws IOException { checkClosed(); @@ -298,6 +306,7 @@ public class InBandBytestreamSession implements BytestreamSession { return buffer[bufferPointer++] & 0xff; } + @Override public synchronized int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); @@ -331,6 +340,7 @@ public class InBandBytestreamSession implements BytestreamSession { return len; } + @Override public synchronized int read(byte[] b) throws IOException { return read(b, 0, b.length); } @@ -405,10 +415,12 @@ public class InBandBytestreamSession implements BytestreamSession { } } + @Override public boolean markSupported() { return false; } + @Override public void close() throws IOException { if (closeInvoked) { return; @@ -444,11 +456,13 @@ public class InBandBytestreamSession implements BytestreamSession { */ private class IQIBBInputStream extends IBBInputStream { + @Override protected StanzaListener getDataPacketListener() { return new StanzaListener() { private long lastSequence = -1; + @Override public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException { // get data packet extension DataPacketExtension data = ((Data) packet).getDataPacketExtension(); @@ -491,6 +505,7 @@ public class InBandBytestreamSession implements BytestreamSession { }; } + @Override protected StanzaFilter getDataPacketFilter() { /* * filter all IQ stanzas having type 'SET' (represented by Data class), containing a @@ -507,9 +522,11 @@ public class InBandBytestreamSession implements BytestreamSession { */ private class MessageIBBInputStream extends IBBInputStream { + @Override protected StanzaListener getDataPacketListener() { return new StanzaListener() { + @Override public void processStanza(Stanza packet) { // get data packet extension DataPacketExtension data = (DataPacketExtension) packet.getExtension( @@ -555,6 +572,7 @@ public class InBandBytestreamSession implements BytestreamSession { */ private class IBBDataPacketFilter implements StanzaFilter { + @Override public boolean accept(Stanza packet) { // sender equals remote peer if (!packet.getFrom().equals(remoteJID)) { @@ -619,6 +637,7 @@ public class InBandBytestreamSession implements BytestreamSession { */ protected abstract void writeToXML(DataPacketExtension data) throws IOException, NotConnectedException, InterruptedException; + @Override public synchronized void write(int b) throws IOException { if (this.isClosed) { throw new IOException("Stream is closed"); @@ -632,6 +651,7 @@ public class InBandBytestreamSession implements BytestreamSession { buffer[bufferPointer++] = (byte) b; } + @Override public synchronized void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); @@ -662,6 +682,7 @@ public class InBandBytestreamSession implements BytestreamSession { } } + @Override public synchronized void write(byte[] b) throws IOException { write(b, 0, b.length); } @@ -698,6 +719,7 @@ public class InBandBytestreamSession implements BytestreamSession { bufferPointer += len - available; } + @Override public synchronized void flush() throws IOException { if (this.isClosed) { throw new IOException("Stream is closed"); @@ -735,6 +757,7 @@ public class InBandBytestreamSession implements BytestreamSession { } + @Override public void close() throws IOException { if (isClosed) { return; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InitiationListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InitiationListener.java index 7188a355a..1a4f3686d 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InitiationListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/InitiationListener.java @@ -66,6 +66,7 @@ class InitiationListener extends AbstractIqRequestHandler { public IQ handleIQRequest(final IQ packet) { initiationListenerExecutor.execute(new Runnable() { + @Override public void run() { try { processRequest(packet); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtension.java index 1e82f8dc8..e076acc95 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtension.java @@ -126,10 +126,12 @@ public class DataPacketExtension implements ExtensionElement { return this.decodedData; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/InitiationListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/InitiationListener.java index 6ed097d05..60309be81 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/InitiationListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/InitiationListener.java @@ -62,6 +62,7 @@ final class InitiationListener extends AbstractIqRequestHandler { public IQ handleIQRequest(final IQ packet) { initiationListenerExecutor.execute(new Runnable() { + @Override public void run() { try { processRequest(packet); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamListener.java index bbb576041..6c8f9d916 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamListener.java @@ -32,6 +32,7 @@ import org.jivesoftware.smackx.bytestreams.BytestreamRequest; */ public abstract class Socks5BytestreamListener implements BytestreamListener { + @Override public void incomingBytestreamRequest(BytestreamRequest request) { incomingBytestreamRequest((Socks5BytestreamRequest) request); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamManager.java index 268f63779..04f4d6ac4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamManager.java @@ -98,6 +98,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(final XMPPConnection connection) { // create the manager for this connection Socks5BytestreamManager.getBytestreamManager(connection); @@ -198,6 +199,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * * @param listener the listener to register */ + @Override public void addIncomingBytestreamListener(BytestreamListener listener) { this.allRequestListeners.add(listener); } @@ -208,6 +210,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * * @param listener the listener to remove */ + @Override public void removeIncomingBytestreamListener(BytestreamListener listener) { this.allRequestListeners.remove(listener); } @@ -230,6 +233,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * @param listener the listener to register * @param initiatorJID the JID of the user that wants to establish a SOCKS5 Bytestream */ + @Override public void addIncomingBytestreamListener(BytestreamListener listener, Jid initiatorJID) { this.userListeners.put(initiatorJID, listener); } @@ -239,6 +243,9 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * * @param initiatorJID the JID of the user the listener should be removed */ + // TODO: Change parameter to Jid in Smack 4.3. + @Override + @SuppressWarnings("CollectionIncompatibleType") public void removeIncomingBytestreamListener(String initiatorJID) { this.userListeners.remove(initiatorJID); } @@ -386,6 +393,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * @throws InterruptedException if the current thread was interrupted while waiting * @throws SmackException if there was no response from the server. */ + @Override public Socks5BytestreamSession establishSession(Jid targetJID) throws XMPPException, IOException, InterruptedException, SmackException { String sessionID = getNextSessionID(); @@ -405,6 +413,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream * @throws SmackException if the target does not support SOCKS5. * @throws XMPPException */ + @Override public Socks5BytestreamSession establishSession(Jid targetJID, String sessionID) throws IOException, InterruptedException, NoResponseException, SmackException, XMPPException{ XMPPConnection connection = connection(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamRequest.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamRequest.java index e636cd3eb..84fb63a4a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamRequest.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamRequest.java @@ -170,6 +170,7 @@ public class Socks5BytestreamRequest implements BytestreamRequest { * * @return the sender of the SOCKS5 Bytestream initialization request. */ + @Override public Jid getFrom() { return this.bytestreamRequest.getFrom(); } @@ -179,6 +180,7 @@ public class Socks5BytestreamRequest implements BytestreamRequest { * * @return the session ID of the SOCKS5 Bytestream initialization request. */ + @Override public String getSessionID() { return this.bytestreamRequest.getSessionID(); } @@ -195,6 +197,7 @@ public class Socks5BytestreamRequest implements BytestreamRequest { * @throws XMPPErrorException * @throws SmackException */ + @Override public Socks5BytestreamSession accept() throws InterruptedException, XMPPErrorException, SmackException { Collection streamHosts = this.bytestreamRequest.getStreamHosts(); @@ -264,6 +267,7 @@ public class Socks5BytestreamRequest implements BytestreamRequest { * @throws NotConnectedException * @throws InterruptedException */ + @Override public void reject() throws NotConnectedException, InterruptedException { this.manager.replyRejectPacket(this.bytestreamRequest); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamSession.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamSession.java index adb423c65..06cf408ad 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamSession.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamSession.java @@ -64,14 +64,17 @@ public class Socks5BytestreamSession implements BytestreamSession { return !this.isDirect; } + @Override public InputStream getInputStream() throws IOException { return this.socket.getInputStream(); } + @Override public OutputStream getOutputStream() throws IOException { return this.socket.getOutputStream(); } + @Override public int getReadTimeout() throws IOException { try { return this.socket.getSoTimeout(); @@ -81,6 +84,7 @@ public class Socks5BytestreamSession implements BytestreamSession { } } + @Override public void setReadTimeout(int timeout) throws IOException { try { this.socket.setSoTimeout(timeout); @@ -90,6 +94,7 @@ public class Socks5BytestreamSession implements BytestreamSession { } } + @Override public void close() throws IOException { this.socket.close(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Client.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Client.java index 2de338a5c..91e2dbe31 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Client.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Client.java @@ -19,6 +19,7 @@ package org.jivesoftware.smackx.bytestreams.socks5; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; @@ -34,6 +35,7 @@ import java.util.logging.Logger; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost; /** @@ -82,6 +84,7 @@ class Socks5Client { // wrap connecting in future for timeout FutureTask futureTask = new FutureTask(new Callable() { + @Override public Socket call() throws IOException, SmackException { // initialize socket @@ -199,7 +202,13 @@ class Socks5Client { * @return SOCKS5 connection request message */ private byte[] createSocks5ConnectRequest() { - byte[] addr = this.digest.getBytes(); + byte[] addr; + try { + addr = digest.getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } byte[] data = new byte[7 + addr.length]; data[0] = (byte) 0x05; // version (SOCKS5) diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiator.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiator.java index 4bdbff82d..bb02f486a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiator.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiator.java @@ -69,6 +69,7 @@ class Socks5ClientForInitiator extends Socks5Client { this.target = target; } + @Override public Socket getSocket(int timeout) throws IOException, InterruptedException, TimeoutException, XMPPException, SmackException { Socket socket = null; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Proxy.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Proxy.java index 54f9dacfa..4a1006877 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Proxy.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5Proxy.java @@ -38,6 +38,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.SmackException; +import org.jivesoftware.smack.util.StringUtils; /** * The Socks5Proxy class represents a local SOCKS5 proxy server. It can be enabled/disabled by @@ -381,6 +382,7 @@ public final class Socks5Proxy { */ private class Socks5ServerProcess implements Runnable { + @Override public void run() { while (true) { Socket socket = null; @@ -470,7 +472,7 @@ public final class Socks5Proxy { byte[] connectionRequest = Socks5Utils.receiveSocks5Message(in); // extract digest - String responseDigest = new String(connectionRequest, 5, connectionRequest[4]); + String responseDigest = new String(connectionRequest, 5, connectionRequest[4], StringUtils.UTF8); // return error if digest is not allowed if (!Socks5Proxy.this.allowedConnections.contains(responseDigest)) { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/packet/Bytestream.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/packet/Bytestream.java index df45488af..4b87c8ecf 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/packet/Bytestream.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/packet/Bytestream.java @@ -317,6 +317,7 @@ public class Bytestream extends IQ { return port; } + @Override public String getElementName() { return ELEMENTNAME; } @@ -366,6 +367,7 @@ public class Bytestream extends IQ { return JID; } + @Override public String getElementName() { return ELEMENTNAME; } @@ -408,6 +410,7 @@ public class Bytestream extends IQ { return target; } + @Override public String getElementName() { return ELEMENTNAME; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java index d61b7c4b1..afcdfce6a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java @@ -65,6 +65,7 @@ import java.util.WeakHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; +import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -113,6 +114,7 @@ public final class EntityCapsManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } @@ -346,6 +348,7 @@ public final class EntityCapsManager extends Manager { // XEP-0115 specifies that a client SHOULD include entity capabilities // with every presence notification it sends. StanzaListener packetInterceptor = new StanzaListener() { + @Override public void processStanza(Stanza packet) { if (!entityCapsEnabled) { // Be sure to not send stanzas with the caps extension if it's not enabled @@ -403,7 +406,11 @@ public final class EntityCapsManager extends Manager { * @param user * the user (Full JID) */ + // TODO: Change parameter type to Jid in Smack 4.3. + @SuppressWarnings("CollectionIncompatibleType") public static void removeUserCapsNode(String user) { + // While JID_TO_NODEVER_CHACHE has the generic types , it is ok to call remove with String + // arguments, since the same Jid and String representations would be equal and have the same hash code. JID_TO_NODEVER_CACHE.remove(user); } @@ -658,6 +665,7 @@ public final class EntityCapsManager extends Manager { // XEP-0128 data forms, sort the forms by the FORM_TYPE (i.e., // by the XML character data of the element). SortedSet fs = new TreeSet(new Comparator() { + @Override public int compare(FormField f1, FormField f2) { return f1.getVariable().compareTo(f2.getVariable()); } @@ -701,9 +709,16 @@ public final class EntityCapsManager extends Manager { // encoded using Base64 as specified in Section 4 of RFC 4648 // (note: the Base64 output MUST NOT include whitespace and MUST set // padding bits to zero). + byte[] bytes; + try { + bytes = sb.toString().getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } byte[] digest; synchronized(md) { - digest = md.digest(sb.toString().getBytes()); + digest = md.digest(bytes); } String version = Base64.encodeToString(digest); return new CapsVersionAndHash(version, hash); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/packet/CapsExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/packet/CapsExtension.java index b14eeb3ca..b23b6de6e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/packet/CapsExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/packet/CapsExtension.java @@ -35,10 +35,12 @@ public class CapsExtension implements ExtensionElement { this.hash = hash; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/provider/CapsExtensionProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/provider/CapsExtensionProvider.java index ba27200c9..55f4f616c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/provider/CapsExtensionProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/provider/CapsExtensionProvider.java @@ -27,6 +27,7 @@ import org.xmlpull.v1.XmlPullParserException; public class CapsExtensionProvider extends ExtensionElementProvider { + @Override public CapsExtension parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { String hash = null; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java index 212ad0918..0552fd9b1 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java @@ -119,6 +119,7 @@ public final class ChatStateManager extends Manager { } + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -129,6 +130,7 @@ public final class ChatStateManager extends Manager { } + @Override public int hashCode() { return connection().hashCode(); } @@ -164,12 +166,14 @@ public final class ChatStateManager extends Manager { } } - private class IncomingMessageInterceptor implements ChatManagerListener, ChatMessageListener { + private static class IncomingMessageInterceptor implements ChatManagerListener, ChatMessageListener { + @Override public void chatCreated(final org.jivesoftware.smack.chat.Chat chat, boolean createdLocally) { chat.addMessageListener(this); } + @Override public void processMessage(org.jivesoftware.smack.chat.Chat chat, Message message) { ExtensionElement extension = message.getExtension(NAMESPACE); if (extension == null) { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/packet/ChatStateExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/packet/ChatStateExtension.java index 8aac8339c..ab0f0c772 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/packet/ChatStateExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/packet/ChatStateExtension.java @@ -19,9 +19,7 @@ package org.jivesoftware.smackx.chatstates.packet; import org.jivesoftware.smackx.chatstates.ChatState; import org.jivesoftware.smack.packet.ExtensionElement; -import org.jivesoftware.smack.provider.ExtensionElementProvider; import org.jivesoftware.smack.util.XmlStringBuilder; -import org.xmlpull.v1.XmlPullParser; /** * Represents a chat state which is an extension to message packets which is used to indicate @@ -66,18 +64,4 @@ public class ChatStateExtension implements ExtensionElement { return xml; } - public static class Provider extends ExtensionElementProvider { - - @Override - public ChatStateExtension parse(XmlPullParser parser, int initialDepth) { - ChatState state; - try { - state = ChatState.valueOf(parser.getName()); - } - catch (Exception ex) { - state = ChatState.active; - } - return new ChatStateExtension(state); - } - } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/ChatStateExtensionProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/ChatStateExtensionProvider.java new file mode 100644 index 000000000..03506dbaa --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/ChatStateExtensionProvider.java @@ -0,0 +1,34 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.chatstates.provider; + +import org.jivesoftware.smack.provider.ExtensionElementProvider; +import org.jivesoftware.smackx.chatstates.ChatState; +import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension; +import org.xmlpull.v1.XmlPullParser; + +public class ChatStateExtensionProvider extends ExtensionElementProvider { + + @Override + public ChatStateExtension parse(XmlPullParser parser, int initialDepth) throws Exception { + String chatStateString = parser.getName(); + ChatState state = ChatState.valueOf(chatStateString); + + return new ChatStateExtension(state); + } + +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/package-info.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/package-info.java new file mode 100644 index 000000000..81c818453 --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/provider/package-info.java @@ -0,0 +1,21 @@ +/** + * + * Copyright 2017 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provider classes for Chat State Notifications (XEP-0085). + */ +package org.jivesoftware.smackx.chatstates.provider; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java index e3f5331f6..46c819ff6 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java @@ -457,12 +457,13 @@ public abstract class AdHocCommand { */ sessionExpired("session-expired"); - private String value; + private final String value; SpecificErrorCondition(String value) { this.value = value; } + @Override public String toString() { return value; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java index b0e9902a1..8ddc1167d 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java @@ -17,6 +17,7 @@ package org.jivesoftware.smackx.commands; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -83,6 +84,7 @@ public final class AdHocCommandManager extends Manager { */ static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getAddHocCommandsManager(connection); } @@ -200,8 +202,16 @@ public final class AdHocCommandManager extends Manager { */ public void registerCommand(String node, String name, final Class clazz) { registerCommand(node, name, new LocalCommandFactory() { + @Override public LocalCommand getInstance() throws InstantiationException, IllegalAccessException { - return clazz.newInstance(); + try { + return clazz.getConstructor().newInstance(); + } + catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException + | SecurityException e) { + // TODO: Throw those method in Smack 4.3. + throw new IllegalStateException(e); + } } }); } @@ -393,6 +403,7 @@ public final class AdHocCommandManager extends Manager { // See if the session reaping thread is started. If not, start it. if (sessionsSweeper == null) { sessionsSweeper = new Thread(new Runnable() { + @Override public void run() { while (true) { for (String sessionId : executingCommands.keySet()) { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java index 56a107a03..80cd688ce 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java @@ -248,9 +248,11 @@ public class AdHocCommandData extends IQ { this.condition = condition; } + @Override public String getElementName() { return condition.toString(); } + @Override public String getNamespace() { return namespace; } @@ -259,6 +261,7 @@ public class AdHocCommandData extends IQ { return condition; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(getElementName()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/delay/packet/DelayInformation.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/delay/packet/DelayInformation.java index 00450d7ea..3133676bb 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/delay/packet/DelayInformation.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/delay/packet/DelayInformation.java @@ -88,10 +88,12 @@ public class DelayInformation implements ExtensionElement { return reason; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/AbstractNodeInformationProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/AbstractNodeInformationProvider.java index ba9ecddaa..6d64bc848 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/AbstractNodeInformationProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/AbstractNodeInformationProvider.java @@ -25,18 +25,22 @@ import java.util.List; public abstract class AbstractNodeInformationProvider implements NodeInformationProvider { + @Override public List getNodeItems() { return null; } + @Override public List getNodeFeatures() { return null; } + @Override public List getNodeIdentities() { return null; } + @Override public List getNodePacketExtensions() { return null; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java index 2a9b8cabf..89667770c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java @@ -91,6 +91,7 @@ public final class ServiceDiscoveryManager extends Manager { // Create a new ServiceDiscoveryManager on every established connection static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java index 1957d2392..93e19cbc5 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java @@ -394,6 +394,7 @@ public class DiscoverInfo extends IQ implements TypedCloneable { * XEP-0015 5.4 Processing Method (Step 3.3). * */ + @Override public boolean equals(Object obj) { if (obj == null) return false; @@ -437,6 +438,7 @@ public class DiscoverInfo extends IQ implements TypedCloneable { * @return a negative integer, zero, or a positive integer as this object is less than, * equal to, or greater than the specified object. */ + @Override public int compareTo(DiscoverInfo.Identity other) { String otherLang = other.lang == null ? "" : other.lang; String thisLang = lang == null ? "" : lang; @@ -512,6 +514,7 @@ public class DiscoverInfo extends IQ implements TypedCloneable { return xml; } + @Override public boolean equals(Object obj) { if (obj == null) return false; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FaultTolerantNegotiator.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FaultTolerantNegotiator.java index bbb853919..597e744ed 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FaultTolerantNegotiator.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FaultTolerantNegotiator.java @@ -55,11 +55,13 @@ public class FaultTolerantNegotiator extends StreamNegotiator { secondaryNegotiator.newStreamInitiation(from, streamID); } + @Override InputStream negotiateIncomingStream(Stanza streamInitiation) { throw new UnsupportedOperationException("Negotiation only handled by create incoming " + "stream method."); } + @Override public InputStream createIncomingStream(final StreamInitiation initiation) throws SmackException, XMPPErrorException, InterruptedException { // This could be either an xep47 ibb 'open' iq or an xep65 streamhost iq IQ initationSet = initiateIncomingStream(connection, initiation); @@ -79,6 +81,7 @@ public class FaultTolerantNegotiator extends StreamNegotiator { } } + @Override public OutputStream createOutgoingStream(String streamID, Jid initiator, Jid target) throws SmackException, XMPPException, InterruptedException { OutputStream stream; @@ -92,6 +95,7 @@ public class FaultTolerantNegotiator extends StreamNegotiator { return stream; } + @Override public String[] getNamespaces() { String[] primary = primaryNegotiator.getNamespaces(); String[] secondary = secondaryNegotiator.getNamespaces(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransfer.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransfer.java index ae99f6224..13220ffaf 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransfer.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransfer.java @@ -31,27 +31,27 @@ import org.jxmpp.jid.Jid; */ public abstract class FileTransfer { - private String fileName; + private String fileName; - private String filePath; + private String filePath; - private long fileSize; + private long fileSize; - private Jid peer; + private Jid peer; - private Status status = Status.initial; + private Status status = Status.initial; private final Object statusMonitor = new Object(); - protected FileTransferNegotiator negotiator; + protected FileTransferNegotiator negotiator; - protected String streamID; + protected String streamID; - protected long amountWritten = -1; + protected long amountWritten = -1; - private Error error; + private Error error; - private Exception exception; + private Exception exception; /** * Buffer size between input and output @@ -59,137 +59,137 @@ public abstract class FileTransfer { private static final int BUFFER_SIZE = 8192; protected FileTransfer(Jid peer, String streamID, - FileTransferNegotiator negotiator) { - this.peer = peer; - this.streamID = streamID; - this.negotiator = negotiator; - } + FileTransferNegotiator negotiator) { + this.peer = peer; + this.streamID = streamID; + this.negotiator = negotiator; + } - protected void setFileInfo(String fileName, long fileSize) { - this.fileName = fileName; - this.fileSize = fileSize; - } + protected void setFileInfo(String fileName, long fileSize) { + this.fileName = fileName; + this.fileSize = fileSize; + } - protected void setFileInfo(String path, String fileName, long fileSize) { - this.filePath = path; - this.fileName = fileName; - this.fileSize = fileSize; - } + protected void setFileInfo(String path, String fileName, long fileSize) { + this.filePath = path; + this.fileName = fileName; + this.fileSize = fileSize; + } - /** - * Returns the size of the file being transfered. - * - * @return Returns the size of the file being transfered. - */ - public long getFileSize() { - return fileSize; - } + /** + * Returns the size of the file being transfered. + * + * @return Returns the size of the file being transfered. + */ + public long getFileSize() { + return fileSize; + } - /** - * Returns the name of the file being transfered. - * - * @return Returns the name of the file being transfered. - */ - public String getFileName() { - return fileName; - } + /** + * Returns the name of the file being transfered. + * + * @return Returns the name of the file being transfered. + */ + public String getFileName() { + return fileName; + } - /** - * Returns the local path of the file. - * - * @return Returns the local path of the file. - */ - public String getFilePath() { - return filePath; - } + /** + * Returns the local path of the file. + * + * @return Returns the local path of the file. + */ + public String getFilePath() { + return filePath; + } - /** - * Returns the JID of the peer for this file transfer. - * - * @return Returns the JID of the peer for this file transfer. - */ - public Jid getPeer() { - return peer; - } + /** + * Returns the JID of the peer for this file transfer. + * + * @return Returns the JID of the peer for this file transfer. + */ + public Jid getPeer() { + return peer; + } - /** - * Returns the progress of the file transfer as a number between 0 and 1. - * - * @return Returns the progress of the file transfer as a number between 0 - * and 1. - */ - public double getProgress() { + /** + * Returns the progress of the file transfer as a number between 0 and 1. + * + * @return Returns the progress of the file transfer as a number between 0 + * and 1. + */ + public double getProgress() { if (amountWritten <= 0 || fileSize <= 0) { return 0; } return (double) amountWritten / (double) fileSize; - } + } - /** - * Returns true if the transfer has been cancelled, if it has stopped because - * of a an error, or the transfer completed successfully. - * - * @return Returns true if the transfer has been cancelled, if it has stopped - * because of a an error, or the transfer completed successfully. - */ - public boolean isDone() { - return status == Status.cancelled || status == Status.error - || status == Status.complete || status == Status.refused; - } + /** + * Returns true if the transfer has been cancelled, if it has stopped because + * of a an error, or the transfer completed successfully. + * + * @return Returns true if the transfer has been cancelled, if it has stopped + * because of a an error, or the transfer completed successfully. + */ + public boolean isDone() { + return status == Status.cancelled || status == Status.error + || status == Status.complete || status == Status.refused; + } - /** - * Returns the current status of the file transfer. - * - * @return Returns the current status of the file transfer. - */ - public Status getStatus() { - return status; - } + /** + * Returns the current status of the file transfer. + * + * @return Returns the current status of the file transfer. + */ + public Status getStatus() { + return status; + } - protected void setError(Error type) { - this.error = type; - } + protected void setError(Error type) { + this.error = type; + } - /** - * When {@link #getStatus()} returns that there was an {@link Status#error} - * during the transfer, the type of error can be retrieved through this - * method. - * - * @return Returns the type of error that occurred if one has occurred. - */ - public Error getError() { - return error; - } + /** + * When {@link #getStatus()} returns that there was an {@link Status#error} + * during the transfer, the type of error can be retrieved through this + * method. + * + * @return Returns the type of error that occurred if one has occurred. + */ + public Error getError() { + return error; + } - /** - * If an exception occurs asynchronously it will be stored for later - * retrieval. If there is an error there maybe an exception set. - * - * @return The exception that occurred or null if there was no exception. - * @see #getError() - */ - public Exception getException() { - return exception; - } + /** + * If an exception occurs asynchronously it will be stored for later + * retrieval. If there is an error there maybe an exception set. + * + * @return The exception that occurred or null if there was no exception. + * @see #getError() + */ + public Exception getException() { + return exception; + } public String getStreamID() { return streamID; } - /** - * Cancels the file transfer. - */ - public abstract void cancel(); + /** + * Cancels the file transfer. + */ + public abstract void cancel(); - protected void setException(Exception exception) { - this.exception = exception; - } + protected void setException(Exception exception) { + this.exception = exception; + } - protected void setStatus(Status status) { + protected void setStatus(Status status) { synchronized (statusMonitor) { // CHECKSTYLE:OFF - this.status = status; - } + this.status = status; + } // CHECKSTYLE:ON } @@ -206,98 +206,99 @@ public abstract class FileTransfer { protected void writeToStream(final InputStream in, final OutputStream out) throws IOException { - final byte[] b = new byte[BUFFER_SIZE]; - int count = 0; - amountWritten = 0; + final byte[] b = new byte[BUFFER_SIZE]; + int count = 0; + amountWritten = 0; while ((count = in.read(b)) > 0 && !getStatus().equals(Status.cancelled)) { out.write(b, 0, count); amountWritten += count; } - // the connection was likely terminated abruptly if these are not equal - if (!getStatus().equals(Status.cancelled) && getError() == Error.none - && amountWritten != fileSize) { + // the connection was likely terminated abruptly if these are not equal + if (!getStatus().equals(Status.cancelled) && getError() == Error.none + && amountWritten != fileSize) { setStatus(Status.error); - this.error = Error.connection; - } - } + this.error = Error.connection; + } + } - /** - * A class to represent the current status of the file transfer. - * - * @author Alexander Wenckus - * - */ - public enum Status { + /** + * A class to represent the current status of the file transfer. + * + * @author Alexander Wenckus + * + */ + public enum Status { - /** - * An error occurred during the transfer. - * - * @see FileTransfer#getError() - */ - error("Error"), + /** + * An error occurred during the transfer. + * + * @see FileTransfer#getError() + */ + error("Error"), - /** + /** * The initial status of the file transfer. */ initial("Initial"), /** - * The file transfer is being negotiated with the peer. The party - * Receiving the file has the option to accept or refuse a file transfer - * request. If they accept, then the process of stream negotiation will - * begin. If they refuse the file will not be transfered. - * - * @see #negotiating_stream - */ - negotiating_transfer("Negotiating Transfer"), + * The file transfer is being negotiated with the peer. The party + * Receiving the file has the option to accept or refuse a file transfer + * request. If they accept, then the process of stream negotiation will + * begin. If they refuse the file will not be transfered. + * + * @see #negotiating_stream + */ + negotiating_transfer("Negotiating Transfer"), - /** - * The peer has refused the file transfer request halting the file - * transfer negotiation process. - */ - refused("Refused"), + /** + * The peer has refused the file transfer request halting the file + * transfer negotiation process. + */ + refused("Refused"), - /** - * The stream to transfer the file is being negotiated over the chosen - * stream type. After the stream negotiating process is complete the - * status becomes negotiated. - * - * @see #negotiated - */ - negotiating_stream("Negotiating Stream"), + /** + * The stream to transfer the file is being negotiated over the chosen + * stream type. After the stream negotiating process is complete the + * status becomes negotiated. + * + * @see #negotiated + */ + negotiating_stream("Negotiating Stream"), - /** - * After the stream negotiation has completed the intermediate state - * between the time when the negotiation is finished and the actual - * transfer begins. - */ - negotiated("Negotiated"), + /** + * After the stream negotiation has completed the intermediate state + * between the time when the negotiation is finished and the actual + * transfer begins. + */ + negotiated("Negotiated"), - /** - * The transfer is in progress. - * - * @see FileTransfer#getProgress() - */ - in_progress("In Progress"), + /** + * The transfer is in progress. + * + * @see FileTransfer#getProgress() + */ + in_progress("In Progress"), - /** - * The transfer has completed successfully. - */ - complete("Complete"), + /** + * The transfer has completed successfully. + */ + complete("Complete"), - /** - * The file transfer was cancelled. - */ - cancelled("Cancelled"); + /** + * The file transfer was cancelled. + */ + cancelled("Cancelled"); - private String status; + private final String status; private Status(String status) { this.status = status; } + @Override public String toString() { return status; } @@ -312,55 +313,56 @@ public abstract class FileTransfer { } public enum Error { - /** - * No error. - */ - none("No error"), + /** + * No error. + */ + none("No error"), - /** - * The peer did not find any of the provided stream mechanisms - * acceptable. - */ - not_acceptable("The peer did not find any of the provided stream mechanisms acceptable."), + /** + * The peer did not find any of the provided stream mechanisms + * acceptable. + */ + not_acceptable("The peer did not find any of the provided stream mechanisms acceptable."), - /** - * The provided file to transfer does not exist or could not be read. - */ - bad_file("The provided file to transfer does not exist or could not be read."), + /** + * The provided file to transfer does not exist or could not be read. + */ + bad_file("The provided file to transfer does not exist or could not be read."), - /** - * The remote user did not respond or the connection timed out. - */ - no_response("The remote user did not respond or the connection timed out."), + /** + * The remote user did not respond or the connection timed out. + */ + no_response("The remote user did not respond or the connection timed out."), - /** - * An error occurred over the socket connected to send the file. - */ - connection("An error occured over the socket connected to send the file."), + /** + * An error occurred over the socket connected to send the file. + */ + connection("An error occured over the socket connected to send the file."), - /** - * An error occurred while sending or receiving the file. - */ - stream("An error occured while sending or recieving the file."); + /** + * An error occurred while sending or receiving the file. + */ + stream("An error occured while sending or recieving the file."); - private final String msg; + private final String msg; - private Error(String msg) { - this.msg = msg; - } + private Error(String msg) { + this.msg = msg; + } - /** - * Returns a String representation of this error. - * - * @return Returns a String representation of this error. - */ - public String getMessage() { - return msg; - } + /** + * Returns a String representation of this error. + * + * @return Returns a String representation of this error. + */ + public String getMessage() { + return msg; + } - public String toString() { - return msg; - } - } + @Override + public String toString() { + return msg; + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferListener.java index 179e3f930..cb1852afc 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferListener.java @@ -23,11 +23,11 @@ package org.jivesoftware.smackx.filetransfer; * @author Alexander Wenckus */ public interface FileTransferListener { - /** - * A request to send a file has been recieved from another user. - * - * @param request - * The request from the other user. - */ - public void fileTransferRequest(final FileTransferRequest request); + /** + * A request to send a file has been recieved from another user. + * + * @param request + * The request from the other user. + */ + public void fileTransferRequest(final FileTransferRequest request); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferManager.java index ac20d7171..78f397758 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferManager.java @@ -56,20 +56,20 @@ public final class FileTransferManager extends Manager { return fileTransferManager; } - private final FileTransferNegotiator fileTransferNegotiator; + private final FileTransferNegotiator fileTransferNegotiator; - private final List listeners = new CopyOnWriteArrayList(); + private final List listeners = new CopyOnWriteArrayList(); - /** - * Creates a file transfer manager to initiate and receive file transfers. - * - * @param connection - * The XMPPConnection that the file transfers will use. - */ - private FileTransferManager(XMPPConnection connection) { - super(connection); - this.fileTransferNegotiator = FileTransferNegotiator - .getInstanceFor(connection); + /** + * Creates a file transfer manager to initiate and receive file transfers. + * + * @param connection + * The XMPPConnection that the file transfers will use. + */ + private FileTransferManager(XMPPConnection connection) { + super(connection); + this.fileTransferNegotiator = FileTransferNegotiator + .getInstanceFor(connection); connection.registerIQRequestHandler(new AbstractIqRequestHandler(StreamInitiation.ELEMENT, StreamInitiation.NAMESPACE, IQ.Type.set, Mode.async) { @Override @@ -82,42 +82,42 @@ public final class FileTransferManager extends Manager { return null; } }); - } + } - /** - * Add a file transfer listener to listen to incoming file transfer - * requests. - * - * @param li - * The listener - * @see #removeFileTransferListener(FileTransferListener) - * @see FileTransferListener - */ - public void addFileTransferListener(final FileTransferListener li) { - listeners.add(li); - } + /** + * Add a file transfer listener to listen to incoming file transfer + * requests. + * + * @param li + * The listener + * @see #removeFileTransferListener(FileTransferListener) + * @see FileTransferListener + */ + public void addFileTransferListener(final FileTransferListener li) { + listeners.add(li); + } - /** - * Removes a file transfer listener. - * - * @param li - * The file transfer listener to be removed - * @see FileTransferListener - */ - public void removeFileTransferListener(final FileTransferListener li) { - listeners.remove(li); - } + /** + * Removes a file transfer listener. + * + * @param li + * The file transfer listener to be removed + * @see FileTransferListener + */ + public void removeFileTransferListener(final FileTransferListener li) { + listeners.remove(li); + } - /** - * Creates an OutgoingFileTransfer to send a file to another user. - * - * @param userID - * The fully qualified jabber ID (i.e. full JID) with resource of the user to - * send the file to. - * @return The send file object on which the negotiated transfer can be run. - * @exception IllegalArgumentException if userID is null or not a full JID - */ - public OutgoingFileTransfer createOutgoingFileTransfer(EntityFullJid userID) { + /** + * Creates an OutgoingFileTransfer to send a file to another user. + * + * @param userID + * The fully qualified jabber ID (i.e. full JID) with resource of the user to + * send the file to. + * @return The send file object on which the negotiated transfer can be run. + * @exception IllegalArgumentException if userID is null or not a full JID + */ + public OutgoingFileTransfer createOutgoingFileTransfer(EntityFullJid userID) { // We need to create outgoing file transfers with a full JID since this method will later // use XEP-0095 to negotiate the stream. This is done with IQ stanzas that need to be addressed to a full JID // in order to reach an client entity. @@ -125,45 +125,45 @@ public final class FileTransferManager extends Manager { throw new IllegalArgumentException("userID was null"); } - return new OutgoingFileTransfer(connection().getUser(), userID, - FileTransferNegotiator.getNextStreamID(), - fileTransferNegotiator); - } - - /** - * When the file transfer request is acceptable, this method should be - * invoked. It will create an IncomingFileTransfer which allows the - * transmission of the file to procede. - * - * @param request - * The remote request that is being accepted. - * @return The IncomingFileTransfer which manages the download of the file - * from the transfer initiator. - */ - protected IncomingFileTransfer createIncomingFileTransfer( - FileTransferRequest request) { - if (request == null) { - throw new NullPointerException("RecieveRequest cannot be null"); - } - - IncomingFileTransfer transfer = new IncomingFileTransfer(request, + return new OutgoingFileTransfer(connection().getUser(), userID, + FileTransferNegotiator.getNextStreamID(), fileTransferNegotiator); - transfer.setFileInfo(request.getFileName(), request.getFileSize()); + } - return transfer; - } + /** + * When the file transfer request is acceptable, this method should be + * invoked. It will create an IncomingFileTransfer which allows the + * transmission of the file to procede. + * + * @param request + * The remote request that is being accepted. + * @return The IncomingFileTransfer which manages the download of the file + * from the transfer initiator. + */ + protected IncomingFileTransfer createIncomingFileTransfer( + FileTransferRequest request) { + if (request == null) { + throw new NullPointerException("RecieveRequest cannot be null"); + } - /** - * Reject an incoming file transfer. - *

- * Specified in XEP-95 4.2 and 3.2 Example 8 - *

- * @param request - * @throws NotConnectedException - * @throws InterruptedException - */ - protected void rejectIncomingFileTransfer(FileTransferRequest request) throws NotConnectedException, InterruptedException { - StreamInitiation initiation = request.getStreamInitiation(); + IncomingFileTransfer transfer = new IncomingFileTransfer(request, + fileTransferNegotiator); + transfer.setFileInfo(request.getFileName(), request.getFileSize()); + + return transfer; + } + + /** + * Reject an incoming file transfer. + *

+ * Specified in XEP-95 4.2 and 3.2 Example 8 + *

+ * @param request + * @throws NotConnectedException + * @throws InterruptedException + */ + protected void rejectIncomingFileTransfer(FileTransferRequest request) throws NotConnectedException, InterruptedException { + StreamInitiation initiation = request.getStreamInitiation(); // Reject as specified in XEP-95 4.2. Note that this is not to be confused with the Socks 5 // Bytestream rejection as specified in XEP-65 5.3.1 Example 13, which says that @@ -172,5 +172,5 @@ public final class FileTransferManager extends Manager { IQ rejection = IQ.createErrorResponse(initiation, XMPPError.getBuilder( XMPPError.Condition.forbidden)); connection().sendStanza(rejection); - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferRequest.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferRequest.java index dd954642e..61e4e3934 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferRequest.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferRequest.java @@ -27,113 +27,113 @@ import org.jxmpp.jid.Jid; * */ public class FileTransferRequest { - private final StreamInitiation streamInitiation; + private final StreamInitiation streamInitiation; - private final FileTransferManager manager; + private final FileTransferManager manager; - /** - * A recieve request is constructed from the Stream Initiation request - * received from the initator. - * - * @param manager - * The manager handling this file transfer - * - * @param si - * The Stream initiaton recieved from the initiator. - */ - public FileTransferRequest(FileTransferManager manager, StreamInitiation si) { - this.streamInitiation = si; - this.manager = manager; - } + /** + * A recieve request is constructed from the Stream Initiation request + * received from the initator. + * + * @param manager + * The manager handling this file transfer + * + * @param si + * The Stream initiaton recieved from the initiator. + */ + public FileTransferRequest(FileTransferManager manager, StreamInitiation si) { + this.streamInitiation = si; + this.manager = manager; + } - /** - * Returns the name of the file. - * - * @return Returns the name of the file. - */ - public String getFileName() { - return streamInitiation.getFile().getName(); - } + /** + * Returns the name of the file. + * + * @return Returns the name of the file. + */ + public String getFileName() { + return streamInitiation.getFile().getName(); + } - /** - * Returns the size in bytes of the file. - * - * @return Returns the size in bytes of the file. - */ - public long getFileSize() { - return streamInitiation.getFile().getSize(); - } + /** + * Returns the size in bytes of the file. + * + * @return Returns the size in bytes of the file. + */ + public long getFileSize() { + return streamInitiation.getFile().getSize(); + } - /** - * Returns the description of the file provided by the requestor. - * - * @return Returns the description of the file provided by the requestor. - */ - public String getDescription() { - return streamInitiation.getFile().getDesc(); - } + /** + * Returns the description of the file provided by the requestor. + * + * @return Returns the description of the file provided by the requestor. + */ + public String getDescription() { + return streamInitiation.getFile().getDesc(); + } - /** - * Returns the mime-type of the file. - * - * @return Returns the mime-type of the file. - */ - public String getMimeType() { - return streamInitiation.getMimeType(); - } + /** + * Returns the mime-type of the file. + * + * @return Returns the mime-type of the file. + */ + public String getMimeType() { + return streamInitiation.getMimeType(); + } - /** - * Returns the fully-qualified jabber ID of the user that requested this - * file transfer. - * - * @return Returns the fully-qualified jabber ID of the user that requested - * this file transfer. - */ - public Jid getRequestor() { - return streamInitiation.getFrom(); - } + /** + * Returns the fully-qualified jabber ID of the user that requested this + * file transfer. + * + * @return Returns the fully-qualified jabber ID of the user that requested + * this file transfer. + */ + public Jid getRequestor() { + return streamInitiation.getFrom(); + } - /** - * Returns the stream ID that uniquely identifies this file transfer. - * - * @return Returns the stream ID that uniquely identifies this file - * transfer. - */ - public String getStreamID() { - return streamInitiation.getSessionID(); - } + /** + * Returns the stream ID that uniquely identifies this file transfer. + * + * @return Returns the stream ID that uniquely identifies this file + * transfer. + */ + public String getStreamID() { + return streamInitiation.getSessionID(); + } - /** - * Returns the stream initiation stanza(/packet) that was sent by the requestor which - * contains the parameters of the file transfer being transfer and also the - * methods available to transfer the file. - * - * @return Returns the stream initiation stanza(/packet) that was sent by the - * requestor which contains the parameters of the file transfer - * being transfer and also the methods available to transfer the - * file. - */ - protected StreamInitiation getStreamInitiation() { - return streamInitiation; - } + /** + * Returns the stream initiation stanza(/packet) that was sent by the requestor which + * contains the parameters of the file transfer being transfer and also the + * methods available to transfer the file. + * + * @return Returns the stream initiation stanza(/packet) that was sent by the + * requestor which contains the parameters of the file transfer + * being transfer and also the methods available to transfer the + * file. + */ + protected StreamInitiation getStreamInitiation() { + return streamInitiation; + } - /** - * Accepts this file transfer and creates the incoming file transfer. - * - * @return Returns the IncomingFileTransfer on which the - * file transfer can be carried out. - */ - public IncomingFileTransfer accept() { - return manager.createIncomingFileTransfer(this); - } + /** + * Accepts this file transfer and creates the incoming file transfer. + * + * @return Returns the IncomingFileTransfer on which the + * file transfer can be carried out. + */ + public IncomingFileTransfer accept() { + return manager.createIncomingFileTransfer(this); + } - /** - * Rejects the file transfer request. - * @throws NotConnectedException - * @throws InterruptedException - */ - public void reject() throws NotConnectedException, InterruptedException { - manager.rejectIncomingFileTransfer(this); - } + /** + * Rejects the file transfer request. + * @throws NotConnectedException + * @throws InterruptedException + */ + public void reject() throws NotConnectedException, InterruptedException { + manager.rejectIncomingFileTransfer(this); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IBBTransferNegotiator.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IBBTransferNegotiator.java index 27d63571c..2e28455fa 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IBBTransferNegotiator.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IBBTransferNegotiator.java @@ -58,6 +58,7 @@ public class IBBTransferNegotiator extends StreamNegotiator { this.manager = InBandBytestreamManager.getByteStreamManager(connection); } + @Override public OutputStream createOutgoingStream(String streamID, Jid initiator, Jid target) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { InBandBytestreamSession session = this.manager.establishSession(target, streamID); @@ -65,6 +66,7 @@ public class IBBTransferNegotiator extends StreamNegotiator { return session.getOutputStream(); } + @Override public InputStream createIncomingStream(StreamInitiation initiation) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { /* @@ -87,10 +89,12 @@ public class IBBTransferNegotiator extends StreamNegotiator { this.manager.ignoreBytestreamRequestOnce(streamID); } + @Override public String[] getNamespaces() { return new String[] { DataPacketExtension.NAMESPACE }; } + @Override InputStream negotiateIncomingStream(Stanza streamInitiation) throws NotConnectedException, InterruptedException { // build In-Band Bytestream request InBandBytestreamRequest request = new ByteStreamRequest(this.manager, diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java index 2783e6910..6e4afef41 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java @@ -126,6 +126,7 @@ public class IncomingFileTransfer extends FileTransfer { } Thread transferThread = new Thread(new Runnable() { + @Override public void run() { try { inputStream = negotiateStream(); @@ -184,6 +185,7 @@ public class IncomingFileTransfer extends FileTransfer { FutureTask streamNegotiatorTask = new FutureTask( new Callable() { + @Override public InputStream call() throws Exception { return streamNegotiator .createIncomingStream(recieveRequest.getStreamInitiation()); @@ -220,6 +222,7 @@ public class IncomingFileTransfer extends FileTransfer { return inputStream; } + @Override public void cancel() { setStatus(Status.cancelled); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java index c8eaf8cf9..ce2d0ae91 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java @@ -43,7 +43,7 @@ import org.jxmpp.jid.Jid; public class OutgoingFileTransfer extends FileTransfer { private static final Logger LOGGER = Logger.getLogger(OutgoingFileTransfer.class.getName()); - private static int RESPONSE_TIMEOUT = 60 * 1000; + private static int RESPONSE_TIMEOUT = 60 * 1000; private NegotiationProgress callback; /** @@ -58,349 +58,353 @@ public class OutgoingFileTransfer extends FileTransfer { return RESPONSE_TIMEOUT; } - /** - * Sets the time in milliseconds after which the file transfer negotiation - * process will timeout if the other user has not responded. - * - * @param responseTimeout - * The timeout time in milliseconds. - */ - public static void setResponseTimeout(int responseTimeout) { - RESPONSE_TIMEOUT = responseTimeout; - } + /** + * Sets the time in milliseconds after which the file transfer negotiation + * process will timeout if the other user has not responded. + * + * @param responseTimeout + * The timeout time in milliseconds. + */ + public static void setResponseTimeout(int responseTimeout) { + RESPONSE_TIMEOUT = responseTimeout; + } - private OutputStream outputStream; + private OutputStream outputStream; - private Jid initiator; + private Jid initiator; - private Thread transferThread; + private Thread transferThread; - protected OutgoingFileTransfer(Jid initiator, Jid target, - String streamID, FileTransferNegotiator transferNegotiator) { - super(target, streamID, transferNegotiator); - this.initiator = initiator; - } + protected OutgoingFileTransfer(Jid initiator, Jid target, + String streamID, FileTransferNegotiator transferNegotiator) { + super(target, streamID, transferNegotiator); + this.initiator = initiator; + } - protected void setOutputStream(OutputStream stream) { - if (outputStream == null) { - this.outputStream = stream; - } - } + protected void setOutputStream(OutputStream stream) { + if (outputStream == null) { + this.outputStream = stream; + } + } - /** - * Returns the output stream connected to the peer to transfer the file. It - * is only available after it has been successfully negotiated by the - * {@link StreamNegotiator}. - * - * @return Returns the output stream connected to the peer to transfer the - * file. - */ - protected OutputStream getOutputStream() { - if (getStatus().equals(FileTransfer.Status.negotiated)) { - return outputStream; - } else { - return null; - } - } + /** + * Returns the output stream connected to the peer to transfer the file. It + * is only available after it has been successfully negotiated by the + * {@link StreamNegotiator}. + * + * @return Returns the output stream connected to the peer to transfer the + * file. + */ + protected OutputStream getOutputStream() { + if (getStatus().equals(FileTransfer.Status.negotiated)) { + return outputStream; + } else { + return null; + } + } - /** - * This method handles the negotiation of the file transfer and the stream, - * it only returns the created stream after the negotiation has been completed. - * - * @param fileName - * The name of the file that will be transmitted. It is - * preferable for this name to have an extension as it will be - * used to determine the type of file it is. - * @param fileSize - * The size in bytes of the file that will be transmitted. - * @param description - * A description of the file that will be transmitted. - * @return The OutputStream that is connected to the peer to transmit the - * file. - * @throws XMPPException - * Thrown if an error occurs during the file transfer - * negotiation process. - * @throws SmackException if there was no response from the server. - * @throws InterruptedException - */ - public synchronized OutputStream sendFile(String fileName, long fileSize, - String description) throws XMPPException, SmackException, InterruptedException { - if (isDone() || outputStream != null) { - throw new IllegalStateException( - "The negotation process has already" - + " been attempted on this file transfer"); - } - try { - setFileInfo(fileName, fileSize); - this.outputStream = negotiateStream(fileName, fileSize, description); - } catch (XMPPErrorException e) { - handleXMPPException(e); - throw e; - } - return outputStream; - } + /** + * This method handles the negotiation of the file transfer and the stream, + * it only returns the created stream after the negotiation has been completed. + * + * @param fileName + * The name of the file that will be transmitted. It is + * preferable for this name to have an extension as it will be + * used to determine the type of file it is. + * @param fileSize + * The size in bytes of the file that will be transmitted. + * @param description + * A description of the file that will be transmitted. + * @return The OutputStream that is connected to the peer to transmit the + * file. + * @throws XMPPException + * Thrown if an error occurs during the file transfer + * negotiation process. + * @throws SmackException if there was no response from the server. + * @throws InterruptedException + */ + public synchronized OutputStream sendFile(String fileName, long fileSize, + String description) throws XMPPException, SmackException, InterruptedException { + if (isDone() || outputStream != null) { + throw new IllegalStateException( + "The negotation process has already" + + " been attempted on this file transfer"); + } + try { + setFileInfo(fileName, fileSize); + this.outputStream = negotiateStream(fileName, fileSize, description); + } catch (XMPPErrorException e) { + handleXMPPException(e); + throw e; + } + return outputStream; + } - /** - * This methods handles the transfer and stream negotiation process. It - * returns immediately and its progress will be updated through the - * {@link NegotiationProgress} callback. - * - * @param fileName - * The name of the file that will be transmitted. It is - * preferable for this name to have an extension as it will be - * used to determine the type of file it is. - * @param fileSize - * The size in bytes of the file that will be transmitted. - * @param description - * A description of the file that will be transmitted. - * @param progress - * A callback to monitor the progress of the file transfer - * negotiation process and to retrieve the OutputStream when it - * is complete. - */ - public synchronized void sendFile(final String fileName, - final long fileSize, final String description, - final NegotiationProgress progress) + /** + * This methods handles the transfer and stream negotiation process. It + * returns immediately and its progress will be updated through the + * {@link NegotiationProgress} callback. + * + * @param fileName + * The name of the file that will be transmitted. It is + * preferable for this name to have an extension as it will be + * used to determine the type of file it is. + * @param fileSize + * The size in bytes of the file that will be transmitted. + * @param description + * A description of the file that will be transmitted. + * @param progress + * A callback to monitor the progress of the file transfer + * negotiation process and to retrieve the OutputStream when it + * is complete. + */ + public synchronized void sendFile(final String fileName, + final long fileSize, final String description, + final NegotiationProgress progress) { if(progress == null) { throw new IllegalArgumentException("Callback progress cannot be null."); } checkTransferThread(); - if (isDone() || outputStream != null) { - throw new IllegalStateException( - "The negotation process has already" - + " been attempted for this file transfer"); - } + if (isDone() || outputStream != null) { + throw new IllegalStateException( + "The negotation process has already" + + " been attempted for this file transfer"); + } setFileInfo(fileName, fileSize); this.callback = progress; transferThread = new Thread(new Runnable() { - public void run() { - try { - OutgoingFileTransfer.this.outputStream = negotiateStream( - fileName, fileSize, description); + @Override + public void run() { + try { + OutgoingFileTransfer.this.outputStream = negotiateStream( + fileName, fileSize, description); progress.outputStreamEstablished(OutgoingFileTransfer.this.outputStream); } catch (XMPPErrorException e) { - handleXMPPException(e); - } + handleXMPPException(e); + } catch (Exception e) { setException(e); } - } - }, "File Transfer Negotiation " + streamID); - transferThread.start(); - } + } + }, "File Transfer Negotiation " + streamID); + transferThread.start(); + } - private void checkTransferThread() { - if (transferThread != null && transferThread.isAlive() || isDone()) { - throw new IllegalStateException( - "File transfer in progress or has already completed."); - } - } + private void checkTransferThread() { + if ((transferThread != null && transferThread.isAlive()) || isDone()) { + throw new IllegalStateException( + "File transfer in progress or has already completed."); + } + } /** - * This method handles the stream negotiation process and transmits the file - * to the remote user. It returns immediately and the progress of the file - * transfer can be monitored through several methods: - * - *
    - *
  • {@link FileTransfer#getStatus()} - *
  • {@link FileTransfer#getProgress()} - *
  • {@link FileTransfer#isDone()} - *
- * + * This method handles the stream negotiation process and transmits the file + * to the remote user. It returns immediately and the progress of the file + * transfer can be monitored through several methods: + * + *
    + *
  • {@link FileTransfer#getStatus()} + *
  • {@link FileTransfer#getProgress()} + *
  • {@link FileTransfer#isDone()} + *
+ * * @param file the file to transfer to the remote entity. * @param description a description for the file to transfer. - * @throws SmackException - * If there is an error during the negotiation process or the - * sending of the file. - */ - public synchronized void sendFile(final File file, final String description) - throws SmackException { - checkTransferThread(); - if (file == null || !file.exists() || !file.canRead()) { - throw new IllegalArgumentException("Could not read file"); - } else { - setFileInfo(file.getAbsolutePath(), file.getName(), file.length()); - } + * @throws SmackException + * If there is an error during the negotiation process or the + * sending of the file. + */ + public synchronized void sendFile(final File file, final String description) + throws SmackException { + checkTransferThread(); + if (file == null || !file.exists() || !file.canRead()) { + throw new IllegalArgumentException("Could not read file"); + } else { + setFileInfo(file.getAbsolutePath(), file.getName(), file.length()); + } - transferThread = new Thread(new Runnable() { - public void run() { - try { - outputStream = negotiateStream(file.getName(), file - .length(), description); - } catch (XMPPErrorException e) { - handleXMPPException(e); - return; - } + transferThread = new Thread(new Runnable() { + @Override + public void run() { + try { + outputStream = negotiateStream(file.getName(), file + .length(), description); + } catch (XMPPErrorException e) { + handleXMPPException(e); + return; + } catch (Exception e) { setException(e); } - if (outputStream == null) { - return; - } + if (outputStream == null) { + return; + } if (!updateStatus(Status.negotiated, Status.in_progress)) { - return; - } + return; + } - InputStream inputStream = null; - try { - inputStream = new FileInputStream(file); - writeToStream(inputStream, outputStream); - } catch (FileNotFoundException e) { - setStatus(FileTransfer.Status.error); - setError(Error.bad_file); - setException(e); - } catch (IOException e) { - setStatus(FileTransfer.Status.error); - setException(e); - } finally { - if (inputStream != null) { - try { + InputStream inputStream = null; + try { + inputStream = new FileInputStream(file); + writeToStream(inputStream, outputStream); + } catch (FileNotFoundException e) { + setStatus(FileTransfer.Status.error); + setError(Error.bad_file); + setException(e); + } catch (IOException e) { + setStatus(FileTransfer.Status.error); + setException(e); + } finally { + if (inputStream != null) { + try { inputStream.close(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Closing input stream", e); } - } + } - try { + try { outputStream.close(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Closing output stream", e); } - } + } updateStatus(Status.in_progress, FileTransfer.Status.complete); - } + } - }, "File Transfer " + streamID); - transferThread.start(); - } + }, "File Transfer " + streamID); + transferThread.start(); + } /** - * This method handles the stream negotiation process and transmits the file - * to the remote user. It returns immediately and the progress of the file - * transfer can be monitored through several methods: - * - *
    - *
  • {@link FileTransfer#getStatus()} - *
  • {@link FileTransfer#getProgress()} - *
  • {@link FileTransfer#isDone()} - *
- * + * This method handles the stream negotiation process and transmits the file + * to the remote user. It returns immediately and the progress of the file + * transfer can be monitored through several methods: + * + *
    + *
  • {@link FileTransfer#getStatus()} + *
  • {@link FileTransfer#getProgress()} + *
  • {@link FileTransfer#isDone()} + *
+ * * @param in the stream to transfer to the remote entity. * @param fileName the name of the file that is transferred * @param fileSize the size of the file that is transferred * @param description a description for the file to transfer. - */ - public synchronized void sendStream(final InputStream in, final String fileName, final long fileSize, final String description){ - checkTransferThread(); + */ + public synchronized void sendStream(final InputStream in, final String fileName, final long fileSize, final String description){ + checkTransferThread(); - setFileInfo(fileName, fileSize); - transferThread = new Thread(new Runnable() { - public void run() { + setFileInfo(fileName, fileSize); + transferThread = new Thread(new Runnable() { + @Override + public void run() { //Create packet filter try { - outputStream = negotiateStream(fileName, fileSize, description); - } catch (XMPPErrorException e) { - handleXMPPException(e); - return; - } + outputStream = negotiateStream(fileName, fileSize, description); + } catch (XMPPErrorException e) { + handleXMPPException(e); + return; + } catch (Exception e) { setException(e); } - if (outputStream == null) { - return; - } + if (outputStream == null) { + return; + } if (!updateStatus(Status.negotiated, Status.in_progress)) { - return; - } - try { - writeToStream(in, outputStream); - } catch (IOException e) { - setStatus(FileTransfer.Status.error); - setException(e); - } finally { - try { - if (in != null) { - in.close(); - } + return; + } + try { + writeToStream(in, outputStream); + } catch (IOException e) { + setStatus(FileTransfer.Status.error); + setException(e); + } finally { + try { + if (in != null) { + in.close(); + } - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { + outputStream.flush(); + outputStream.close(); + } catch (IOException e) { /* Do Nothing */ - } - } + } + } updateStatus(Status.in_progress, FileTransfer.Status.complete); - } + } - }, "File Transfer " + streamID); - transferThread.start(); - } + }, "File Transfer " + streamID); + transferThread.start(); + } - private void handleXMPPException(XMPPErrorException e) { - XMPPError error = e.getXMPPError(); - if (error != null) { - switch (error.getCondition()) { - case forbidden: - setStatus(Status.refused); - return; - case bad_request: - setStatus(Status.error); - setError(Error.not_acceptable); - break; + private void handleXMPPException(XMPPErrorException e) { + XMPPError error = e.getXMPPError(); + if (error != null) { + switch (error.getCondition()) { + case forbidden: + setStatus(Status.refused); + return; + case bad_request: + setStatus(Status.error); + setError(Error.not_acceptable); + break; default: setStatus(FileTransfer.Status.error); } } setException(e); - } + } - /** - * Returns the amount of bytes that have been sent for the file transfer. Or - * -1 if the file transfer has not started. - *

- * Note: This method is only useful when the {@link #sendFile(File, String)} - * method is called, as it is the only method that actually transmits the - * file. - * - * @return Returns the amount of bytes that have been sent for the file - * transfer. Or -1 if the file transfer has not started. - */ - public long getBytesSent() { - return amountWritten; - } + /** + * Returns the amount of bytes that have been sent for the file transfer. Or + * -1 if the file transfer has not started. + *

+ * Note: This method is only useful when the {@link #sendFile(File, String)} + * method is called, as it is the only method that actually transmits the + * file. + * + * @return Returns the amount of bytes that have been sent for the file + * transfer. Or -1 if the file transfer has not started. + */ + public long getBytesSent() { + return amountWritten; + } - private OutputStream negotiateStream(String fileName, long fileSize, - String description) throws SmackException, XMPPException, InterruptedException { - // Negotiate the file transfer profile + private OutputStream negotiateStream(String fileName, long fileSize, + String description) throws SmackException, XMPPException, InterruptedException { + // Negotiate the file transfer profile if (!updateStatus(Status.initial, Status.negotiating_transfer)) { throw new IllegalStateChangeException(); } - StreamNegotiator streamNegotiator = negotiator.negotiateOutgoingTransfer( - getPeer(), streamID, fileName, fileSize, description, - RESPONSE_TIMEOUT); + StreamNegotiator streamNegotiator = negotiator.negotiateOutgoingTransfer( + getPeer(), streamID, fileName, fileSize, description, + RESPONSE_TIMEOUT); // Negotiate the stream if (!updateStatus(Status.negotiating_transfer, Status.negotiating_stream)) { throw new IllegalStateChangeException(); } - outputStream = streamNegotiator.createOutgoingStream(streamID, + outputStream = streamNegotiator.createOutgoingStream(streamID, initiator, getPeer()); if (!updateStatus(Status.negotiating_stream, Status.negotiated)) { throw new IllegalStateChangeException(); - } - return outputStream; - } + } + return outputStream; + } - public void cancel() { - setStatus(Status.cancelled); - } + @Override + public void cancel() { + setStatus(Status.cancelled); + } @Override protected boolean updateStatus(Status oldStatus, Status newStatus) { @@ -429,30 +433,30 @@ public class OutgoingFileTransfer extends FileTransfer { } /** - * A callback class to retrieve the status of an outgoing transfer - * negotiation process. - * - * @author Alexander Wenckus - * - */ - public interface NegotiationProgress { + * A callback class to retrieve the status of an outgoing transfer + * negotiation process. + * + * @author Alexander Wenckus + * + */ + public interface NegotiationProgress { - /** - * Called when the status changes. + /** + * Called when the status changes. * * @param oldStatus the previous status of the file transfer. * @param newStatus the new status of the file transfer. */ - void statusUpdated(Status oldStatus, Status newStatus); + void statusUpdated(Status oldStatus, Status newStatus); - /** - * Once the negotiation process is completed the output stream can be - * retrieved. + /** + * Once the negotiation process is completed the output stream can be + * retrieved. * * @param stream the established stream which can be used to transfer the file to the remote * entity - */ - void outputStreamEstablished(OutputStream stream); + */ + void outputStreamEstablished(OutputStream stream); /** * Called when an exception occurs during the negotiation progress. diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/geoloc/GeoLocationManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/geoloc/GeoLocationManager.java index f3ada0e69..89021126c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/geoloc/GeoLocationManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/geoloc/GeoLocationManager.java @@ -34,6 +34,7 @@ public final class GeoLocationManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqlast/LastActivityManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqlast/LastActivityManager.java index b49051ce8..0d9a11cfb 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqlast/LastActivityManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqlast/LastActivityManager.java @@ -108,6 +108,7 @@ public final class LastActivityManager extends Manager { // Enable the LastActivity support on every established connection static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { LastActivityManager.getInstanceFor(connection); } @@ -135,6 +136,7 @@ public final class LastActivityManager extends Manager { // Listen to all the sent messages to reset the idle time on each one connection.addPacketSendingListener(new StanzaListener() { + @Override public void processStanza(Stanza packet) { Presence presence = (Presence) packet; Presence.Mode mode = presence.getMode(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/packet/DefaultPrivateData.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/packet/DefaultPrivateData.java index 02a208452..83474b3c3 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/packet/DefaultPrivateData.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/packet/DefaultPrivateData.java @@ -66,6 +66,7 @@ public class DefaultPrivateData implements PrivateData { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return elementName; } @@ -75,10 +76,12 @@ public class DefaultPrivateData implements PrivateData { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return namespace; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(elementName).append(" xmlns=\"").append(namespace).append("\">"); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/provider/RegistrationProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/provider/RegistrationProvider.java index bf3aa34e0..f4063c5a8 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/provider/RegistrationProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/provider/RegistrationProvider.java @@ -71,6 +71,6 @@ public class RegistrationProvider extends IQProvider { Registration registration = new Registration(instruction, fields); registration.addExtensions(packetExtensions); return registration; - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqversion/VersionManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqversion/VersionManager.java index 202a084dc..a6797315a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/iqversion/VersionManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/iqversion/VersionManager.java @@ -71,6 +71,7 @@ public final class VersionManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { VersionManager.getInstanceFor(connection); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultParticipantStatusListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultParticipantStatusListener.java index 6cf4de52c..baf836557 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultParticipantStatusListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultParticipantStatusListener.java @@ -32,48 +32,63 @@ import org.jxmpp.jid.parts.Resourcepart; */ public class DefaultParticipantStatusListener implements ParticipantStatusListener { + @Override public void joined(EntityFullJid participant) { } + @Override public void left(EntityFullJid participant) { } + @Override public void kicked(EntityFullJid participant, Jid actor, String reason) { } + @Override public void voiceGranted(EntityFullJid participant) { } + @Override public void voiceRevoked(EntityFullJid participant) { } + @Override public void banned(EntityFullJid participant, Jid actor, String reason) { } + @Override public void membershipGranted(EntityFullJid participant) { } + @Override public void membershipRevoked(EntityFullJid participant) { } + @Override public void moderatorGranted(EntityFullJid participant) { } + @Override public void moderatorRevoked(EntityFullJid participant) { } + @Override public void ownershipGranted(EntityFullJid participant) { } + @Override public void ownershipRevoked(EntityFullJid participant) { } + @Override public void adminGranted(EntityFullJid participant) { } + @Override public void adminRevoked(EntityFullJid participant) { } + @Override public void nicknameChanged(EntityFullJid participant, Resourcepart newNickname) { } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultUserStatusListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultUserStatusListener.java index 021f16d8e..9b0d71108 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultUserStatusListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/DefaultUserStatusListener.java @@ -30,42 +30,55 @@ import org.jxmpp.jid.Jid; */ public class DefaultUserStatusListener implements UserStatusListener { + @Override public void kicked(Jid actor, String reason) { } + @Override public void voiceGranted() { } + @Override public void voiceRevoked() { } + @Override public void banned(Jid actor, String reason) { } + @Override public void membershipGranted() { } + @Override public void membershipRevoked() { } + @Override public void moderatorGranted() { } + @Override public void moderatorRevoked() { } + @Override public void ownershipGranted() { } + @Override public void ownershipRevoked() { } + @Override public void adminGranted() { } + @Override public void adminRevoked() { } + @Override public void roomDestroyed(MultiUserChat alternateMUC, String reason) { } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/InvitationListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/InvitationListener.java index 4c9289050..8b1ead939 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/InvitationListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/InvitationListener.java @@ -20,7 +20,7 @@ package org.jivesoftware.smackx.muc; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smackx.muc.packet.MUCUser; -import org.jxmpp.jid.EntityFullJid; +import org.jxmpp.jid.EntityJid; /** * A listener that is fired anytime an invitation to join a MUC room is received. @@ -43,7 +43,7 @@ public interface InvitationListener { * @param message the message used by the inviter to send the invitation. * @param invitation the raw invitation received with the message. */ - public abstract void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityFullJid inviter, String reason, + public abstract void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityJid inviter, String reason, String password, Message message, MUCUser.Invite invitation); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MucEnterConfiguration.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MucEnterConfiguration.java index 93ba18392..a08604a4f 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MucEnterConfiguration.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MucEnterConfiguration.java @@ -95,15 +95,16 @@ public final class MucEnterConfiguration { /** * Set the presence used to join the MUC room. *

- * The 'to' value of the given presence will be overridden. + * The 'to' value of the given presence will be overridden and the given presence must be of type + * 'available', otherwise an {@link IllegalArgumentException} will be thrown. *

* * @param presence * @return a reference to this builder. */ public Builder withPresence(Presence presence) { - if (presence.getType() == Presence.Type.available) { - throw new IllegalArgumentException(); + if (presence.getType() != Presence.Type.available) { + throw new IllegalArgumentException("Presence must be of type 'available'"); } joinPresence = presence; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java index ea823accc..3d240756e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java @@ -46,7 +46,7 @@ import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.filter.StanzaExtensionFilter; import org.jivesoftware.smack.filter.StanzaTypeFilter; -import org.jivesoftware.smack.filter.ToFilter; +import org.jivesoftware.smack.filter.ToMatchesFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Stanza; @@ -163,6 +163,7 @@ public class MultiUserChat { // Create a listener for subject updates. subjectListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { Message msg = (Message) packet; EntityFullJid from = msg.getFrom().asEntityFullJidIfPossible(); @@ -181,6 +182,7 @@ public class MultiUserChat { // Create a listener for all presence updates. presenceListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { Presence presence = (Presence) packet; final EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible(); @@ -251,6 +253,7 @@ public class MultiUserChat { // Listens for all messages that include a MUCUser extension and fire the invitation // rejection listeners if the message includes an invitation rejection. declinesListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { Message message = (Message) packet; // Get the MUC User extension @@ -319,7 +322,7 @@ public class MultiUserChat { connection.addSyncStanzaListener(subjectListener, new AndFilter(fromRoomFilter, MessageWithSubjectFilter.INSTANCE, new NotFilter(MessageTypeFilter.ERROR))); connection.addSyncStanzaListener(declinesListener, DECLINE_FILTER); - connection.addPacketInterceptor(presenceInterceptor, new AndFilter(new ToFilter(room), + connection.addPacketInterceptor(presenceInterceptor, new AndFilter(ToMatchesFilter.create(room), StanzaTypeFilter.PRESENCE)); messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter); @@ -331,7 +334,7 @@ public class MultiUserChat { try { presence = connection.createStanzaCollectorAndSend(responseFilter, joinPresence).nextResultOrThrow(conf.getTimeout()); } - catch (InterruptedException | NoResponseException | XMPPErrorException e) { + catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) { // Ensure that all callbacks are removed if there is an exception removeConnectionCallbacks(); throw e; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java index ae6556cbd..8a8b5e069 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2014-2016 Florian Schmaus + * Copyright © 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,6 @@ import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceExceptio import org.jivesoftware.smackx.muc.packet.MUCInitialPresence; import org.jivesoftware.smackx.muc.packet.MUCUser; import org.jxmpp.jid.EntityBareJid; -import org.jxmpp.jid.EntityFullJid; import org.jxmpp.jid.DomainBareJid; import org.jxmpp.jid.Jid; import org.jxmpp.jid.parts.Resourcepart; @@ -83,6 +82,7 @@ public final class MultiUserChatManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(final XMPPConnection connection) { // Set on every established connection that this client supports the Multi-User // Chat protocol. This information will be used when another client tries to @@ -150,6 +150,7 @@ public final class MultiUserChatManager extends Manager { // Listens for all messages that include a MUCUser extension and fire the invitation // listeners if the message includes an invitation. StanzaListener invitationPacketListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { final Message message = (Message) packet; // Get the MUCUser extension @@ -165,7 +166,7 @@ public final class MultiUserChatManager extends Manager { final MultiUserChat muc = getMultiUserChat(mucJid); final XMPPConnection connection = connection(); final MUCUser.Invite invite = mucUser.getInvite(); - final EntityFullJid from = invite.getFrom(); + final EntityJid from = invite.getFrom(); final String reason = invite.getReason(); final String password = mucUser.getPassword(); for (final InvitationListener listener : invitationsListeners) { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/Occupant.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/Occupant.java index b7bde0c58..044a027e2 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/Occupant.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/Occupant.java @@ -110,6 +110,7 @@ public class Occupant { return nick; } + @Override public boolean equals(Object obj) { if(!(obj instanceof Occupant)) { return false; @@ -118,6 +119,7 @@ public class Occupant { return jid.equals(occupant.jid); } + @Override public int hashCode() { int result; result = affiliation.hashCode(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/GroupChatInvitation.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/GroupChatInvitation.java index dfd327296..d445769cc 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/GroupChatInvitation.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/GroupChatInvitation.java @@ -92,10 +92,12 @@ public class GroupChatInvitation implements ExtensionElement { return roomAddress; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCInitialPresence.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCInitialPresence.java index 6482971fb..e6510987c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCInitialPresence.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCInitialPresence.java @@ -72,10 +72,12 @@ public class MUCInitialPresence implements ExtensionElement { } } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } @@ -282,6 +284,7 @@ public class MUCInitialPresence implements ExtensionElement { this.since = since; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); xml.optIntAttribute("maxchars", getMaxChars()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCItem.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCItem.java index 9cbc6cd3a..05ef5aea9 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCItem.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCItem.java @@ -158,6 +158,7 @@ public class MUCItem implements NamedElement { return role; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); xml.optAttribute("affiliation", getAffiliation()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCUser.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCUser.java index e8dcdd5e1..ac476a7d2 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCUser.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/packet/MUCUser.java @@ -29,6 +29,7 @@ import org.jivesoftware.smack.packet.ExtensionElement; import org.jivesoftware.smack.util.XmlStringBuilder; import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.EntityFullJid; +import org.jxmpp.jid.EntityJid; /** * Represents extended presence information about roles, affiliations, full JIDs, @@ -49,10 +50,12 @@ public class MUCUser implements ExtensionElement { private String password; private Destroy destroy; + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } @@ -247,7 +250,12 @@ public class MUCUser implements ExtensionElement { public static final String ELEMENT ="invite"; private final String reason; - private final EntityFullJid from; + + /** + * From XEP-0045 § 7.8.2: "… whose value is the bare JID, full JID, or occupant JID of the inviter …" + */ + private final EntityJid from; + private final EntityBareJid to; public Invite(String reason, EntityFullJid from) { @@ -258,7 +266,7 @@ public class MUCUser implements ExtensionElement { this(reason, null, to); } - public Invite(String reason, EntityFullJid from, EntityBareJid to) { + public Invite(String reason, EntityJid from, EntityBareJid to) { this.reason = reason; this.from = from; this.to = to; @@ -270,7 +278,7 @@ public class MUCUser implements ExtensionElement { * * @return the room's occupant that sent the invitation. */ - public EntityFullJid getFrom() { + public EntityJid getFrom() { return from; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/provider/MUCUserProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/provider/MUCUserProvider.java index 638145e20..787be13b6 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/provider/MUCUserProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/provider/MUCUserProvider.java @@ -24,7 +24,7 @@ import org.jivesoftware.smack.provider.ExtensionElementProvider; import org.jivesoftware.smack.util.ParserUtils; import org.jivesoftware.smackx.muc.packet.MUCUser; import org.jxmpp.jid.EntityBareJid; -import org.jxmpp.jid.EntityFullJid; +import org.jxmpp.jid.EntityJid; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; @@ -86,7 +86,7 @@ public class MUCUserProvider extends ExtensionElementProvider { private static MUCUser.Invite parseInvite(XmlPullParser parser) throws XmlPullParserException, IOException { String reason = null; EntityBareJid to = ParserUtils.getBareJidAttribute(parser, "to"); - EntityFullJid from = ParserUtils.getFullJidAttribute(parser, "from"); + EntityJid from = ParserUtils.getEntityJidAttribute(parser, "from"); outerloop: while (true) { int eventType = parser.next(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/nick/packet/Nick.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/nick/packet/Nick.java index 0038dd0a4..a88d54d5c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/nick/packet/Nick.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/nick/packet/Nick.java @@ -31,77 +31,80 @@ import org.xmlpull.v1.XmlPullParserException; */ public class Nick implements ExtensionElement { - public static final String NAMESPACE = "http://jabber.org/protocol/nick"; + public static final String NAMESPACE = "http://jabber.org/protocol/nick"; - public static final String ELEMENT_NAME = "nick"; + public static final String ELEMENT_NAME = "nick"; - private String name = null; + private String name = null; - public Nick(String name) { - this.name = name; - } + public Nick(String name) { + this.name = name; + } - /** - * The value of this nickname. - * - * @return the nickname - */ - public String getName() { - return name; - } + /** + * The value of this nickname. + * + * @return the nickname + */ + public String getName() { + return name; + } - /** - * Sets the value of this nickname. - * - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * Sets the value of this nickname. + * + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /* - * (non-Javadoc) - * - * @see org.jivesoftware.smack.packet.PacketExtension#getElementName() - */ - public String getElementName() { - return ELEMENT_NAME; - } + /* + * (non-Javadoc) + * + * @see org.jivesoftware.smack.packet.PacketExtension#getElementName() + */ + @Override + public String getElementName() { + return ELEMENT_NAME; + } - /* - * (non-Javadoc) - * - * @see org.jivesoftware.smack.packet.PacketExtension#getNamespace() - */ - public String getNamespace() { - return NAMESPACE; - } + /* + * (non-Javadoc) + * + * @see org.jivesoftware.smack.packet.PacketExtension#getNamespace() + */ + @Override + public String getNamespace() { + return NAMESPACE; + } - /* - * (non-Javadoc) - * - * @see org.jivesoftware.smack.packet.PacketExtension#toXML() - */ - public String toXML() { - final StringBuilder buf = new StringBuilder(); + /* + * (non-Javadoc) + * + * @see org.jivesoftware.smack.packet.PacketExtension#toXML() + */ + @Override + public String toXML() { + final StringBuilder buf = new StringBuilder(); - buf.append('<').append(ELEMENT_NAME).append(" xmlns=\"").append( - NAMESPACE).append("\">"); - buf.append(getName()); - buf.append("'); + buf.append('<').append(ELEMENT_NAME).append(" xmlns=\"").append( + NAMESPACE).append("\">"); + buf.append(getName()); + buf.append("'); - return buf.toString(); - } + return buf.toString(); + } - public static class Provider extends ExtensionElementProvider { + public static class Provider extends ExtensionElementProvider { @Override public Nick parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException { - final String name = parser.nextText(); + final String name = parser.nextText(); - return new Nick(name); - } - } + return new Nick(name); + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/OfflineMessageManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/OfflineMessageManager.java index 7afe302ec..6b83128a7 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/OfflineMessageManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/OfflineMessageManager.java @@ -152,6 +152,7 @@ public class OfflineMessageManager { } // Filter offline messages that were requested by this request StanzaFilter messageFilter = new AndFilter(PACKET_FILTER, new StanzaFilter() { + @Override public boolean accept(Stanza packet) { OfflineMessageInfo info = (OfflineMessageInfo) packet.getExtension("offline", namespace); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/packet/OfflineMessageInfo.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/packet/OfflineMessageInfo.java index 237debfda..c121d8b60 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/packet/OfflineMessageInfo.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/offline/packet/OfflineMessageInfo.java @@ -42,6 +42,7 @@ public class OfflineMessageInfo implements ExtensionElement { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return "offline"; } @@ -52,6 +53,7 @@ public class OfflineMessageInfo implements ExtensionElement { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return "http://jabber.org/protocol/offline"; } @@ -78,6 +80,7 @@ public class OfflineMessageInfo implements ExtensionElement { this.node = node; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pep/PEPManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pep/PEPManager.java index 280296e96..2fc42be80 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pep/PEPManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pep/PEPManager.java @@ -91,6 +91,7 @@ public final class PEPManager extends Manager { private PEPManager(XMPPConnection connection) { super(connection); StanzaListener packetListener = new StanzaListener() { + @Override public void processStanza(Stanza stanza) { Message message = (Message) stanza; EventElement event = EventElement.from(stanza); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java index ce63a78ea..11f9dcd0f 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java @@ -67,6 +67,7 @@ public final class PingManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } @@ -402,6 +403,7 @@ public final class PingManager extends Manager { } private final Runnable pingServerRunnable = new Runnable() { + @Override public void run() { LOGGER.fine("ServerPingTask run()"); pingServerIfNecessary(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java index 73aa34c7a..afe170d51 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java @@ -78,6 +78,7 @@ public final class PrivacyListManager extends Manager { static { // Create a new PrivacyListManager on every established connection. XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } @@ -95,7 +96,7 @@ public final class PrivacyListManager extends Manager { * * @param connection the XMPP connection. */ - private PrivacyListManager(XMPPConnection connection) { + private PrivacyListManager(XMPPConnection connection) { super(connection); connection.registerIQRequestHandler(new AbstractIqRequestHandler(Privacy.ELEMENT, Privacy.NAMESPACE, @@ -215,24 +216,24 @@ public final class PrivacyListManager extends Manager { return plm; } - /** - * Send the {@link Privacy} stanza(/packet) to the server in order to know some privacy content and then - * waits for the answer. - * - * @param requestPrivacy is the {@link Privacy} stanza(/packet) configured properly whose XML + /** + * Send the {@link Privacy} stanza(/packet) to the server in order to know some privacy content and then + * waits for the answer. + * + * @param requestPrivacy is the {@link Privacy} stanza(/packet) configured properly whose XML * will be sent to the server. - * @return a new {@link Privacy} with the data received from the server. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - private Privacy getRequest(Privacy requestPrivacy) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request is a get iq type - requestPrivacy.setType(Privacy.Type.get); + * @return a new {@link Privacy} with the data received from the server. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + private Privacy getRequest(Privacy requestPrivacy) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request is a get iq type + requestPrivacy.setType(Privacy.Type.get); return connection().createStanzaCollectorAndSend(requestPrivacy).nextResultOrThrow(); - } + } /** * Send the {@link Privacy} stanza(/packet) to the server in order to modify the server privacy and waits @@ -253,22 +254,22 @@ public final class PrivacyListManager extends Manager { return connection().createStanzaCollectorAndSend(requestPrivacy).nextResultOrThrow(); } - /** - * Answer a privacy containing the list structure without {@link PrivacyItem}. - * - * @return a Privacy with the list names. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - private Privacy getPrivacyWithListNames() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an empty privacy message - Privacy request = new Privacy(); + /** + * Answer a privacy containing the list structure without {@link PrivacyItem}. + * + * @return a Privacy with the list names. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + private Privacy getPrivacyWithListNames() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an empty privacy message + Privacy request = new Privacy(); - // Send the package to the server and get the answer - return getRequest(request); - } + // Send the package to the server and get the answer + return getRequest(request); + } /** * Answer the active privacy list. Returns null if there is no active list. @@ -386,20 +387,20 @@ public final class PrivacyListManager extends Manager { return privacyAnswer.getPrivacyList(listName); } - /** - * Answer the privacy list items under listName with the allowed and blocked permissions. - * - * @param listName the name of the list to get the allowed and blocked permissions. - * @return a privacy list under the list listName. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public PrivacyList getPrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + /** + * Answer the privacy list items under listName with the allowed and blocked permissions. + * + * @param listName the name of the list to get the allowed and blocked permissions. + * @return a privacy list under the list listName. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public PrivacyList getPrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { listName = StringUtils.requireNotNullOrEmpty(listName, "List name must not be null"); return new PrivacyList(false, false, listName, getPrivacyListItems(listName)); - } + } /** * Answer every privacy list with the allowed and blocked permissions. @@ -423,87 +424,87 @@ public final class PrivacyListManager extends Manager { return lists; } - /** - * Set or change the active list to listName. - * - * @param listName the list name to set as the active one. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void setActiveListName(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an privacy message with an empty list - Privacy request = new Privacy(); - request.setActiveName(listName); + /** + * Set or change the active list to listName. + * + * @param listName the list name to set as the active one. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void setActiveListName(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an privacy message with an empty list + Privacy request = new Privacy(); + request.setActiveName(listName); - // Send the package to the server - setRequest(request); - } + // Send the package to the server + setRequest(request); + } - /** - * Client declines the use of active lists. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void declineActiveList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an privacy message with an empty list - Privacy request = new Privacy(); - request.setDeclineActiveList(true); + /** + * Client declines the use of active lists. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void declineActiveList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an privacy message with an empty list + Privacy request = new Privacy(); + request.setDeclineActiveList(true); - // Send the package to the server - setRequest(request); - } + // Send the package to the server + setRequest(request); + } - /** - * Set or change the default list to listName. - * - * @param listName the list name to set as the default one. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void setDefaultListName(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an privacy message with an empty list - Privacy request = new Privacy(); - request.setDefaultName(listName); + /** + * Set or change the default list to listName. + * + * @param listName the list name to set as the default one. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void setDefaultListName(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an privacy message with an empty list + Privacy request = new Privacy(); + request.setDefaultName(listName); - // Send the package to the server - setRequest(request); - } + // Send the package to the server + setRequest(request); + } - /** - * Client declines the use of default lists. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void declineDefaultList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an privacy message with an empty list - Privacy request = new Privacy(); - request.setDeclineDefaultList(true); + /** + * Client declines the use of default lists. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void declineDefaultList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an privacy message with an empty list + Privacy request = new Privacy(); + request.setDeclineDefaultList(true); - // Send the package to the server - setRequest(request); - } + // Send the package to the server + setRequest(request); + } - /** - * The client has created a new list. It send the new one to the server. - * + /** + * The client has created a new list. It send the new one to the server. + * * @param listName the list that has changed its content. * @param privacyItems a List with every privacy item in the list. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void createPrivacyList(String listName, List privacyItems) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - updatePrivacyList(listName, privacyItems); - } + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void createPrivacyList(String listName, List privacyItems) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + updatePrivacyList(listName, privacyItems); + } /** * The client has edited an existing list. It updates the server content with the resulting @@ -526,23 +527,23 @@ public final class PrivacyListManager extends Manager { setRequest(request); } - /** - * Remove a privacy list. - * + /** + * Remove a privacy list. + * * @param listName the list that has changed its content. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void deletePrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // The request of the list is an privacy message with an empty list - Privacy request = new Privacy(); - request.setPrivacyList(listName, new ArrayList()); + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void deletePrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + // The request of the list is an privacy message with an empty list + Privacy request = new Privacy(); + request.setPrivacyList(listName, new ArrayList()); - // Send the package to the server - setRequest(request); - } + // Send the package to the server + setRequest(request); + } /** * Adds a privacy list listener that will be notified of any new update in the user diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java index be45b3992..11b056a28 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/packet/Privacy.java @@ -45,17 +45,17 @@ public class Privacy extends IQ { public static final String ELEMENT = QUERY_ELEMENT; public static final String NAMESPACE = "jabber:iq:privacy"; - /** declineActiveList is true when the user declines the use of the active list **/ - private boolean declineActiveList=false; - /** activeName is the name associated with the active list set for the session **/ - private String activeName; - /** declineDefaultList is true when the user declines the use of the default list **/ - private boolean declineDefaultList=false; - /** defaultName is the name of the default list that applies to the user as a whole **/ - private String defaultName; - /** itemLists holds the set of privacy items classified in lists. It is a map where the - * key is the name of the list and the value a collection with privacy items. **/ - private Map> itemLists = new HashMap>(); + /** declineActiveList is true when the user declines the use of the active list **/ + private boolean declineActiveList=false; + /** activeName is the name associated with the active list set for the session **/ + private String activeName; + /** declineDefaultList is true when the user declines the use of the default list **/ + private boolean declineDefaultList=false; + /** defaultName is the name of the default list that applies to the user as a whole **/ + private String defaultName; + /** itemLists holds the set of privacy items classified in lists. It is a map where the + * key is the name of the list and the value a collection with privacy items. **/ + private Map> itemLists = new HashMap>(); public Privacy() { super(ELEMENT, NAMESPACE); @@ -94,13 +94,13 @@ public class Privacy extends IQ { public void deletePrivacyList(String listName) { // Remove the list from the cache // CHECKSTYLE:OFF - this.getItemLists().remove(listName); + this.getItemLists().remove(listName); // CHECKSTYLE:ON // Check if deleted list was the default list if (this.getDefaultName() != null && listName.equals(this.getDefaultName())) { // CHECKSTYLE:OFF - this.setDefaultName(null); + this.setDefaultName(null); // CHECKSTYLE:ON } } @@ -114,9 +114,9 @@ public class Privacy extends IQ { // Check if we have the default list // CHECKSTYLE:OFF if (this.getActiveName() == null) { - return null; + return null; } else { - return this.getItemLists().get(this.getActiveName()); + return this.getItemLists().get(this.getActiveName()); } // CHECKSTYLE:ON } @@ -130,9 +130,9 @@ public class Privacy extends IQ { // Check if we have the default list // CHECKSTYLE:OFF if (this.getDefaultName() == null) { - return null; + return null; } else { - return this.getItemLists().get(this.getDefaultName()); + return this.getItemLists().get(this.getDefaultName()); } // CHECKSTYLE:ON } @@ -156,15 +156,15 @@ public class Privacy extends IQ { */ public PrivacyItem getItem(String listName, int order) { // CHECKSTYLE:OFF - Iterator values = getPrivacyList(listName).iterator(); - PrivacyItem itemFound = null; - while (itemFound == null && values.hasNext()) { - PrivacyItem element = values.next(); - if (element.getOrder() == order) { - itemFound = element; - } - } - return itemFound; + Iterator values = getPrivacyList(listName).iterator(); + PrivacyItem itemFound = null; + while (itemFound == null && values.hasNext()) { + PrivacyItem element = values.next(); + if (element.getOrder() == order) { + itemFound = element; + } + } + return itemFound; // CHECKSTYLE:ON } @@ -180,7 +180,7 @@ public class Privacy extends IQ { return true; } else { // CHECKSTYLE:OFF - return false; + return false; // CHECKSTYLE:ON } } @@ -192,7 +192,7 @@ public class Privacy extends IQ { */ public void deleteList(String listName) { // CHECKSTYLE:OFF - this.getItemLists().remove(listName); + this.getItemLists().remove(listName); // CHECKSTYLE:ON } @@ -203,9 +203,9 @@ public class Privacy extends IQ { * @return the name of the active list. */ // CHECKSTYLE:OFF - public String getActiveName() { - return activeName; - } + public String getActiveName() { + return activeName; + } // CHECKSTYLE:ON /** @@ -215,9 +215,9 @@ public class Privacy extends IQ { * @param activeName is the name of the active list. */ // CHECKSTYLE:OFF - public void setActiveName(String activeName) { - this.activeName = activeName; - } + public void setActiveName(String activeName) { + this.activeName = activeName; + } // CHECKSTYLE:ON /** @@ -228,9 +228,9 @@ public class Privacy extends IQ { * @return the name of the default list. */ // CHECKSTYLE:OFF - public String getDefaultName() { - return defaultName; - } + public String getDefaultName() { + return defaultName; + } // CHECKSTYLE:ON /** @@ -243,9 +243,9 @@ public class Privacy extends IQ { * @param defaultName is the name of the default list. */ // CHECKSTYLE:OFF - public void setDefaultName(String defaultName) { - this.defaultName = defaultName; - } + public void setDefaultName(String defaultName) { + this.defaultName = defaultName; + } // CHECKSTYLE:ON /** @@ -257,9 +257,9 @@ public class Privacy extends IQ { * collection of privacy items. */ // CHECKSTYLE:OFF - public Map> getItemLists() { - return itemLists; - } + public Map> getItemLists() { + return itemLists; + } // CHECKSTYLE:ON /** @@ -268,9 +268,9 @@ public class Privacy extends IQ { * @return the decline status of the list. */ // CHECKSTYLE:OFF - public boolean isDeclineActiveList() { - return declineActiveList; - } + public boolean isDeclineActiveList() { + return declineActiveList; + } // CHECKSYTLE:ON /** @@ -279,9 +279,9 @@ public class Privacy extends IQ { * @param declineActiveList indicates if the receiver declines the use of an active list. */ // CHECKSTYLE:OFF - public void setDeclineActiveList(boolean declineActiveList) { - this.declineActiveList = declineActiveList; - } + public void setDeclineActiveList(boolean declineActiveList) { + this.declineActiveList = declineActiveList; + } // CHECKSTYLE:ON /** @@ -290,9 +290,9 @@ public class Privacy extends IQ { * @return the decline status of the list. */ // CHECKSTYLE:OFF - public boolean isDeclineDefaultList() { - return declineDefaultList; - } + public boolean isDeclineDefaultList() { + return declineDefaultList; + } // CHECKSTYLE:ON /** @@ -301,18 +301,18 @@ public class Privacy extends IQ { * @param declineDefaultList indicates if the receiver declines the use of a default list. */ // CHECKSTYLE:OFF - public void setDeclineDefaultList(boolean declineDefaultList) { - this.declineDefaultList = declineDefaultList; - } + public void setDeclineDefaultList(boolean declineDefaultList) { + this.declineDefaultList = declineDefaultList; + } - /** + /** * Returns all the list names the user has defined to group restrictions. * * @return a Set with Strings containing every list names. */ - public Set getPrivacyListNames() { - return this.itemLists.keySet(); - } + public Set getPrivacyListNames() { + return this.itemLists.keySet(); + } // CHECKSTYLE:ON @Override @@ -322,40 +322,40 @@ public class Privacy extends IQ { // Add the active tag if (this.isDeclineActiveList()) { - buf.append(""); + buf.append(""); } else { - if (this.getActiveName() != null) { + if (this.getActiveName() != null) { buf.append(""); } } // Add the default tag if (this.isDeclineDefaultList()) { - buf.append(""); + buf.append(""); } else { - if (this.getDefaultName() != null) { + if (this.getDefaultName() != null) { buf.append(""); - } + } } // Add the list with their privacy items for (Map.Entry> entry : this.getItemLists().entrySet()) { String listName = entry.getKey(); List items = entry.getValue(); - // Begin the list tag - if (items.isEmpty()) { + // Begin the list tag + if (items.isEmpty()) { buf.append(""); - } else { + } else { buf.append(""); - } - for (PrivacyItem item : items) { - // Append the item xml representation - buf.append(item.toXML()); - } - // Close the list tag - if (!items.isEmpty()) { - buf.append(""); - } - } + } + for (PrivacyItem item : items) { + // Append the item xml representation + buf.append(item.toXML()); + } + // Close the list tag + if (!items.isEmpty()) { + buf.append(""); + } + } // CHECKSTYLE:ON return buf; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/provider/PrivacyProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/provider/PrivacyProvider.java index ac6a8e523..15db41f9a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/provider/PrivacyProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/provider/PrivacyProvider.java @@ -47,20 +47,20 @@ public class PrivacyProvider extends IQProvider { if (eventType == XmlPullParser.START_TAG) { // CHECKSTYLE:OFF if (parser.getName().equals("active")) { - String activeName = parser.getAttributeValue("", "name"); - if (activeName == null) { - privacy.setDeclineActiveList(true); - } else { - privacy.setActiveName(activeName); - } + String activeName = parser.getAttributeValue("", "name"); + if (activeName == null) { + privacy.setDeclineActiveList(true); + } else { + privacy.setActiveName(activeName); + } } else if (parser.getName().equals("default")) { - String defaultName = parser.getAttributeValue("", "name"); - if (defaultName == null) { - privacy.setDeclineDefaultList(true); - } else { - privacy.setDefaultName(defaultName); - } + String defaultName = parser.getAttributeValue("", "name"); + if (defaultName == null) { + privacy.setDeclineDefaultList(true); + } else { + privacy.setDefaultName(defaultName); + } } // CHECKSTYLE:ON else if (parser.getName().equals("list")) { @@ -75,10 +75,10 @@ public class PrivacyProvider extends IQProvider { } return privacy; - } + } - // Parse the list complex type - private static void parseList(XmlPullParser parser, Privacy privacy) throws XmlPullParserException, IOException, SmackException { + // Parse the list complex type + private static void parseList(XmlPullParser parser, Privacy privacy) throws XmlPullParserException, IOException, SmackException { boolean done = false; String listName = parser.getAttributeValue("", "name"); ArrayList items = new ArrayList(); @@ -87,7 +87,7 @@ public class PrivacyProvider extends IQProvider { if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("item")) { // CHECKSTYLE:OFF - items.add(parseItem(parser)); + items.add(parseItem(parser)); // CHECKSTYLE:ON } } @@ -100,10 +100,10 @@ public class PrivacyProvider extends IQProvider { privacy.setPrivacyList(listName, items); // CHECKSTYLE:OFF - } + } - // Parse the list complex type - private static PrivacyItem parseItem(XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { + // Parse the list complex type + private static PrivacyItem parseItem(XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { // CHECKSTYLE:ON // Retrieves the required attributes String actionValue = parser.getAttributeValue("", "action"); @@ -142,7 +142,7 @@ public class PrivacyProvider extends IQProvider { parseItemChildElements(parser, item); return item; // CHECKSTYLE:OFF - } + } // CHECKSTYLE:ON private static void parseItemChildElements(XmlPullParser parser, PrivacyItem privacyItem) throws XmlPullParserException, IOException { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AccessModel.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AccessModel.java index 6748cd40a..eb2614872 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AccessModel.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AccessModel.java @@ -24,18 +24,18 @@ package org.jivesoftware.smackx.pubsub; */ public enum AccessModel { - /** Anyone may subscribe and retrieve items. */ - open, + /** Anyone may subscribe and retrieve items. */ + open, - /** Subscription request must be approved and only subscribers may retrieve items. */ - authorize, + /** Subscription request must be approved and only subscribers may retrieve items. */ + authorize, - /** Anyone with a presence subscription of both or from may subscribe and retrieve items. */ - presence, + /** Anyone with a presence subscription of both or from may subscribe and retrieve items. */ + presence, - /** Anyone in the specified roster group(s) may subscribe and retrieve items. */ - roster, + /** Anyone in the specified roster group(s) may subscribe and retrieve items. */ + roster, - /** Only those on a whitelist may subscribe and retrieve items. */ - whitelist; + /** Only those on a whitelist may subscribe and retrieve items. */ + whitelist; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Affiliation.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Affiliation.java index 9bd1b8c2f..da2ba07da 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Affiliation.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Affiliation.java @@ -42,17 +42,17 @@ public class Affiliation implements ExtensionElement private final Type affiliation; private final PubSubNamespace namespace; - public enum Type - { - member, none, outcast, owner, publisher - } + public enum Type + { + member, none, outcast, owner, publisher + } - /** - * Constructs an affiliation. - * - * @param node The node the user is affiliated with. - * @param affiliation the optional affiliation. - */ + /** + * Constructs an affiliation. + * + * @param node The node the user is affiliated with. + * @param affiliation the optional affiliation. + */ public Affiliation(String node, Type affiliation) { this.node = StringUtils.requireNotNullOrEmpty(node, "node must not be null or empty"); this.affiliation = affiliation; @@ -122,6 +122,7 @@ public class Affiliation implements ExtensionElement return ELEMENT; } + @Override public String getNamespace() { return namespace.getXmlns(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AffiliationsExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AffiliationsExtension.java index b365adc47..9e4ae26be 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AffiliationsExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/AffiliationsExtension.java @@ -30,8 +30,8 @@ import org.jivesoftware.smack.util.XmlStringBuilder; */ public class AffiliationsExtension extends NodeExtension { - protected List items = Collections.emptyList(); - private final String node; + protected List items = Collections.emptyList(); + private final String node; public AffiliationsExtension() { this(null, null); @@ -47,20 +47,20 @@ public class AffiliationsExtension extends NodeExtension this.node = node; } - public List getAffiliations() - { - return items; - } + public List getAffiliations() + { + return items; + } - @Override - public CharSequence toXML() - { - if ((items == null) || (items.size() == 0)) - { - return super.toXML(); - } - else - { + @Override + public CharSequence toXML() + { + if ((items == null) || (items.size() == 0)) + { + return super.toXML(); + } + else + { // Can't use XmlStringBuilder(this), because we don't want the namespace to be included XmlStringBuilder xml = new XmlStringBuilder(); xml.openElement(getElementName()); @@ -69,6 +69,6 @@ public class AffiliationsExtension extends NodeExtension xml.append(items); xml.closeElement(this); return xml; - } - } + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ChildrenAssociationPolicy.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ChildrenAssociationPolicy.java index cab4ddb64..9e5021b13 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ChildrenAssociationPolicy.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ChildrenAssociationPolicy.java @@ -24,12 +24,12 @@ package org.jivesoftware.smackx.pubsub; */ public enum ChildrenAssociationPolicy { - /** Anyone may associate leaf nodes with the collection. */ - all, + /** Anyone may associate leaf nodes with the collection. */ + all, - /** Only collection node owners may associate leaf nodes with the collection. */ - owners, + /** Only collection node owners may associate leaf nodes with the collection. */ + owners, - /** Only those on a whitelist may associate leaf nodes with the collection. */ - whitelist; + /** Only those on a whitelist may associate leaf nodes with the collection. */ + whitelist; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/CollectionNode.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/CollectionNode.java index 4b93f3bd5..47260e6bb 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/CollectionNode.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/CollectionNode.java @@ -18,9 +18,9 @@ package org.jivesoftware.smackx.pubsub; public class CollectionNode extends Node { - CollectionNode(PubSubManager pubSubManager, String nodeId) - { - super(pubSubManager, nodeId); - } + CollectionNode(PubSubManager pubSubManager, String nodeId) + { + super(pubSubManager, nodeId); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigurationEvent.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigurationEvent.java index fb46f78cc..97c4d086c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigurationEvent.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigurationEvent.java @@ -31,29 +31,30 @@ import org.jivesoftware.smack.packet.ExtensionElement; */ public class ConfigurationEvent extends NodeExtension implements EmbeddedPacketExtension { - private ConfigureForm form; + private ConfigureForm form; - public ConfigurationEvent(String nodeId) - { - super(PubSubElementType.CONFIGURATION, nodeId); - } + public ConfigurationEvent(String nodeId) + { + super(PubSubElementType.CONFIGURATION, nodeId); + } - public ConfigurationEvent(String nodeId, ConfigureForm configForm) - { - super(PubSubElementType.CONFIGURATION, nodeId); - form = configForm; - } + public ConfigurationEvent(String nodeId, ConfigureForm configForm) + { + super(PubSubElementType.CONFIGURATION, nodeId); + form = configForm; + } - public ConfigureForm getConfiguration() - { - return form; - } + public ConfigureForm getConfiguration() + { + return form; + } - public List getExtensions() - { - if (getConfiguration() == null) - return Collections.emptyList(); - else - return Arrays.asList(((ExtensionElement)getConfiguration().getDataFormToSend())); - } + @Override + public List getExtensions() + { + if (getConfiguration() == null) + return Collections.emptyList(); + else + return Arrays.asList(((ExtensionElement)getConfiguration().getDataFormToSend())); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureForm.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureForm.java index 144c50393..4dd2979d7 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureForm.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureForm.java @@ -35,555 +35,555 @@ import org.jivesoftware.smackx.xdata.packet.DataForm; */ public class ConfigureForm extends Form { - /** - * Create a decorator from an existing {@link DataForm} that has been - * retrieved from parsing a node configuration request. - * - * @param configDataForm - */ - public ConfigureForm(DataForm configDataForm) - { - super(configDataForm); - } + /** + * Create a decorator from an existing {@link DataForm} that has been + * retrieved from parsing a node configuration request. + * + * @param configDataForm + */ + public ConfigureForm(DataForm configDataForm) + { + super(configDataForm); + } - /** - * Create a decorator from an existing {@link Form} for node configuration. - * Typically, this can be used to create a decorator for an answer form - * by using the result of {@link #createAnswerForm()} as the input parameter. - * - * @param nodeConfigForm - */ - public ConfigureForm(Form nodeConfigForm) - { - super(nodeConfigForm.getDataFormToSend()); - } + /** + * Create a decorator from an existing {@link Form} for node configuration. + * Typically, this can be used to create a decorator for an answer form + * by using the result of {@link #createAnswerForm()} as the input parameter. + * + * @param nodeConfigForm + */ + public ConfigureForm(Form nodeConfigForm) + { + super(nodeConfigForm.getDataFormToSend()); + } - /** - * Create a new form for configuring a node. This would typically only be used - * when creating and configuring a node at the same time via {@link PubSubManager#createNode(String, Form)}, since - * configuration of an existing node is typically accomplished by calling {@link LeafNode#getNodeConfiguration()} and - * using the resulting form to create a answer form. See {@link #ConfigureForm(Form)}. - * @param formType - */ - public ConfigureForm(DataForm.Type formType) - { - super(formType); - } + /** + * Create a new form for configuring a node. This would typically only be used + * when creating and configuring a node at the same time via {@link PubSubManager#createNode(String, Form)}, since + * configuration of an existing node is typically accomplished by calling {@link LeafNode#getNodeConfiguration()} and + * using the resulting form to create a answer form. See {@link #ConfigureForm(Form)}. + * @param formType + */ + public ConfigureForm(DataForm.Type formType) + { + super(formType); + } - /** - * Get the currently configured {@link AccessModel}, null if it is not set. - * - * @return The current {@link AccessModel} - */ - public AccessModel getAccessModel() - { - String value = getFieldValue(ConfigureNodeFields.access_model); + /** + * Get the currently configured {@link AccessModel}, null if it is not set. + * + * @return The current {@link AccessModel} + */ + public AccessModel getAccessModel() + { + String value = getFieldValue(ConfigureNodeFields.access_model); - if (value == null) - return null; - else - return AccessModel.valueOf(value); - } + if (value == null) + return null; + else + return AccessModel.valueOf(value); + } - /** - * Sets the value of access model. - * - * @param accessModel - */ - public void setAccessModel(AccessModel accessModel) - { - addField(ConfigureNodeFields.access_model, FormField.Type.list_single); - setAnswer(ConfigureNodeFields.access_model.getFieldName(), getListSingle(accessModel.toString())); - } + /** + * Sets the value of access model. + * + * @param accessModel + */ + public void setAccessModel(AccessModel accessModel) + { + addField(ConfigureNodeFields.access_model, FormField.Type.list_single); + setAnswer(ConfigureNodeFields.access_model.getFieldName(), getListSingle(accessModel.toString())); + } - /** - * Returns the URL of an XSL transformation which can be applied to payloads in order to - * generate an appropriate message body element. - * - * @return URL to an XSL - */ - public String getBodyXSLT() - { - return getFieldValue(ConfigureNodeFields.body_xslt); - } + /** + * Returns the URL of an XSL transformation which can be applied to payloads in order to + * generate an appropriate message body element. + * + * @return URL to an XSL + */ + public String getBodyXSLT() + { + return getFieldValue(ConfigureNodeFields.body_xslt); + } - /** - * Set the URL of an XSL transformation which can be applied to payloads in order to - * generate an appropriate message body element. - * - * @param bodyXslt The URL of an XSL - */ - public void setBodyXSLT(String bodyXslt) - { - addField(ConfigureNodeFields.body_xslt, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.body_xslt.getFieldName(), bodyXslt); - } + /** + * Set the URL of an XSL transformation which can be applied to payloads in order to + * generate an appropriate message body element. + * + * @param bodyXslt The URL of an XSL + */ + public void setBodyXSLT(String bodyXslt) + { + addField(ConfigureNodeFields.body_xslt, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.body_xslt.getFieldName(), bodyXslt); + } - /** - * The id's of the child nodes associated with a collection node (both leaf and collection). - * - * @return list of child nodes. - */ - public List getChildren() - { - return getFieldValues(ConfigureNodeFields.children); - } + /** + * The id's of the child nodes associated with a collection node (both leaf and collection). + * + * @return list of child nodes. + */ + public List getChildren() + { + return getFieldValues(ConfigureNodeFields.children); + } - /** - * Set the list of child node ids that are associated with a collection node. - * - * @param children - */ - public void setChildren(List children) - { - addField(ConfigureNodeFields.children, FormField.Type.text_multi); - setAnswer(ConfigureNodeFields.children.getFieldName(), children); - } + /** + * Set the list of child node ids that are associated with a collection node. + * + * @param children + */ + public void setChildren(List children) + { + addField(ConfigureNodeFields.children, FormField.Type.text_multi); + setAnswer(ConfigureNodeFields.children.getFieldName(), children); + } - /** - * Returns the policy that determines who may associate children with the node. - * - * @return The current policy - */ - public ChildrenAssociationPolicy getChildrenAssociationPolicy() - { - String value = getFieldValue(ConfigureNodeFields.children_association_policy); + /** + * Returns the policy that determines who may associate children with the node. + * + * @return The current policy + */ + public ChildrenAssociationPolicy getChildrenAssociationPolicy() + { + String value = getFieldValue(ConfigureNodeFields.children_association_policy); - if (value == null) - return null; - else - return ChildrenAssociationPolicy.valueOf(value); - } + if (value == null) + return null; + else + return ChildrenAssociationPolicy.valueOf(value); + } - /** - * Sets the policy that determines who may associate children with the node. - * - * @param policy The policy being set - */ - public void setChildrenAssociationPolicy(ChildrenAssociationPolicy policy) - { - addField(ConfigureNodeFields.children_association_policy, FormField.Type.list_single); + /** + * Sets the policy that determines who may associate children with the node. + * + * @param policy The policy being set + */ + public void setChildrenAssociationPolicy(ChildrenAssociationPolicy policy) + { + addField(ConfigureNodeFields.children_association_policy, FormField.Type.list_single); List values = new ArrayList(1); values.add(policy.toString()); setAnswer(ConfigureNodeFields.children_association_policy.getFieldName(), values); - } + } - /** - * List of JID's that are on the whitelist that determines who can associate child nodes - * with the collection node. This is only relevant if {@link #getChildrenAssociationPolicy()} is set to - * {@link ChildrenAssociationPolicy#whitelist}. - * - * @return List of the whitelist - */ - public List getChildrenAssociationWhitelist() - { - return getFieldValues(ConfigureNodeFields.children_association_whitelist); - } + /** + * List of JID's that are on the whitelist that determines who can associate child nodes + * with the collection node. This is only relevant if {@link #getChildrenAssociationPolicy()} is set to + * {@link ChildrenAssociationPolicy#whitelist}. + * + * @return List of the whitelist + */ + public List getChildrenAssociationWhitelist() + { + return getFieldValues(ConfigureNodeFields.children_association_whitelist); + } - /** - * Set the JID's in the whitelist of users that can associate child nodes with the collection - * node. This is only relevant if {@link #getChildrenAssociationPolicy()} is set to - * {@link ChildrenAssociationPolicy#whitelist}. - * - * @param whitelist The list of JID's - */ - public void setChildrenAssociationWhitelist(List whitelist) - { - addField(ConfigureNodeFields.children_association_whitelist, FormField.Type.jid_multi); - setAnswer(ConfigureNodeFields.children_association_whitelist.getFieldName(), whitelist); - } + /** + * Set the JID's in the whitelist of users that can associate child nodes with the collection + * node. This is only relevant if {@link #getChildrenAssociationPolicy()} is set to + * {@link ChildrenAssociationPolicy#whitelist}. + * + * @param whitelist The list of JID's + */ + public void setChildrenAssociationWhitelist(List whitelist) + { + addField(ConfigureNodeFields.children_association_whitelist, FormField.Type.jid_multi); + setAnswer(ConfigureNodeFields.children_association_whitelist.getFieldName(), whitelist); + } - /** - * Gets the maximum number of child nodes that can be associated with the collection node. - * - * @return The maximum number of child nodes - */ - public int getChildrenMax() - { - return Integer.parseInt(getFieldValue(ConfigureNodeFields.children_max)); - } + /** + * Gets the maximum number of child nodes that can be associated with the collection node. + * + * @return The maximum number of child nodes + */ + public int getChildrenMax() + { + return Integer.parseInt(getFieldValue(ConfigureNodeFields.children_max)); + } - /** - * Set the maximum number of child nodes that can be associated with a collection node. - * - * @param max The maximum number of child nodes. - */ - public void setChildrenMax(int max) - { - addField(ConfigureNodeFields.children_max, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.children_max.getFieldName(), max); - } + /** + * Set the maximum number of child nodes that can be associated with a collection node. + * + * @param max The maximum number of child nodes. + */ + public void setChildrenMax(int max) + { + addField(ConfigureNodeFields.children_max, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.children_max.getFieldName(), max); + } - /** - * Gets the collection node which the node is affiliated with. - * - * @return The collection node id - */ - public String getCollection() - { - return getFieldValue(ConfigureNodeFields.collection); - } + /** + * Gets the collection node which the node is affiliated with. + * + * @return The collection node id + */ + public String getCollection() + { + return getFieldValue(ConfigureNodeFields.collection); + } - /** - * Sets the collection node which the node is affiliated with. - * - * @param collection The node id of the collection node - */ - public void setCollection(String collection) - { - addField(ConfigureNodeFields.collection, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.collection.getFieldName(), collection); - } + /** + * Sets the collection node which the node is affiliated with. + * + * @param collection The node id of the collection node + */ + public void setCollection(String collection) + { + addField(ConfigureNodeFields.collection, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.collection.getFieldName(), collection); + } - /** - * Gets the URL of an XSL transformation which can be applied to the payload - * format in order to generate a valid Data Forms result that the client could - * display using a generic Data Forms rendering engine. - * - * @return The URL of an XSL transformation - */ - public String getDataformXSLT() - { - return getFieldValue(ConfigureNodeFields.dataform_xslt); - } + /** + * Gets the URL of an XSL transformation which can be applied to the payload + * format in order to generate a valid Data Forms result that the client could + * display using a generic Data Forms rendering engine. + * + * @return The URL of an XSL transformation + */ + public String getDataformXSLT() + { + return getFieldValue(ConfigureNodeFields.dataform_xslt); + } - /** - * Sets the URL of an XSL transformation which can be applied to the payload - * format in order to generate a valid Data Forms result that the client could - * display using a generic Data Forms rendering engine. - * - * @param url The URL of an XSL transformation - */ - public void setDataformXSLT(String url) - { - addField(ConfigureNodeFields.dataform_xslt, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.dataform_xslt.getFieldName(), url); - } + /** + * Sets the URL of an XSL transformation which can be applied to the payload + * format in order to generate a valid Data Forms result that the client could + * display using a generic Data Forms rendering engine. + * + * @param url The URL of an XSL transformation + */ + public void setDataformXSLT(String url) + { + addField(ConfigureNodeFields.dataform_xslt, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.dataform_xslt.getFieldName(), url); + } - /** - * Does the node deliver payloads with event notifications. - * - * @return true if it does, false otherwise - */ - public boolean isDeliverPayloads() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.deliver_payloads)); - } + /** + * Does the node deliver payloads with event notifications. + * + * @return true if it does, false otherwise + */ + public boolean isDeliverPayloads() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.deliver_payloads)); + } - /** - * Sets whether the node will deliver payloads with event notifications. - * - * @param deliver true if the payload will be delivered, false otherwise - */ - public void setDeliverPayloads(boolean deliver) - { - addField(ConfigureNodeFields.deliver_payloads, FormField.Type.bool); - setAnswer(ConfigureNodeFields.deliver_payloads.getFieldName(), deliver); - } + /** + * Sets whether the node will deliver payloads with event notifications. + * + * @param deliver true if the payload will be delivered, false otherwise + */ + public void setDeliverPayloads(boolean deliver) + { + addField(ConfigureNodeFields.deliver_payloads, FormField.Type.bool); + setAnswer(ConfigureNodeFields.deliver_payloads.getFieldName(), deliver); + } - /** - * Determines who should get replies to items. - * - * @return Who should get the reply - */ - public ItemReply getItemReply() - { - String value = getFieldValue(ConfigureNodeFields.itemreply); + /** + * Determines who should get replies to items. + * + * @return Who should get the reply + */ + public ItemReply getItemReply() + { + String value = getFieldValue(ConfigureNodeFields.itemreply); - if (value == null) - return null; - else - return ItemReply.valueOf(value); - } + if (value == null) + return null; + else + return ItemReply.valueOf(value); + } - /** - * Sets who should get the replies to items. - * - * @param reply Defines who should get the reply - */ - public void setItemReply(ItemReply reply) - { - addField(ConfigureNodeFields.itemreply, FormField.Type.list_single); - setAnswer(ConfigureNodeFields.itemreply.getFieldName(), getListSingle(reply.toString())); - } + /** + * Sets who should get the replies to items. + * + * @param reply Defines who should get the reply + */ + public void setItemReply(ItemReply reply) + { + addField(ConfigureNodeFields.itemreply, FormField.Type.list_single); + setAnswer(ConfigureNodeFields.itemreply.getFieldName(), getListSingle(reply.toString())); + } - /** - * Gets the maximum number of items to persisted to this node if {@link #isPersistItems()} is - * true. - * - * @return The maximum number of items to persist - */ - public int getMaxItems() - { - return Integer.parseInt(getFieldValue(ConfigureNodeFields.max_items)); - } + /** + * Gets the maximum number of items to persisted to this node if {@link #isPersistItems()} is + * true. + * + * @return The maximum number of items to persist + */ + public int getMaxItems() + { + return Integer.parseInt(getFieldValue(ConfigureNodeFields.max_items)); + } - /** - * Set the maximum number of items to persisted to this node if {@link #isPersistItems()} is - * true. - * - * @param max The maximum number of items to persist - */ - public void setMaxItems(int max) - { - addField(ConfigureNodeFields.max_items, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.max_items.getFieldName(), max); - } + /** + * Set the maximum number of items to persisted to this node if {@link #isPersistItems()} is + * true. + * + * @param max The maximum number of items to persist + */ + public void setMaxItems(int max) + { + addField(ConfigureNodeFields.max_items, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.max_items.getFieldName(), max); + } - /** - * Gets the maximum payload size in bytes. - * - * @return The maximum payload size - */ - public int getMaxPayloadSize() - { - return Integer.parseInt(getFieldValue(ConfigureNodeFields.max_payload_size)); - } + /** + * Gets the maximum payload size in bytes. + * + * @return The maximum payload size + */ + public int getMaxPayloadSize() + { + return Integer.parseInt(getFieldValue(ConfigureNodeFields.max_payload_size)); + } - /** - * Sets the maximum payload size in bytes. - * - * @param max The maximum payload size - */ - public void setMaxPayloadSize(int max) - { - addField(ConfigureNodeFields.max_payload_size, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.max_payload_size.getFieldName(), max); - } + /** + * Sets the maximum payload size in bytes. + * + * @param max The maximum payload size + */ + public void setMaxPayloadSize(int max) + { + addField(ConfigureNodeFields.max_payload_size, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.max_payload_size.getFieldName(), max); + } - /** - * Gets the node type. - * - * @return The node type - */ - public NodeType getNodeType() - { - String value = getFieldValue(ConfigureNodeFields.node_type); + /** + * Gets the node type. + * + * @return The node type + */ + public NodeType getNodeType() + { + String value = getFieldValue(ConfigureNodeFields.node_type); - if (value == null) - return null; - else - return NodeType.valueOf(value); - } + if (value == null) + return null; + else + return NodeType.valueOf(value); + } - /** - * Sets the node type. - * - * @param type The node type - */ - public void setNodeType(NodeType type) - { - addField(ConfigureNodeFields.node_type, FormField.Type.list_single); - setAnswer(ConfigureNodeFields.node_type.getFieldName(), getListSingle(type.toString())); - } + /** + * Sets the node type. + * + * @param type The node type + */ + public void setNodeType(NodeType type) + { + addField(ConfigureNodeFields.node_type, FormField.Type.list_single); + setAnswer(ConfigureNodeFields.node_type.getFieldName(), getListSingle(type.toString())); + } - /** - * Determines if subscribers should be notified when the configuration changes. - * - * @return true if they should be notified, false otherwise - */ - public boolean isNotifyConfig() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.notify_config)); - } + /** + * Determines if subscribers should be notified when the configuration changes. + * + * @return true if they should be notified, false otherwise + */ + public boolean isNotifyConfig() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.notify_config)); + } - /** - * Sets whether subscribers should be notified when the configuration changes. - * - * @param notify true if subscribers should be notified, false otherwise - */ - public void setNotifyConfig(boolean notify) - { - addField(ConfigureNodeFields.notify_config, FormField.Type.bool); - setAnswer(ConfigureNodeFields.notify_config.getFieldName(), notify); - } + /** + * Sets whether subscribers should be notified when the configuration changes. + * + * @param notify true if subscribers should be notified, false otherwise + */ + public void setNotifyConfig(boolean notify) + { + addField(ConfigureNodeFields.notify_config, FormField.Type.bool); + setAnswer(ConfigureNodeFields.notify_config.getFieldName(), notify); + } - /** - * Determines whether subscribers should be notified when the node is deleted. - * - * @return true if subscribers should be notified, false otherwise - */ - public boolean isNotifyDelete() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.notify_delete)); - } + /** + * Determines whether subscribers should be notified when the node is deleted. + * + * @return true if subscribers should be notified, false otherwise + */ + public boolean isNotifyDelete() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.notify_delete)); + } - /** - * Sets whether subscribers should be notified when the node is deleted. - * - * @param notify true if subscribers should be notified, false otherwise - */ - public void setNotifyDelete(boolean notify) - { - addField(ConfigureNodeFields.notify_delete, FormField.Type.bool); - setAnswer(ConfigureNodeFields.notify_delete.getFieldName(), notify); - } + /** + * Sets whether subscribers should be notified when the node is deleted. + * + * @param notify true if subscribers should be notified, false otherwise + */ + public void setNotifyDelete(boolean notify) + { + addField(ConfigureNodeFields.notify_delete, FormField.Type.bool); + setAnswer(ConfigureNodeFields.notify_delete.getFieldName(), notify); + } - /** - * Determines whether subscribers should be notified when items are deleted - * from the node. - * - * @return true if subscribers should be notified, false otherwise - */ - public boolean isNotifyRetract() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.notify_retract)); - } + /** + * Determines whether subscribers should be notified when items are deleted + * from the node. + * + * @return true if subscribers should be notified, false otherwise + */ + public boolean isNotifyRetract() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.notify_retract)); + } - /** - * Sets whether subscribers should be notified when items are deleted - * from the node. - * - * @param notify true if subscribers should be notified, false otherwise - */ - public void setNotifyRetract(boolean notify) - { - addField(ConfigureNodeFields.notify_retract, FormField.Type.bool); - setAnswer(ConfigureNodeFields.notify_retract.getFieldName(), notify); - } + /** + * Sets whether subscribers should be notified when items are deleted + * from the node. + * + * @param notify true if subscribers should be notified, false otherwise + */ + public void setNotifyRetract(boolean notify) + { + addField(ConfigureNodeFields.notify_retract, FormField.Type.bool); + setAnswer(ConfigureNodeFields.notify_retract.getFieldName(), notify); + } - /** - * Determines whether items should be persisted in the node. - * - * @return true if items are persisted - */ - public boolean isPersistItems() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.persist_items)); - } + /** + * Determines whether items should be persisted in the node. + * + * @return true if items are persisted + */ + public boolean isPersistItems() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.persist_items)); + } - /** - * Sets whether items should be persisted in the node. - * - * @param persist true if items should be persisted, false otherwise - */ - public void setPersistentItems(boolean persist) - { - addField(ConfigureNodeFields.persist_items, FormField.Type.bool); - setAnswer(ConfigureNodeFields.persist_items.getFieldName(), persist); - } + /** + * Sets whether items should be persisted in the node. + * + * @param persist true if items should be persisted, false otherwise + */ + public void setPersistentItems(boolean persist) + { + addField(ConfigureNodeFields.persist_items, FormField.Type.bool); + setAnswer(ConfigureNodeFields.persist_items.getFieldName(), persist); + } - /** - * Determines whether to deliver notifications to available users only. - * - * @return true if users must be available - */ - public boolean isPresenceBasedDelivery() - { - return parseBoolean(getFieldValue(ConfigureNodeFields.presence_based_delivery)); - } + /** + * Determines whether to deliver notifications to available users only. + * + * @return true if users must be available + */ + public boolean isPresenceBasedDelivery() + { + return parseBoolean(getFieldValue(ConfigureNodeFields.presence_based_delivery)); + } - /** - * Sets whether to deliver notifications to available users only. - * - * @param presenceBased true if user must be available, false otherwise - */ - public void setPresenceBasedDelivery(boolean presenceBased) - { - addField(ConfigureNodeFields.presence_based_delivery, FormField.Type.bool); - setAnswer(ConfigureNodeFields.presence_based_delivery.getFieldName(), presenceBased); - } + /** + * Sets whether to deliver notifications to available users only. + * + * @param presenceBased true if user must be available, false otherwise + */ + public void setPresenceBasedDelivery(boolean presenceBased) + { + addField(ConfigureNodeFields.presence_based_delivery, FormField.Type.bool); + setAnswer(ConfigureNodeFields.presence_based_delivery.getFieldName(), presenceBased); + } - /** - * Gets the publishing model for the node, which determines who may publish to it. - * - * @return The publishing model - */ - public PublishModel getPublishModel() - { - String value = getFieldValue(ConfigureNodeFields.publish_model); + /** + * Gets the publishing model for the node, which determines who may publish to it. + * + * @return The publishing model + */ + public PublishModel getPublishModel() + { + String value = getFieldValue(ConfigureNodeFields.publish_model); - if (value == null) - return null; - else - return PublishModel.valueOf(value); - } + if (value == null) + return null; + else + return PublishModel.valueOf(value); + } - /** - * Sets the publishing model for the node, which determines who may publish to it. - * - * @param publish The enum representing the possible options for the publishing model - */ - public void setPublishModel(PublishModel publish) - { - addField(ConfigureNodeFields.publish_model, FormField.Type.list_single); - setAnswer(ConfigureNodeFields.publish_model.getFieldName(), getListSingle(publish.toString())); - } + /** + * Sets the publishing model for the node, which determines who may publish to it. + * + * @param publish The enum representing the possible options for the publishing model + */ + public void setPublishModel(PublishModel publish) + { + addField(ConfigureNodeFields.publish_model, FormField.Type.list_single); + setAnswer(ConfigureNodeFields.publish_model.getFieldName(), getListSingle(publish.toString())); + } - /** - * List of the multi user chat rooms that are specified as reply rooms. - * - * @return The reply room JID's - */ - public List getReplyRoom() - { - return getFieldValues(ConfigureNodeFields.replyroom); - } + /** + * List of the multi user chat rooms that are specified as reply rooms. + * + * @return The reply room JID's + */ + public List getReplyRoom() + { + return getFieldValues(ConfigureNodeFields.replyroom); + } - /** - * Sets the multi user chat rooms that are specified as reply rooms. - * - * @param replyRooms The multi user chat room to use as reply rooms - */ - public void setReplyRoom(List replyRooms) - { - addField(ConfigureNodeFields.replyroom, FormField.Type.list_multi); - setAnswer(ConfigureNodeFields.replyroom.getFieldName(), replyRooms); - } + /** + * Sets the multi user chat rooms that are specified as reply rooms. + * + * @param replyRooms The multi user chat room to use as reply rooms + */ + public void setReplyRoom(List replyRooms) + { + addField(ConfigureNodeFields.replyroom, FormField.Type.list_multi); + setAnswer(ConfigureNodeFields.replyroom.getFieldName(), replyRooms); + } - /** - * Gets the specific JID's for reply to. - * - * @return The JID's - */ - public List getReplyTo() - { - return getFieldValues(ConfigureNodeFields.replyto); - } + /** + * Gets the specific JID's for reply to. + * + * @return The JID's + */ + public List getReplyTo() + { + return getFieldValues(ConfigureNodeFields.replyto); + } - /** - * Sets the specific JID's for reply to. - * - * @param replyTos The JID's to reply to - */ - public void setReplyTo(List replyTos) - { - addField(ConfigureNodeFields.replyto, FormField.Type.list_multi); - setAnswer(ConfigureNodeFields.replyto.getFieldName(), replyTos); - } + /** + * Sets the specific JID's for reply to. + * + * @param replyTos The JID's to reply to + */ + public void setReplyTo(List replyTos) + { + addField(ConfigureNodeFields.replyto, FormField.Type.list_multi); + setAnswer(ConfigureNodeFields.replyto.getFieldName(), replyTos); + } - /** - * Gets the roster groups that are allowed to subscribe and retrieve items. - * - * @return The roster groups - */ - public List getRosterGroupsAllowed() - { - return getFieldValues(ConfigureNodeFields.roster_groups_allowed); - } + /** + * Gets the roster groups that are allowed to subscribe and retrieve items. + * + * @return The roster groups + */ + public List getRosterGroupsAllowed() + { + return getFieldValues(ConfigureNodeFields.roster_groups_allowed); + } - /** - * Sets the roster groups that are allowed to subscribe and retrieve items. - * - * @param groups The roster groups - */ - public void setRosterGroupsAllowed(List groups) - { - addField(ConfigureNodeFields.roster_groups_allowed, FormField.Type.list_multi); - setAnswer(ConfigureNodeFields.roster_groups_allowed.getFieldName(), groups); - } + /** + * Sets the roster groups that are allowed to subscribe and retrieve items. + * + * @param groups The roster groups + */ + public void setRosterGroupsAllowed(List groups) + { + addField(ConfigureNodeFields.roster_groups_allowed, FormField.Type.list_multi); + setAnswer(ConfigureNodeFields.roster_groups_allowed.getFieldName(), groups); + } - /** - * Determines if subscriptions are allowed. - * - * @return true if subscriptions are allowed, false otherwise - * @deprecated use {@link #isSubscribe()} instead - */ - @Deprecated - public boolean isSubscibe() - { - return isSubscribe(); - } + /** + * Determines if subscriptions are allowed. + * + * @return true if subscriptions are allowed, false otherwise + * @deprecated use {@link #isSubscribe()} instead + */ + @Deprecated + public boolean isSubscibe() + { + return isSubscribe(); + } /** * Determines if subscriptions are allowed. @@ -594,124 +594,126 @@ public class ConfigureForm extends Form return parseBoolean(getFieldValue(ConfigureNodeFields.subscribe)); } - /** - * Sets whether subscriptions are allowed. - * - * @param subscribe true if they are, false otherwise - */ - public void setSubscribe(boolean subscribe) - { - addField(ConfigureNodeFields.subscribe, FormField.Type.bool); - setAnswer(ConfigureNodeFields.subscribe.getFieldName(), subscribe); - } + /** + * Sets whether subscriptions are allowed. + * + * @param subscribe true if they are, false otherwise + */ + public void setSubscribe(boolean subscribe) + { + addField(ConfigureNodeFields.subscribe, FormField.Type.bool); + setAnswer(ConfigureNodeFields.subscribe.getFieldName(), subscribe); + } - /** - * Gets the human readable node title. - * - * @return The node title - */ - public String getTitle() - { - return getFieldValue(ConfigureNodeFields.title); - } + /** + * Gets the human readable node title. + * + * @return The node title + */ + @Override + public String getTitle() + { + return getFieldValue(ConfigureNodeFields.title); + } - /** - * Sets a human readable title for the node. - * - * @param title The node title - */ - public void setTitle(String title) - { - addField(ConfigureNodeFields.title, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.title.getFieldName(), title); - } + /** + * Sets a human readable title for the node. + * + * @param title The node title + */ + @Override + public void setTitle(String title) + { + addField(ConfigureNodeFields.title, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.title.getFieldName(), title); + } - /** - * The type of node data, usually specified by the namespace of the payload (if any). - * - * @return The type of node data - */ - public String getDataType() - { - return getFieldValue(ConfigureNodeFields.type); - } + /** + * The type of node data, usually specified by the namespace of the payload (if any). + * + * @return The type of node data + */ + public String getDataType() + { + return getFieldValue(ConfigureNodeFields.type); + } - /** - * Sets the type of node data, usually specified by the namespace of the payload (if any). - * - * @param type The type of node data - */ - public void setDataType(String type) - { - addField(ConfigureNodeFields.type, FormField.Type.text_single); - setAnswer(ConfigureNodeFields.type.getFieldName(), type); - } + /** + * Sets the type of node data, usually specified by the namespace of the payload (if any). + * + * @param type The type of node data + */ + public void setDataType(String type) + { + addField(ConfigureNodeFields.type, FormField.Type.text_single); + setAnswer(ConfigureNodeFields.type.getFieldName(), type); + } - @Override - public String toString() - { - StringBuilder result = new StringBuilder(getClass().getName() + " Content ["); + @Override + public String toString() + { + StringBuilder result = new StringBuilder(getClass().getName() + " Content ["); - for (FormField formField : getFields()) - { - result.append('('); - result.append(formField.getVariable()); - result.append(':'); + for (FormField formField : getFields()) + { + result.append('('); + result.append(formField.getVariable()); + result.append(':'); - StringBuilder valuesBuilder = new StringBuilder(); + StringBuilder valuesBuilder = new StringBuilder(); - for (String value : formField.getValues()) - { - if (valuesBuilder.length() > 0) - result.append(','); - valuesBuilder.append(value); - } + for (String value : formField.getValues()) + { + if (valuesBuilder.length() > 0) + result.append(','); + valuesBuilder.append(value); + } - if (valuesBuilder.length() == 0) - valuesBuilder.append("NOT SET"); - result.append(valuesBuilder); - result.append(')'); - } - result.append(']'); - return result.toString(); - } + if (valuesBuilder.length() == 0) + valuesBuilder.append("NOT SET"); + result.append(valuesBuilder); + result.append(')'); + } + result.append(']'); + return result.toString(); + } - static private boolean parseBoolean(String fieldValue) - { - return ("1".equals(fieldValue) || "true".equals(fieldValue)); - } + static private boolean parseBoolean(String fieldValue) + { + return ("1".equals(fieldValue) || "true".equals(fieldValue)); + } - private String getFieldValue(ConfigureNodeFields field) - { - FormField formField = getField(field.getFieldName()); + private String getFieldValue(ConfigureNodeFields field) + { + FormField formField = getField(field.getFieldName()); - return (formField.getValues().isEmpty()) ? null : formField.getValues().get(0); - } + return (formField.getValues().isEmpty()) ? null : formField.getValues().get(0); + } - private List getFieldValues(ConfigureNodeFields field) - { - FormField formField = getField(field.getFieldName()); + private List getFieldValues(ConfigureNodeFields field) + { + FormField formField = getField(field.getFieldName()); - return formField.getValues(); - } + return formField.getValues(); + } - private void addField(ConfigureNodeFields nodeField, FormField.Type type) - { - String fieldName = nodeField.getFieldName(); + private void addField(ConfigureNodeFields nodeField, FormField.Type type) + { + String fieldName = nodeField.getFieldName(); - if (getField(fieldName) == null) - { - FormField field = new FormField(fieldName); - field.setType(type); - addField(field); - } - } + if (getField(fieldName) == null) + { + FormField field = new FormField(fieldName); + field.setType(type); + addField(field); + } + } - private static List getListSingle(String value) - { - List list = new ArrayList(1); - list.add(value); - return list; - } + private static List getListSingle(String value) + { + List list = new ArrayList(1); + list.add(value); + return list; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureNodeFields.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureNodeFields.java index 7a3797a6a..47d01b80a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureNodeFields.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ConfigureNodeFields.java @@ -29,193 +29,193 @@ import org.jivesoftware.smackx.xdata.Form; */ public enum ConfigureNodeFields { - /** - * Determines who may subscribe and retrieve items. - * - *

Value: {@link AccessModel}

- */ - access_model, + /** + * Determines who may subscribe and retrieve items. + * + *

Value: {@link AccessModel}

+ */ + access_model, - /** - * The URL of an XSL transformation which can be applied to - * payloads in order to generate an appropriate message - * body element. - * - *

Value: {@link URL}

- */ - body_xslt, + /** + * The URL of an XSL transformation which can be applied to + * payloads in order to generate an appropriate message + * body element. + * + *

Value: {@link URL}

+ */ + body_xslt, - /** - * The collection with which a node is affiliated. - * - *

Value: String

- */ - collection, + /** + * The collection with which a node is affiliated. + * + *

Value: String

+ */ + collection, - /** - * The URL of an XSL transformation which can be applied to - * payload format in order to generate a valid Data Forms result - * that the client could display using a generic Data Forms - * rendering engine body element. - * - *

Value: {@link URL}

- */ - dataform_xslt, + /** + * The URL of an XSL transformation which can be applied to + * payload format in order to generate a valid Data Forms result + * that the client could display using a generic Data Forms + * rendering engine body element. + * + *

Value: {@link URL}

+ */ + dataform_xslt, - /** - * Whether to deliver payloads with event notifications. - * - *

Value: boolean

- */ - deliver_payloads, + /** + * Whether to deliver payloads with event notifications. + * + *

Value: boolean

+ */ + deliver_payloads, - /** - * Whether owners or publisher should receive replies to items. - * - *

Value: {@link ItemReply}

- */ - itemreply, + /** + * Whether owners or publisher should receive replies to items. + * + *

Value: {@link ItemReply}

+ */ + itemreply, - /** - * Who may associate leaf nodes with a collection. - * - *

Value: {@link ChildrenAssociationPolicy}

- */ - children_association_policy, + /** + * Who may associate leaf nodes with a collection. + * + *

Value: {@link ChildrenAssociationPolicy}

+ */ + children_association_policy, - /** - * The list of JIDs that may associate leaf nodes with a - * collection. - * - *

Value: List of JIDs as Strings

- */ - children_association_whitelist, + /** + * The list of JIDs that may associate leaf nodes with a + * collection. + * + *

Value: List of JIDs as Strings

+ */ + children_association_whitelist, - /** - * The child nodes (leaf or collection) associated with a collection. - * - *

Value: List of Strings

- */ - children, + /** + * The child nodes (leaf or collection) associated with a collection. + * + *

Value: List of Strings

+ */ + children, - /** - * The maximum number of child nodes that can be associated with a - * collection. - * - *

Value: int

- */ - children_max, + /** + * The maximum number of child nodes that can be associated with a + * collection. + * + *

Value: int

+ */ + children_max, - /** - * The maximum number of items to persist. - * - *

Value: int

- */ - max_items, + /** + * The maximum number of items to persist. + * + *

Value: int

+ */ + max_items, - /** - * The maximum payload size in bytes. - * - *

Value: int

- */ - max_payload_size, + /** + * The maximum payload size in bytes. + * + *

Value: int

+ */ + max_payload_size, - /** - * Whether the node is a leaf (default) or collection. - * - *

Value: {@link NodeType}

- */ - node_type, + /** + * Whether the node is a leaf (default) or collection. + * + *

Value: {@link NodeType}

+ */ + node_type, - /** - * Whether to notify subscribers when the node configuration changes. - * - *

Value: boolean

- */ - notify_config, + /** + * Whether to notify subscribers when the node configuration changes. + * + *

Value: boolean

+ */ + notify_config, - /** - * Whether to notify subscribers when the node is deleted. - * - *

Value: boolean

- */ - notify_delete, + /** + * Whether to notify subscribers when the node is deleted. + * + *

Value: boolean

+ */ + notify_delete, - /** - * Whether to notify subscribers when items are removed from the node. - * - *

Value: boolean

- */ - notify_retract, + /** + * Whether to notify subscribers when items are removed from the node. + * + *

Value: boolean

+ */ + notify_retract, - /** - * Whether to persist items to storage. This is required to have. multiple - * items in the node. - * - *

Value: boolean

- */ - persist_items, + /** + * Whether to persist items to storage. This is required to have. multiple + * items in the node. + * + *

Value: boolean

+ */ + persist_items, - /** - * Whether to deliver notifications to available users only. - * - *

Value: boolean

- */ - presence_based_delivery, + /** + * Whether to deliver notifications to available users only. + * + *

Value: boolean

+ */ + presence_based_delivery, - /** - * Defines who can publish to the node. - * - *

Value: {@link PublishModel}

- */ - publish_model, + /** + * Defines who can publish to the node. + * + *

Value: {@link PublishModel}

+ */ + publish_model, - /** - * The specific multi-user chat rooms to specify for replyroom. - * - *

Value: List of JIDs as Strings

- */ - replyroom, + /** + * The specific multi-user chat rooms to specify for replyroom. + * + *

Value: List of JIDs as Strings

+ */ + replyroom, - /** - * The specific JID(s) to specify for replyto. - * - *

Value: List of JIDs as Strings

- */ - replyto, + /** + * The specific JID(s) to specify for replyto. + * + *

Value: List of JIDs as Strings

+ */ + replyto, - /** - * The roster group(s) allowed to subscribe and retrieve items. - * - *

Value: List of strings

- */ - roster_groups_allowed, + /** + * The roster group(s) allowed to subscribe and retrieve items. + * + *

Value: List of strings

+ */ + roster_groups_allowed, - /** - * Whether to allow subscriptions. - * - *

Value: boolean

- */ - subscribe, + /** + * Whether to allow subscriptions. + * + *

Value: boolean

+ */ + subscribe, - /** - * A friendly name for the node. - * - *

Value: String

- */ - title, + /** + * A friendly name for the node. + * + *

Value: String

+ */ + title, - /** - * The type of node data, ussually specified by the namespace - * of the payload(if any);MAY be a list-single rather than a - * text single. - * - *

Value: String

- */ - type; + /** + * The type of node data, ussually specified by the namespace + * of the payload(if any);MAY be a list-single rather than a + * text single. + * + *

Value: String

+ */ + type; - public String getFieldName() - { - return "pubsub#" + toString(); - } + public String getFieldName() + { + return "pubsub#" + toString(); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EmbeddedPacketExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EmbeddedPacketExtension.java index b32a6e637..841a20cd8 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EmbeddedPacketExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EmbeddedPacketExtension.java @@ -39,10 +39,10 @@ import org.jivesoftware.smack.util.PacketParserUtils; */ public interface EmbeddedPacketExtension extends ExtensionElement { - /** - * Get the list of embedded {@link ExtensionElement} objects. - * - * @return List of embedded {@link ExtensionElement} - */ - List getExtensions(); + /** + * Get the list of embedded {@link ExtensionElement} objects. + * + * @return List of embedded {@link ExtensionElement} + */ + List getExtensions(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElement.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElement.java index cca9c2ae2..2d03cc896 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElement.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElement.java @@ -44,39 +44,42 @@ public class EventElement implements EmbeddedPacketExtension */ public static final String NAMESPACE = PubSubNamespace.EVENT.getXmlns(); - private EventElementType type; - private NodeExtension ext; + private EventElementType type; + private NodeExtension ext; - public EventElement(EventElementType eventType, NodeExtension eventExt) - { - type = eventType; - ext = eventExt; - } + public EventElement(EventElementType eventType, NodeExtension eventExt) + { + type = eventType; + ext = eventExt; + } - public EventElementType getEventType() - { - return type; - } + public EventElementType getEventType() + { + return type; + } - public List getExtensions() - { - return Arrays.asList(new ExtensionElement[]{getEvent()}); - } + @Override + public List getExtensions() + { + return Arrays.asList(new ExtensionElement[]{getEvent()}); + } - public NodeExtension getEvent() - { - return ext; - } + public NodeExtension getEvent() + { + return ext; + } - public String getElementName() - { - return "event"; - } + @Override + public String getElementName() + { + return "event"; + } - public String getNamespace() - { - return PubSubNamespace.EVENT.getXmlns(); - } + @Override + public String getNamespace() + { + return PubSubNamespace.EVENT.getXmlns(); + } @Override public XmlStringBuilder toXML() { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElementType.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElementType.java index e02de606b..0850e7d92 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElementType.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/EventElementType.java @@ -24,21 +24,21 @@ package org.jivesoftware.smackx.pubsub; */ public enum EventElementType { - /** A node has been associated or dissassociated with a collection node. */ - collection, + /** A node has been associated or dissassociated with a collection node. */ + collection, - /** A node has had its configuration changed. */ - configuration, + /** A node has had its configuration changed. */ + configuration, - /** A node has been deleted. */ - delete, + /** A node has been deleted. */ + delete, - /** Items have been published to a node. */ - items, + /** Items have been published to a node. */ + items, - /** All items have been purged from a node. */ - purge, + /** All items have been purged from a node. */ + purge, - /** A node has been subscribed to. */ - subscription + /** A node has been subscribed to. */ + subscription } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNode.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNode.java index 6be866197..5940c6aaf 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNode.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNode.java @@ -28,75 +28,75 @@ import org.jivesoftware.smackx.xdata.Form; */ public class FormNode extends NodeExtension { - private Form configForm; + private Form configForm; - /** - * Create a {@link FormNode} which contains the specified form. - * - * @param formType The type of form being sent - * @param submitForm The form - */ - public FormNode(FormNodeType formType, Form submitForm) - { - super(formType.getNodeElement()); + /** + * Create a {@link FormNode} which contains the specified form. + * + * @param formType The type of form being sent + * @param submitForm The form + */ + public FormNode(FormNodeType formType, Form submitForm) + { + super(formType.getNodeElement()); - if (submitForm == null) - throw new IllegalArgumentException("Submit form cannot be null"); - configForm = submitForm; - } + if (submitForm == null) + throw new IllegalArgumentException("Submit form cannot be null"); + configForm = submitForm; + } - /** - * Create a {@link FormNode} which contains the specified form, which is - * associated with the specified node. - * - * @param formType The type of form being sent - * @param nodeId The node the form is associated with - * @param submitForm The form - */ - public FormNode(FormNodeType formType, String nodeId, Form submitForm) - { - super(formType.getNodeElement(), nodeId); + /** + * Create a {@link FormNode} which contains the specified form, which is + * associated with the specified node. + * + * @param formType The type of form being sent + * @param nodeId The node the form is associated with + * @param submitForm The form + */ + public FormNode(FormNodeType formType, String nodeId, Form submitForm) + { + super(formType.getNodeElement(), nodeId); - if (submitForm == null) - throw new IllegalArgumentException("Submit form cannot be null"); - configForm = submitForm; - } + if (submitForm == null) + throw new IllegalArgumentException("Submit form cannot be null"); + configForm = submitForm; + } - /** - * Get the Form that is to be sent, or was retrieved from the server. - * - * @return The form - */ - public Form getForm() - { - return configForm; - } + /** + * Get the Form that is to be sent, or was retrieved from the server. + * + * @return The form + */ + public Form getForm() + { + return configForm; + } - @Override - public CharSequence toXML() - { - if (configForm == null) - { - return super.toXML(); - } - else - { - StringBuilder builder = new StringBuilder("<"); - builder.append(getElementName()); + @Override + public CharSequence toXML() + { + if (configForm == null) + { + return super.toXML(); + } + else + { + StringBuilder builder = new StringBuilder("<"); + builder.append(getElementName()); - if (getNode() != null) - { - builder.append(" node='"); - builder.append(getNode()); - builder.append("'>"); - } - else - builder.append('>'); - builder.append(configForm.getDataFormToSend().toXML()); - builder.append("'); - return builder.toString(); - } - } + if (getNode() != null) + { + builder.append(" node='"); + builder.append(getNode()); + builder.append("'>"); + } + else + builder.append('>'); + builder.append(configForm.getDataFormToSend().toXML()); + builder.append("'); + return builder.toString(); + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNodeType.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNodeType.java index 95532f5fb..c8bed54c4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNodeType.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/FormNodeType.java @@ -27,29 +27,29 @@ import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace; */ public enum FormNodeType { - /** Form for configuring an existing node. */ - CONFIGURE_OWNER, + /** Form for configuring an existing node. */ + CONFIGURE_OWNER, - /** Form for configuring a node during creation. */ - CONFIGURE, + /** Form for configuring a node during creation. */ + CONFIGURE, - /** Form for configuring subscription options. */ - OPTIONS, + /** Form for configuring subscription options. */ + OPTIONS, - /** Form which represents the default node configuration options. */ - DEFAULT; + /** Form which represents the default node configuration options. */ + DEFAULT; - public PubSubElementType getNodeElement() - { - return PubSubElementType.valueOf(toString()); - } + public PubSubElementType getNodeElement() + { + return PubSubElementType.valueOf(toString()); + } - public static FormNodeType valueOfFromElementName(String elem, String configNamespace) - { - if ("configure".equals(elem) && PubSubNamespace.OWNER.getXmlns().equals(configNamespace)) - { - return CONFIGURE_OWNER; - } - return valueOf(elem.toUpperCase(Locale.US)); - } + public static FormNodeType valueOfFromElementName(String elem, String configNamespace) + { + if ("configure".equals(elem) && PubSubNamespace.OWNER.getXmlns().equals(configNamespace)) + { + return CONFIGURE_OWNER; + } + return valueOf(elem.toUpperCase(Locale.US)); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/GetItemsRequest.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/GetItemsRequest.java index 1d29ab1e2..05b94b716 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/GetItemsRequest.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/GetItemsRequest.java @@ -25,42 +25,42 @@ import org.jivesoftware.smack.util.XmlStringBuilder; */ public class GetItemsRequest extends NodeExtension { - protected final String subId; - protected final int maxItems; + protected final String subId; + protected final int maxItems; - public GetItemsRequest(String nodeId) - { - this(nodeId, null, -1); - } + public GetItemsRequest(String nodeId) + { + this(nodeId, null, -1); + } - public GetItemsRequest(String nodeId, String subscriptionId) - { + public GetItemsRequest(String nodeId, String subscriptionId) + { this(nodeId, subscriptionId, -1); - } + } - public GetItemsRequest(String nodeId, int maxItemsToReturn) - { + public GetItemsRequest(String nodeId, int maxItemsToReturn) + { this(nodeId, null, maxItemsToReturn); - } + } - public GetItemsRequest(String nodeId, String subscriptionId, int maxItemsToReturn) - { + public GetItemsRequest(String nodeId, String subscriptionId, int maxItemsToReturn) + { super(PubSubElementType.ITEMS, nodeId); maxItems = maxItemsToReturn; - subId = subscriptionId; - } + subId = subscriptionId; + } - public String getSubscriptionId() - { - return subId; - } + public String getSubscriptionId() + { + return subId; + } - public int getMaxItems() - { - return maxItems; - } + public int getMaxItems() + { + return maxItems; + } - @Override + @Override public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(); xml.halfOpenElement(getElementName()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Item.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Item.java index 177f222d3..0e5eac49d 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Item.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Item.java @@ -50,94 +50,92 @@ import org.jivesoftware.smackx.pubsub.provider.ItemProvider; */ public class Item extends NodeExtension { - private String id; + private String id; - /** - * Create an empty Item with no id. This is a valid item for nodes which are configured - * so that {@link ConfigureForm#isDeliverPayloads()} is false. In most cases an id will be generated by the server. - * For nodes configured with {@link ConfigureForm#isDeliverPayloads()} and {@link ConfigureForm#isPersistItems()} - * set to false, no Item is sent to the node, you have to use {@link LeafNode#send()} or {@link LeafNode#publish()} - * methods in this case. - */ - public Item() - { - super(PubSubElementType.ITEM); - } - - /** - * Create an Item with an id but no payload. This is a valid item for nodes which are configured - * so that {@link ConfigureForm#isDeliverPayloads()} is false. - * - * @param itemId The id if the item. It must be unique within the node unless overwriting and existing item. - * Passing null is the equivalent of calling {@link #Item()}. - */ - public Item(String itemId) - { - // The element type is actually irrelevant since we override getNamespace() to return null - super(PubSubElementType.ITEM); - id = itemId; - } - - /** - * Create an Item with an id and a node id. - *

- * Note: This is not valid for publishing an item to a node, only receiving from - * one as part of {@link Message}. If used to create an Item to publish - * (via {@link LeafNode#publish(Item)}, the server may return an - * error for an invalid packet. - * - * @param itemId The id of the item. - * @param nodeId The id of the node which the item was published to. - */ - public Item(String itemId, String nodeId) + /** + * Create an empty Item with no id. This is a valid item for nodes which are configured + * so that {@link ConfigureForm#isDeliverPayloads()} is false. In most cases an id will be generated by the server. + * For nodes configured with {@link ConfigureForm#isDeliverPayloads()} and {@link ConfigureForm#isPersistItems()} + * set to false, no Item is sent to the node, you have to use {@link LeafNode#send()} or {@link LeafNode#publish()} + * methods in this case. + */ + public Item() { - // CHECKSTYLE:OFF - super(PubSubElementType.ITEM_EVENT, nodeId); - // CHECKSTYLE:ON + super(PubSubElementType.ITEM); + } + + /** + * Create an Item with an id but no payload. This is a valid item for nodes which are configured + * so that {@link ConfigureForm#isDeliverPayloads()} is false. + * + * @param itemId The id if the item. It must be unique within the node unless overwriting and existing item. + * Passing null is the equivalent of calling {@link #Item()}. + */ + public Item(String itemId) + { + // The element type is actually irrelevant since we override getNamespace() to return null + super(PubSubElementType.ITEM); id = itemId; } - /** - * Get the item id. Unique to the node it is associated with. - * - * @return The id - */ - public String getId() - { - return id; - } + /** + * Create an Item with an id and a node id. + *

+ * Note: This is not valid for publishing an item to a node, only receiving from + * one as part of {@link Message}. If used to create an Item to publish + * (via {@link LeafNode#publish(Item)}, the server may return an + * error for an invalid packet. + * + * @param itemId The id of the item. + * @param nodeId The id of the node which the item was published to. + */ + public Item(String itemId, String nodeId) + { + super(PubSubElementType.ITEM_EVENT, nodeId); + id = itemId; + } - @Override - public String getNamespace() - { - return null; - } + /** + * Get the item id. Unique to the node it is associated with. + * + * @return The id + */ + public String getId() + { + return id; + } - @Override - public String toXML() - { - StringBuilder builder = new StringBuilder(""); + builder.append("/>"); - return builder.toString(); - } + return builder.toString(); + } - @Override - public String toString() - { - return getClass().getName() + " | Content [" + toXML() + "]"; - } + @Override + public String toString() + { + return getClass().getName() + " | Content [" + toXML() + "]"; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemDeleteEvent.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemDeleteEvent.java index 4bfbe30d6..d2fbf1b18 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemDeleteEvent.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemDeleteEvent.java @@ -26,40 +26,40 @@ import java.util.List; */ public class ItemDeleteEvent extends SubscriptionEvent { - private List itemIds = Collections.emptyList(); + private List itemIds = Collections.emptyList(); - /** - * Constructs an ItemDeleteEvent that indicates the the supplied - * items (by id) have been deleted, and that the event matches the listed - * subscriptions. The subscriptions would have been created by calling - * {@link LeafNode#subscribe(String)}. - * - * @param nodeId The id of the node the event came from - * @param deletedItemIds The item ids of the items that were deleted. - * @param subscriptionIds The subscriptions that match the event. - */ - public ItemDeleteEvent(String nodeId, List deletedItemIds, List subscriptionIds) - { - super(nodeId, subscriptionIds); + /** + * Constructs an ItemDeleteEvent that indicates the the supplied + * items (by id) have been deleted, and that the event matches the listed + * subscriptions. The subscriptions would have been created by calling + * {@link LeafNode#subscribe(String)}. + * + * @param nodeId The id of the node the event came from + * @param deletedItemIds The item ids of the items that were deleted. + * @param subscriptionIds The subscriptions that match the event. + */ + public ItemDeleteEvent(String nodeId, List deletedItemIds, List subscriptionIds) + { + super(nodeId, subscriptionIds); - if (deletedItemIds == null) - throw new IllegalArgumentException("deletedItemIds cannot be null"); - itemIds = deletedItemIds; - } + if (deletedItemIds == null) + throw new IllegalArgumentException("deletedItemIds cannot be null"); + itemIds = deletedItemIds; + } - /** - * Get the item id's of the items that have been deleted. - * - * @return List of item id's - */ - public List getItemIds() - { - return Collections.unmodifiableList(itemIds); - } + /** + * Get the item id's of the items that have been deleted. + * + * @return List of item id's + */ + public List getItemIds() + { + return Collections.unmodifiableList(itemIds); + } - @Override - public String toString() - { - return getClass().getName() + " [subscriptions: " + getSubscriptions() + "], [Deleted Items: " + itemIds + ']'; - } + @Override + public String toString() + { + return getClass().getName() + " [subscriptions: " + getSubscriptions() + "], [Deleted Items: " + itemIds + ']'; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemPublishEvent.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemPublishEvent.java index ed49eb2fb..980797bdb 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemPublishEvent.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemPublishEvent.java @@ -27,98 +27,98 @@ import java.util.List; */ public class ItemPublishEvent extends SubscriptionEvent { - private List items; - private Date originalDate; + private List items; + private Date originalDate; - /** - * Constructs an ItemPublishEvent with the provided list - * of {@link Item} that were published. - * - * @param nodeId The id of the node the event came from - * @param eventItems The list of {@link Item} that were published - */ - public ItemPublishEvent(String nodeId, List eventItems) - { - super(nodeId); - items = eventItems; - } + /** + * Constructs an ItemPublishEvent with the provided list + * of {@link Item} that were published. + * + * @param nodeId The id of the node the event came from + * @param eventItems The list of {@link Item} that were published + */ + public ItemPublishEvent(String nodeId, List eventItems) + { + super(nodeId); + items = eventItems; + } - /** - * Constructs an ItemPublishEvent with the provided list - * of {@link Item} that were published. The list of subscription ids - * represents the subscriptions that matched the event, in the case - * of the user having multiple subscriptions. - * - * @param nodeId The id of the node the event came from - * @param eventItems The list of {@link Item} that were published - * @param subscriptionIds The list of subscriptionIds - */ - public ItemPublishEvent(String nodeId, List eventItems, List subscriptionIds) - { - super(nodeId, subscriptionIds); - items = eventItems; - } + /** + * Constructs an ItemPublishEvent with the provided list + * of {@link Item} that were published. The list of subscription ids + * represents the subscriptions that matched the event, in the case + * of the user having multiple subscriptions. + * + * @param nodeId The id of the node the event came from + * @param eventItems The list of {@link Item} that were published + * @param subscriptionIds The list of subscriptionIds + */ + public ItemPublishEvent(String nodeId, List eventItems, List subscriptionIds) + { + super(nodeId, subscriptionIds); + items = eventItems; + } - /** - * Constructs an ItemPublishEvent with the provided list - * of {@link Item} that were published in the past. The published - * date signifies that this is delayed event. The list of subscription ids - * represents the subscriptions that matched the event, in the case - * of the user having multiple subscriptions. - * - * @param nodeId The id of the node the event came from - * @param eventItems The list of {@link Item} that were published - * @param subscriptionIds The list of subscriptionIds - */ - public ItemPublishEvent(String nodeId, List eventItems, List subscriptionIds, Date publishedDate) - { - super(nodeId, subscriptionIds); - items = eventItems; + /** + * Constructs an ItemPublishEvent with the provided list + * of {@link Item} that were published in the past. The published + * date signifies that this is delayed event. The list of subscription ids + * represents the subscriptions that matched the event, in the case + * of the user having multiple subscriptions. + * + * @param nodeId The id of the node the event came from + * @param eventItems The list of {@link Item} that were published + * @param subscriptionIds The list of subscriptionIds + */ + public ItemPublishEvent(String nodeId, List eventItems, List subscriptionIds, Date publishedDate) + { + super(nodeId, subscriptionIds); + items = eventItems; - if (publishedDate != null) - originalDate = publishedDate; - } + if (publishedDate != null) + originalDate = publishedDate; + } - /** - * Get the list of {@link Item} that were published. - * - * @return The list of published {@link Item} - */ - public List getItems() - { - return Collections.unmodifiableList(items); - } + /** + * Get the list of {@link Item} that were published. + * + * @return The list of published {@link Item} + */ + public List getItems() + { + return Collections.unmodifiableList(items); + } - /** - * Indicates whether this event was delayed. That is, the items - * were published to the node at some time in the past. This will - * typically happen if there is an item already published to the node - * before a user subscribes to it. In this case, when the user - * subscribes, the server may send the last item published to the node - * with a delay date showing its time of original publication. - * - * @return true if the items are delayed, false otherwise. - */ - public boolean isDelayed() - { - return (originalDate != null); - } + /** + * Indicates whether this event was delayed. That is, the items + * were published to the node at some time in the past. This will + * typically happen if there is an item already published to the node + * before a user subscribes to it. In this case, when the user + * subscribes, the server may send the last item published to the node + * with a delay date showing its time of original publication. + * + * @return true if the items are delayed, false otherwise. + */ + public boolean isDelayed() + { + return (originalDate != null); + } - /** - * Gets the original date the items were published. This is only - * valid if {@link #isDelayed()} is true. - * - */ - public Date getPublishedDate() - { - return originalDate; - } + /** + * Gets the original date the items were published. This is only + * valid if {@link #isDelayed()} is true. + * + */ + public Date getPublishedDate() + { + return originalDate; + } - @Override - public String toString() - { - return getClass().getName() + " [subscriptions: " + getSubscriptions() + "], [Delayed: " + - (isDelayed() ? originalDate.toString() : "false") + ']'; - } + @Override + public String toString() + { + return getClass().getName() + " [subscriptions: " + getSubscriptions() + "], [Delayed: " + + (isDelayed() ? originalDate.toString() : "false") + ']'; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemReply.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemReply.java index 6928c6d79..3d39e82e5 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemReply.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemReply.java @@ -24,9 +24,9 @@ package org.jivesoftware.smackx.pubsub; */ public enum ItemReply { - /** The node owner. */ - owner, + /** The node owner. */ + owner, - /** The item publisher. */ - publisher; + /** The item publisher. */ + publisher; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemsExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemsExtension.java index 69ec1b7af..6b53fd408 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemsExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/ItemsExtension.java @@ -36,168 +36,169 @@ import org.jivesoftware.smack.packet.ExtensionElement; */ public class ItemsExtension extends NodeExtension implements EmbeddedPacketExtension { - protected ItemsElementType type; - protected Boolean notify; - protected List items; + protected ItemsElementType type; + protected Boolean notify; + protected List items; - public enum ItemsElementType - { - /** An items element, which has an optional max_items attribute when requesting items. */ - items(PubSubElementType.ITEMS, "max_items"), + public enum ItemsElementType + { + /** An items element, which has an optional max_items attribute when requesting items. */ + items(PubSubElementType.ITEMS, "max_items"), - /** A retract element, which has an optional notify attribute when publishing deletions. */ - retract(PubSubElementType.RETRACT, "notify"); + /** A retract element, which has an optional notify attribute when publishing deletions. */ + retract(PubSubElementType.RETRACT, "notify"); - private PubSubElementType elem; - private String att; + private final PubSubElementType elem; + private final String att; - private ItemsElementType(PubSubElementType nodeElement, String attribute) - { - elem = nodeElement; - att = attribute; - } + private ItemsElementType(PubSubElementType nodeElement, String attribute) + { + elem = nodeElement; + att = attribute; + } - public PubSubElementType getNodeElement() - { - return elem; - } + public PubSubElementType getNodeElement() + { + return elem; + } - public String getElementAttribute() - { - return att; - } - } + public String getElementAttribute() + { + return att; + } + } - /** - * Construct an instance with a list representing items that have been published or deleted. - * - *

Valid scenarios are:

- *
    - *
  • Request items from node - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and an - * optional value for the max_items attribute. - *
  • Request to delete items - itemsType = {@link ItemsElementType#retract}, items = list of {@link Item} containing - * only id's and an optional value for the notify attribute. - *
  • Items published event - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and - * attributeValue = null - *
  • Items deleted event - itemsType = {@link ItemsElementType#items}, items = list of {@link RetractItem} and - * attributeValue = null - *
- * - * @param itemsType Type of representation - * @param nodeId The node to which the items are being sent or deleted - * @param items The list of {@link Item} or {@link RetractItem} - */ - public ItemsExtension(ItemsElementType itemsType, String nodeId, List items) - { - super(itemsType.getNodeElement(), nodeId); - type = itemsType; - this.items = items; - } + /** + * Construct an instance with a list representing items that have been published or deleted. + * + *

Valid scenarios are:

+ *
    + *
  • Request items from node - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and an + * optional value for the max_items attribute. + *
  • Request to delete items - itemsType = {@link ItemsElementType#retract}, items = list of {@link Item} containing + * only id's and an optional value for the notify attribute. + *
  • Items published event - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and + * attributeValue = null + *
  • Items deleted event - itemsType = {@link ItemsElementType#items}, items = list of {@link RetractItem} and + * attributeValue = null + *
+ * + * @param itemsType Type of representation + * @param nodeId The node to which the items are being sent or deleted + * @param items The list of {@link Item} or {@link RetractItem} + */ + public ItemsExtension(ItemsElementType itemsType, String nodeId, List items) + { + super(itemsType.getNodeElement(), nodeId); + type = itemsType; + this.items = items; + } - /** - * Construct an instance with a list representing items that have been published or deleted. - * - *

Valid scenarios are:

- *
    - *
  • Request items from node - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and an - * optional value for the max_items attribute. - *
  • Request to delete items - itemsType = {@link ItemsElementType#retract}, items = list of {@link Item} containing - * only id's and an optional value for the notify attribute. - *
  • Items published event - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and - * attributeValue = null - *
  • Items deleted event - itemsType = {@link ItemsElementType#items}, items = list of {@link RetractItem} and - * attributeValue = null - *
- * - * @param nodeId The node to which the items are being sent or deleted - * @param items The list of {@link Item} or {@link RetractItem} - */ - public ItemsExtension(String nodeId, List items, boolean notify) - { - super(ItemsElementType.retract.getNodeElement(), nodeId); - type = ItemsElementType.retract; - this.items = items; - this.notify = notify; - } + /** + * Construct an instance with a list representing items that have been published or deleted. + * + *

Valid scenarios are:

+ *
    + *
  • Request items from node - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and an + * optional value for the max_items attribute. + *
  • Request to delete items - itemsType = {@link ItemsElementType#retract}, items = list of {@link Item} containing + * only id's and an optional value for the notify attribute. + *
  • Items published event - itemsType = {@link ItemsElementType#items}, items = list of {@link Item} and + * attributeValue = null + *
  • Items deleted event - itemsType = {@link ItemsElementType#items}, items = list of {@link RetractItem} and + * attributeValue = null + *
+ * + * @param nodeId The node to which the items are being sent or deleted + * @param items The list of {@link Item} or {@link RetractItem} + */ + public ItemsExtension(String nodeId, List items, boolean notify) + { + super(ItemsElementType.retract.getNodeElement(), nodeId); + type = ItemsElementType.retract; + this.items = items; + this.notify = notify; + } - /** - * Get the type of element. - * - * @return The element type - */ - public ItemsElementType getItemsElementType() - { - return type; - } + /** + * Get the type of element. + * + * @return The element type + */ + public ItemsElementType getItemsElementType() + { + return type; + } - @SuppressWarnings("unchecked") - public List getExtensions() - { - return (List)getItems(); - } + @Override + @SuppressWarnings("unchecked") + public List getExtensions() + { + return (List)getItems(); + } - /** - * Gets the items related to the type of request or event. - * - * return List of {@link Item}, {@link RetractItem}, or null - */ - public List getItems() - { - return items; - } + /** + * Gets the items related to the type of request or event. + * + * return List of {@link Item}, {@link RetractItem}, or null + */ + public List getItems() + { + return items; + } - /** - * Gets the value of the optional attribute related to the {@link ItemsElementType}. - * - * @return The attribute value - */ - public boolean getNotify() - { - return notify; - } + /** + * Gets the value of the optional attribute related to the {@link ItemsElementType}. + * + * @return The attribute value + */ + public boolean getNotify() + { + return notify; + } - @Override - public CharSequence toXML() - { - if ((items == null) || (items.size() == 0)) - { - return super.toXML(); - } - else - { - StringBuilder builder = new StringBuilder("<"); - builder.append(getElementName()); - builder.append(" node='"); - builder.append(getNode()); + @Override + public CharSequence toXML() + { + if ((items == null) || (items.size() == 0)) + { + return super.toXML(); + } + else + { + StringBuilder builder = new StringBuilder("<"); + builder.append(getElementName()); + builder.append(" node='"); + builder.append(getNode()); - if (notify != null) - { - builder.append("' "); - builder.append(type.getElementAttribute()); - builder.append("='"); - builder.append(notify.equals(Boolean.TRUE) ? 1 : 0); - builder.append("'>"); - } - else - { - builder.append("'>"); - for (ExtensionElement item : items) - { - builder.append(item.toXML()); - } - } + if (notify != null) + { + builder.append("' "); + builder.append(type.getElementAttribute()); + builder.append("='"); + builder.append(notify.equals(Boolean.TRUE) ? 1 : 0); + builder.append("'>"); + } + else + { + builder.append("'>"); + for (ExtensionElement item : items) + { + builder.append(item.toXML()); + } + } - builder.append("'); - return builder.toString(); - } - } + builder.append("'); + return builder.toString(); + } + } - @Override - public String toString() - { - return getClass().getName() + "Content [" + toXML() + "]"; - } + @Override + public String toString() + { + return getClass().getName() + "Content [" + toXML() + "]"; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/LeafNode.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/LeafNode.java index cf53afdd5..653fdbe7d 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/LeafNode.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/LeafNode.java @@ -38,125 +38,125 @@ import org.jivesoftware.smackx.pubsub.packet.PubSub; */ public class LeafNode extends Node { - LeafNode(PubSubManager pubSubManager, String nodeId) - { - super(pubSubManager, nodeId); - } + LeafNode(PubSubManager pubSubManager, String nodeId) + { + super(pubSubManager, nodeId); + } - /** - * Get information on the items in the node in standard - * {@link DiscoverItems} format. - * - * @return The item details in {@link DiscoverItems} format - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public DiscoverItems discoverItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - DiscoverItems items = new DiscoverItems(); - items.setTo(pubSubManager.getServiceJid()); - items.setNode(getId()); + /** + * Get information on the items in the node in standard + * {@link DiscoverItems} format. + * + * @return The item details in {@link DiscoverItems} format + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public DiscoverItems discoverItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + DiscoverItems items = new DiscoverItems(); + items.setTo(pubSubManager.getServiceJid()); + items.setNode(getId()); return pubSubManager.getConnection().createStanzaCollectorAndSend(items).nextResultOrThrow(); - } + } - /** - * Get the current items stored in the node. - * - * @return List of {@link Item} in the node - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { + /** + * Get the current items stored in the node. + * + * @return List of {@link Item} in the node + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { return getItems((List) null, (List) null); - } + } - /** - * Get the current items stored in the node based - * on the subscription associated with the provided - * subscription id. - * - * @param subscriptionId - The subscription id for the - * associated subscription. - * @return List of {@link Item} in the node - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getItems(String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), subscriptionId)); + /** + * Get the current items stored in the node based + * on the subscription associated with the provided + * subscription id. + * + * @param subscriptionId - The subscription id for the + * associated subscription. + * @return List of {@link Item} in the node + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getItems(String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), subscriptionId)); return getItems(request); - } + } - /** - * Get the items specified from the node. This would typically be - * used when the server does not return the payload due to size - * constraints. The user would be required to retrieve the payload - * after the items have been retrieved via {@link #getItems()} or an - * event, that did not include the payload. - * - * @param ids Item ids of the items to retrieve - * - * @return The list of {@link Item} with payload - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getItems(Collection ids) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - List itemList = new ArrayList(ids.size()); + /** + * Get the items specified from the node. This would typically be + * used when the server does not return the payload due to size + * constraints. The user would be required to retrieve the payload + * after the items have been retrieved via {@link #getItems()} or an + * event, that did not include the payload. + * + * @param ids Item ids of the items to retrieve + * + * @return The list of {@link Item} with payload + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getItems(Collection ids) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + List itemList = new ArrayList(ids.size()); - for (String id : ids) - { - itemList.add(new Item(id)); - } - PubSub request = createPubsubPacket(Type.get, new ItemsExtension(ItemsExtension.ItemsElementType.items, getId(), itemList)); + for (String id : ids) + { + itemList.add(new Item(id)); + } + PubSub request = createPubsubPacket(Type.get, new ItemsExtension(ItemsExtension.ItemsElementType.items, getId(), itemList)); return getItems(request); - } + } - /** - * Get items persisted on the node, limited to the specified number. - * - * @param maxItems Maximum number of items to return - * - * @return List of {@link Item} - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getItems(int maxItems) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), maxItems)); + /** + * Get items persisted on the node, limited to the specified number. + * + * @param maxItems Maximum number of items to return + * + * @return List of {@link Item} + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getItems(int maxItems) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), maxItems)); return getItems(request); - } + } - /** - * Get items persisted on the node, limited to the specified number - * based on the subscription associated with the provided subscriptionId. - * - * @param maxItems Maximum number of items to return - * @param subscriptionId The subscription which the retrieval is based - * on. - * - * @return List of {@link Item} - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getItems(int maxItems, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), subscriptionId, maxItems)); + /** + * Get items persisted on the node, limited to the specified number + * based on the subscription associated with the provided subscriptionId. + * + * @param maxItems Maximum number of items to return + * @param subscriptionId The subscription which the retrieval is based + * on. + * + * @return List of {@link Item} + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getItems(int maxItems, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = createPubsubPacket(Type.get, new GetItemsRequest(getId(), subscriptionId, maxItems)); return getItems(request); - } + } /** * Get items persisted on the node. @@ -200,206 +200,206 @@ public class LeafNode extends Node return (List) itemsElem.getItems(); } - /** - * Publishes an event to the node. This is an empty event - * with no item. - * - * This is only acceptable for nodes with {@link ConfigureForm#isPersistItems()}=false - * and {@link ConfigureForm#isDeliverPayloads()}=false. - * - * This is an asynchronous call which returns as soon as the - * stanza(/packet) has been sent. - * - * For synchronous calls use {@link #send() send()}. - * @throws NotConnectedException - * @throws InterruptedException - */ - public void publish() throws NotConnectedException, InterruptedException - { - PubSub packet = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PUBLISH, getId())); + /** + * Publishes an event to the node. This is an empty event + * with no item. + * + * This is only acceptable for nodes with {@link ConfigureForm#isPersistItems()}=false + * and {@link ConfigureForm#isDeliverPayloads()}=false. + * + * This is an asynchronous call which returns as soon as the + * stanza(/packet) has been sent. + * + * For synchronous calls use {@link #send() send()}. + * @throws NotConnectedException + * @throws InterruptedException + */ + public void publish() throws NotConnectedException, InterruptedException + { + PubSub packet = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PUBLISH, getId())); - pubSubManager.getConnection().sendStanza(packet); - } + pubSubManager.getConnection().sendStanza(packet); + } - /** - * Publishes an event to the node. This is a simple item - * with no payload. - * - * If the id is null, an empty item (one without an id) will be sent. - * Please note that this is not the same as {@link #send()}, which - * publishes an event with NO item. - * - * This is an asynchronous call which returns as soon as the - * stanza(/packet) has been sent. - * - * For synchronous calls use {@link #send(Item) send(Item))}. - * - * @param item - The item being sent - * @throws NotConnectedException - * @throws InterruptedException - */ - @SuppressWarnings("unchecked") - public void publish(T item) throws NotConnectedException, InterruptedException - { - Collection items = new ArrayList(1); - items.add((T)(item == null ? new Item() : item)); - publish(items); - } + /** + * Publishes an event to the node. This is a simple item + * with no payload. + * + * If the id is null, an empty item (one without an id) will be sent. + * Please note that this is not the same as {@link #send()}, which + * publishes an event with NO item. + * + * This is an asynchronous call which returns as soon as the + * stanza(/packet) has been sent. + * + * For synchronous calls use {@link #send(Item) send(Item))}. + * + * @param item - The item being sent + * @throws NotConnectedException + * @throws InterruptedException + */ + @SuppressWarnings("unchecked") + public void publish(T item) throws NotConnectedException, InterruptedException + { + Collection items = new ArrayList(1); + items.add((T)(item == null ? new Item() : item)); + publish(items); + } - /** - * Publishes multiple events to the node. Same rules apply as in {@link #publish(Item)}. - * - * In addition, if {@link ConfigureForm#isPersistItems()}=false, only the last item in the input - * list will get stored on the node, assuming it stores the last sent item. - * - * This is an asynchronous call which returns as soon as the - * stanza(/packet) has been sent. - * - * For synchronous calls use {@link #send(Collection) send(Collection))}. - * - * @param items - The collection of items being sent - * @throws NotConnectedException - * @throws InterruptedException - */ - public void publish(Collection items) throws NotConnectedException, InterruptedException - { - PubSub packet = createPubsubPacket(Type.set, new PublishItem(getId(), items)); + /** + * Publishes multiple events to the node. Same rules apply as in {@link #publish(Item)}. + * + * In addition, if {@link ConfigureForm#isPersistItems()}=false, only the last item in the input + * list will get stored on the node, assuming it stores the last sent item. + * + * This is an asynchronous call which returns as soon as the + * stanza(/packet) has been sent. + * + * For synchronous calls use {@link #send(Collection) send(Collection))}. + * + * @param items - The collection of items being sent + * @throws NotConnectedException + * @throws InterruptedException + */ + public void publish(Collection items) throws NotConnectedException, InterruptedException + { + PubSub packet = createPubsubPacket(Type.set, new PublishItem(getId(), items)); - pubSubManager.getConnection().sendStanza(packet); - } + pubSubManager.getConnection().sendStanza(packet); + } - /** - * Publishes an event to the node. This is an empty event - * with no item. - * - * This is only acceptable for nodes with {@link ConfigureForm#isPersistItems()}=false - * and {@link ConfigureForm#isDeliverPayloads()}=false. - * - * This is a synchronous call which will throw an exception - * on failure. - * - * For asynchronous calls, use {@link #publish() publish()}. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public void send() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub packet = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PUBLISH, getId())); + /** + * Publishes an event to the node. This is an empty event + * with no item. + * + * This is only acceptable for nodes with {@link ConfigureForm#isPersistItems()}=false + * and {@link ConfigureForm#isDeliverPayloads()}=false. + * + * This is a synchronous call which will throw an exception + * on failure. + * + * For asynchronous calls, use {@link #publish() publish()}. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public void send() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub packet = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PUBLISH, getId())); - pubSubManager.getConnection().createStanzaCollectorAndSend(packet).nextResultOrThrow(); - } + pubSubManager.getConnection().createStanzaCollectorAndSend(packet).nextResultOrThrow(); + } - /** - * Publishes an event to the node. This can be either a simple item - * with no payload, or one with it. This is determined by the Node - * configuration. - * - * If the node has deliver_payload=false, the Item must not - * have a payload. - * - * If the id is null, an empty item (one without an id) will be sent. - * Please note that this is not the same as {@link #send()}, which - * publishes an event with NO item. - * - * This is a synchronous call which will throw an exception - * on failure. - * - * For asynchronous calls, use {@link #publish(Item) publish(Item)}. - * - * @param item - The item being sent - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - @SuppressWarnings("unchecked") - public void send(T item) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - Collection items = new ArrayList(1); - items.add((item == null ? (T)new Item() : item)); - send(items); - } + /** + * Publishes an event to the node. This can be either a simple item + * with no payload, or one with it. This is determined by the Node + * configuration. + * + * If the node has deliver_payload=false, the Item must not + * have a payload. + * + * If the id is null, an empty item (one without an id) will be sent. + * Please note that this is not the same as {@link #send()}, which + * publishes an event with NO item. + * + * This is a synchronous call which will throw an exception + * on failure. + * + * For asynchronous calls, use {@link #publish(Item) publish(Item)}. + * + * @param item - The item being sent + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + @SuppressWarnings("unchecked") + public void send(T item) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + Collection items = new ArrayList(1); + items.add((item == null ? (T)new Item() : item)); + send(items); + } - /** - * Publishes multiple events to the node. Same rules apply as in {@link #send(Item)}. - * - * In addition, if {@link ConfigureForm#isPersistItems()}=false, only the last item in the input - * list will get stored on the node, assuming it stores the last sent item. - * - * This is a synchronous call which will throw an exception - * on failure. - * - * For asynchronous calls, use {@link #publish(Collection) publish(Collection))}. - * - * @param items - The collection of {@link Item} objects being sent - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public void send(Collection items) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub packet = createPubsubPacket(Type.set, new PublishItem(getId(), items)); + /** + * Publishes multiple events to the node. Same rules apply as in {@link #send(Item)}. + * + * In addition, if {@link ConfigureForm#isPersistItems()}=false, only the last item in the input + * list will get stored on the node, assuming it stores the last sent item. + * + * This is a synchronous call which will throw an exception + * on failure. + * + * For asynchronous calls, use {@link #publish(Collection) publish(Collection))}. + * + * @param items - The collection of {@link Item} objects being sent + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public void send(Collection items) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub packet = createPubsubPacket(Type.set, new PublishItem(getId(), items)); - pubSubManager.getConnection().createStanzaCollectorAndSend(packet).nextResultOrThrow(); - } + pubSubManager.getConnection().createStanzaCollectorAndSend(packet).nextResultOrThrow(); + } - /** - * Purges the node of all items. - * - *

Note: Some implementations may keep the last item - * sent. - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public void deleteAllItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub request = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PURGE_OWNER, getId()), PubSubElementType.PURGE_OWNER.getNamespace()); + /** + * Purges the node of all items. + * + *

Note: Some implementations may keep the last item + * sent. + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public void deleteAllItems() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = createPubsubPacket(Type.set, new NodeExtension(PubSubElementType.PURGE_OWNER, getId()), PubSubElementType.PURGE_OWNER.getNamespace()); - pubSubManager.getConnection().createStanzaCollectorAndSend(request).nextResultOrThrow(); - } + pubSubManager.getConnection().createStanzaCollectorAndSend(request).nextResultOrThrow(); + } - /** - * Delete the item with the specified id from the node. - * - * @param itemId The id of the item - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void deleteItem(String itemId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - Collection items = new ArrayList(1); - items.add(itemId); - deleteItem(items); - } + /** + * Delete the item with the specified id from the node. + * + * @param itemId The id of the item + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void deleteItem(String itemId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + Collection items = new ArrayList(1); + items.add(itemId); + deleteItem(items); + } - /** - * Delete the items with the specified id's from the node. - * - * @param itemIds The list of id's of items to delete - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public void deleteItem(Collection itemIds) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - List items = new ArrayList(itemIds.size()); + /** + * Delete the items with the specified id's from the node. + * + * @param itemIds The list of id's of items to delete + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public void deleteItem(Collection itemIds) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + List items = new ArrayList(itemIds.size()); - for (String id : itemIds) - { - items.add(new Item(id)); - } - PubSub request = createPubsubPacket(Type.set, new ItemsExtension(ItemsExtension.ItemsElementType.retract, getId(), items)); - pubSubManager.getConnection().createStanzaCollectorAndSend(request).nextResultOrThrow(); - } + for (String id : itemIds) + { + items.add(new Item(id)); + } + PubSub request = createPubsubPacket(Type.set, new ItemsExtension(ItemsExtension.ItemsElementType.retract, getId(), items)); + pubSubManager.getConnection().createStanzaCollectorAndSend(request).nextResultOrThrow(); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java index 22cc12b7a..c62180dd4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java @@ -48,97 +48,97 @@ abstract public class Node protected final PubSubManager pubSubManager; protected final String id; - protected ConcurrentHashMap, StanzaListener> itemEventToListenerMap = new ConcurrentHashMap, StanzaListener>(); - protected ConcurrentHashMap itemDeleteToListenerMap = new ConcurrentHashMap(); - protected ConcurrentHashMap configEventToListenerMap = new ConcurrentHashMap(); + protected ConcurrentHashMap, StanzaListener> itemEventToListenerMap = new ConcurrentHashMap, StanzaListener>(); + protected ConcurrentHashMap itemDeleteToListenerMap = new ConcurrentHashMap(); + protected ConcurrentHashMap configEventToListenerMap = new ConcurrentHashMap(); - /** - * Construct a node associated to the supplied connection with the specified - * node id. - * - * @param connection The connection the node is associated with - * @param nodeName The node id - */ - Node(PubSubManager pubSubManager, String nodeId) - { - this.pubSubManager = pubSubManager; - id = nodeId; - } + /** + * Construct a node associated to the supplied connection with the specified + * node id. + * + * @param connection The connection the node is associated with + * @param nodeName The node id + */ + Node(PubSubManager pubSubManager, String nodeId) + { + this.pubSubManager = pubSubManager; + id = nodeId; + } - /** - * Get the NodeId. - * - * @return the node id - */ - public String getId() - { - return id; - } - /** - * Returns a configuration form, from which you can create an answer form to be submitted - * via the {@link #sendConfigurationForm(Form)}. - * - * @return the configuration form - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public ConfigureForm getNodeConfiguration() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { + /** + * Get the NodeId. + * + * @return the node id + */ + public String getId() + { + return id; + } + /** + * Returns a configuration form, from which you can create an answer form to be submitted + * via the {@link #sendConfigurationForm(Form)}. + * + * @return the configuration form + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public ConfigureForm getNodeConfiguration() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension( PubSubElementType.CONFIGURE_OWNER, getId()), PubSubNamespace.OWNER); - Stanza reply = sendPubsubPacket(pubSub); - return NodeUtils.getFormFromPacket(reply, PubSubElementType.CONFIGURE_OWNER); - } + Stanza reply = sendPubsubPacket(pubSub); + return NodeUtils.getFormFromPacket(reply, PubSubElementType.CONFIGURE_OWNER); + } - /** - * Update the configuration with the contents of the new {@link Form}. - * - * @param submitForm - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void sendConfigurationForm(Form submitForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { + /** + * Update the configuration with the contents of the new {@link Form}. + * + * @param submitForm + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void sendConfigurationForm(Form submitForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { PubSub packet = createPubsubPacket(Type.set, new FormNode(FormNodeType.CONFIGURE_OWNER, getId(), submitForm), PubSubNamespace.OWNER); pubSubManager.getConnection().createStanzaCollectorAndSend(packet).nextResultOrThrow(); - } + } - /** - * Discover node information in standard {@link DiscoverInfo} format. - * - * @return The discovery information about the node. - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public DiscoverInfo discoverInfo() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - DiscoverInfo info = new DiscoverInfo(); - info.setTo(pubSubManager.getServiceJid()); - info.setNode(getId()); - return pubSubManager.getConnection().createStanzaCollectorAndSend(info).nextResultOrThrow(); - } + /** + * Discover node information in standard {@link DiscoverInfo} format. + * + * @return The discovery information about the node. + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public DiscoverInfo discoverInfo() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + DiscoverInfo info = new DiscoverInfo(); + info.setTo(pubSubManager.getServiceJid()); + info.setNode(getId()); + return pubSubManager.getConnection().createStanzaCollectorAndSend(info).nextResultOrThrow(); + } - /** - * Get the subscriptions currently associated with this node. - * - * @return List of {@link Subscription} - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public List getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { + /** + * Get the subscriptions currently associated with this node. + * + * @return List of {@link Subscription} + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public List getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { return getSubscriptions(null, null); - } + } /** * Get the subscriptions currently associated with this node. @@ -223,15 +223,15 @@ abstract public class Node return subElem.getSubscriptions(); } - /** - * Get the affiliations of this node. - * - * @return List of {@link Affiliation} - * @throws NoResponseException - * @throws XMPPErrorException - * @throws NotConnectedException - * @throws InterruptedException - */ + /** + * Get the affiliations of this node. + * + * @return List of {@link Affiliation} + * @throws NoResponseException + * @throws XMPPErrorException + * @throws NotConnectedException + * @throws InterruptedException + */ public List getAffiliations() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return getAffiliations(null, null); @@ -346,398 +346,396 @@ abstract public class Node return sendPubsubPacket(pubSub); } - /** - * The user subscribes to the node using the supplied jid. The - * bare jid portion of this one must match the jid for the connection. - * - * Please note that the {@link Subscription.State} should be checked - * on return since more actions may be required by the caller. - * {@link Subscription.State#pending} - The owner must approve the subscription - * request before messages will be received. - * {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true, - * the caller must configure the subscription before messages will be received. If it is false - * the caller can configure it but is not required to do so. - * @param jid The jid to subscribe as. - * @return The subscription - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public Subscription subscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { -// CHECKSTYLE:OFF - PubSub pubSub = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId())); -// CHECKSTYLE:ON - PubSub reply = sendPubsubPacket(pubSub); - return reply.getExtension(PubSubElementType.SUBSCRIPTION); - } + /** + * The user subscribes to the node using the supplied jid. The + * bare jid portion of this one must match the jid for the connection. + * + * Please note that the {@link Subscription.State} should be checked + * on return since more actions may be required by the caller. + * {@link Subscription.State#pending} - The owner must approve the subscription + * request before messages will be received. + * {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true, + * the caller must configure the subscription before messages will be received. If it is false + * the caller can configure it but is not required to do so. + * @param jid The jid to subscribe as. + * @return The subscription + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public Subscription subscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub pubSub = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId())); + PubSub reply = sendPubsubPacket(pubSub); + return reply.getExtension(PubSubElementType.SUBSCRIPTION); + } - /** - * The user subscribes to the node using the supplied jid and subscription - * options. The bare jid portion of this one must match the jid for the - * connection. - * - * Please note that the {@link Subscription.State} should be checked - * on return since more actions may be required by the caller. - * {@link Subscription.State#pending} - The owner must approve the subscription - * request before messages will be received. - * {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true, - * the caller must configure the subscription before messages will be received. If it is false - * the caller can configure it but is not required to do so. - * @param jid The jid to subscribe as. - * @return The subscription - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public Subscription subscribe(String jid, SubscribeForm subForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { -// CHECKSTYLE:OFF - PubSub request = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId())); -// CHECKSTYLE:ON - request.addExtension(new FormNode(FormNodeType.OPTIONS, subForm)); - PubSub reply = sendPubsubPacket(request); - return reply.getExtension(PubSubElementType.SUBSCRIPTION); - } + /** + * The user subscribes to the node using the supplied jid and subscription + * options. The bare jid portion of this one must match the jid for the + * connection. + * + * Please note that the {@link Subscription.State} should be checked + * on return since more actions may be required by the caller. + * {@link Subscription.State#pending} - The owner must approve the subscription + * request before messages will be received. + * {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true, + * the caller must configure the subscription before messages will be received. If it is false + * the caller can configure it but is not required to do so. + * @param jid The jid to subscribe as. + * @return The subscription + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public Subscription subscribe(String jid, SubscribeForm subForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId())); + request.addExtension(new FormNode(FormNodeType.OPTIONS, subForm)); + PubSub reply = sendPubsubPacket(request); + return reply.getExtension(PubSubElementType.SUBSCRIPTION); + } - /** - * Remove the subscription related to the specified JID. This will only - * work if there is only 1 subscription. If there are multiple subscriptions, - * use {@link #unsubscribe(String, String)}. - * - * @param jid The JID used to subscribe to the node - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public void unsubscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - unsubscribe(jid, null); - } + /** + * Remove the subscription related to the specified JID. This will only + * work if there is only 1 subscription. If there are multiple subscriptions, + * use {@link #unsubscribe(String, String)}. + * + * @param jid The JID used to subscribe to the node + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public void unsubscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + unsubscribe(jid, null); + } - /** - * Remove the specific subscription related to the specified JID. - * - * @param jid The JID used to subscribe to the node - * @param subscriptionId The id of the subscription being removed - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void unsubscribe(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - sendPubsubPacket(createPubsubPacket(Type.set, new UnsubscribeExtension(jid, getId(), subscriptionId))); - } + /** + * Remove the specific subscription related to the specified JID. + * + * @param jid The JID used to subscribe to the node + * @param subscriptionId The id of the subscription being removed + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void unsubscribe(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + sendPubsubPacket(createPubsubPacket(Type.set, new UnsubscribeExtension(jid, getId(), subscriptionId))); + } - /** - * Returns a SubscribeForm for subscriptions, from which you can create an answer form to be submitted - * via the {@link #sendConfigurationForm(Form)}. - * - * @return A subscription options form - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public SubscribeForm getSubscriptionOptions(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - return getSubscriptionOptions(jid, null); - } + /** + * Returns a SubscribeForm for subscriptions, from which you can create an answer form to be submitted + * via the {@link #sendConfigurationForm(Form)}. + * + * @return A subscription options form + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public SubscribeForm getSubscriptionOptions(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + return getSubscriptionOptions(jid, null); + } - /** - * Get the options for configuring the specified subscription. - * - * @param jid JID the subscription is registered under - * @param subscriptionId The subscription id - * - * @return The subscription option form - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public SubscribeForm getSubscriptionOptions(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub packet = sendPubsubPacket(createPubsubPacket(Type.get, new OptionsExtension(jid, getId(), subscriptionId))); - FormNode ext = packet.getExtension(PubSubElementType.OPTIONS); - return new SubscribeForm(ext.getForm()); - } + /** + * Get the options for configuring the specified subscription. + * + * @param jid JID the subscription is registered under + * @param subscriptionId The subscription id + * + * @return The subscription option form + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public SubscribeForm getSubscriptionOptions(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub packet = sendPubsubPacket(createPubsubPacket(Type.get, new OptionsExtension(jid, getId(), subscriptionId))); + FormNode ext = packet.getExtension(PubSubElementType.OPTIONS); + return new SubscribeForm(ext.getForm()); + } - /** - * Register a listener for item publication events. This - * listener will get called whenever an item is published to - * this node. - * - * @param listener The handler for the event - */ - @SuppressWarnings("unchecked") + /** + * Register a listener for item publication events. This + * listener will get called whenever an item is published to + * this node. + * + * @param listener The handler for the event + */ + @SuppressWarnings("unchecked") public void addItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) - { - StanzaListener conListener = new ItemEventTranslator(listener); - itemEventToListenerMap.put(listener, conListener); - pubSubManager.getConnection().addSyncStanzaListener(conListener, new EventContentFilter(EventElementType.items.toString(), "item")); - } + { + StanzaListener conListener = new ItemEventTranslator(listener); + itemEventToListenerMap.put(listener, conListener); + pubSubManager.getConnection().addSyncStanzaListener(conListener, new EventContentFilter(EventElementType.items.toString(), "item")); + } - /** - * Unregister a listener for publication events. - * - * @param listener The handler to unregister - */ - public void removeItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) - { - StanzaListener conListener = itemEventToListenerMap.remove(listener); + /** + * Unregister a listener for publication events. + * + * @param listener The handler to unregister + */ + public void removeItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) + { + StanzaListener conListener = itemEventToListenerMap.remove(listener); - if (conListener != null) - pubSubManager.getConnection().removeSyncStanzaListener(conListener); - } + if (conListener != null) + pubSubManager.getConnection().removeSyncStanzaListener(conListener); + } - /** - * Register a listener for configuration events. This listener - * will get called whenever the node's configuration changes. - * - * @param listener The handler for the event - */ - public void addConfigurationListener(NodeConfigListener listener) - { - StanzaListener conListener = new NodeConfigTranslator(listener); - configEventToListenerMap.put(listener, conListener); - pubSubManager.getConnection().addSyncStanzaListener(conListener, new EventContentFilter(EventElementType.configuration.toString())); - } + /** + * Register a listener for configuration events. This listener + * will get called whenever the node's configuration changes. + * + * @param listener The handler for the event + */ + public void addConfigurationListener(NodeConfigListener listener) + { + StanzaListener conListener = new NodeConfigTranslator(listener); + configEventToListenerMap.put(listener, conListener); + pubSubManager.getConnection().addSyncStanzaListener(conListener, new EventContentFilter(EventElementType.configuration.toString())); + } - /** - * Unregister a listener for configuration events. - * - * @param listener The handler to unregister - */ - public void removeConfigurationListener(NodeConfigListener listener) - { - StanzaListener conListener = configEventToListenerMap .remove(listener); + /** + * Unregister a listener for configuration events. + * + * @param listener The handler to unregister + */ + public void removeConfigurationListener(NodeConfigListener listener) + { + StanzaListener conListener = configEventToListenerMap .remove(listener); - if (conListener != null) - pubSubManager.getConnection().removeSyncStanzaListener(conListener); - } + if (conListener != null) + pubSubManager.getConnection().removeSyncStanzaListener(conListener); + } - /** - * Register an listener for item delete events. This listener - * gets called whenever an item is deleted from the node. - * - * @param listener The handler for the event - */ - public void addItemDeleteListener(ItemDeleteListener listener) - { - StanzaListener delListener = new ItemDeleteTranslator(listener); - itemDeleteToListenerMap.put(listener, delListener); - EventContentFilter deleteItem = new EventContentFilter(EventElementType.items.toString(), "retract"); - EventContentFilter purge = new EventContentFilter(EventElementType.purge.toString()); + /** + * Register an listener for item delete events. This listener + * gets called whenever an item is deleted from the node. + * + * @param listener The handler for the event + */ + public void addItemDeleteListener(ItemDeleteListener listener) + { + StanzaListener delListener = new ItemDeleteTranslator(listener); + itemDeleteToListenerMap.put(listener, delListener); + EventContentFilter deleteItem = new EventContentFilter(EventElementType.items.toString(), "retract"); + EventContentFilter purge = new EventContentFilter(EventElementType.purge.toString()); - pubSubManager.getConnection().addSyncStanzaListener(delListener, new OrFilter(deleteItem, purge)); - } + pubSubManager.getConnection().addSyncStanzaListener(delListener, new OrFilter(deleteItem, purge)); + } - /** - * Unregister a listener for item delete events. - * - * @param listener The handler to unregister - */ - public void removeItemDeleteListener(ItemDeleteListener listener) - { - StanzaListener conListener = itemDeleteToListenerMap .remove(listener); + /** + * Unregister a listener for item delete events. + * + * @param listener The handler to unregister + */ + public void removeItemDeleteListener(ItemDeleteListener listener) + { + StanzaListener conListener = itemDeleteToListenerMap .remove(listener); - if (conListener != null) - pubSubManager.getConnection().removeSyncStanzaListener(conListener); - } + if (conListener != null) + pubSubManager.getConnection().removeSyncStanzaListener(conListener); + } - @Override - public String toString() - { - return super.toString() + " " + getClass().getName() + " id: " + id; - } + @Override + public String toString() + { + return super.toString() + " " + getClass().getName() + " id: " + id; + } - protected PubSub createPubsubPacket(Type type, ExtensionElement ext) - { - return createPubsubPacket(type, ext, null); - } + protected PubSub createPubsubPacket(Type type, ExtensionElement ext) + { + return createPubsubPacket(type, ext, null); + } - protected PubSub createPubsubPacket(Type type, ExtensionElement ext, PubSubNamespace ns) - { + protected PubSub createPubsubPacket(Type type, ExtensionElement ext, PubSubNamespace ns) + { return PubSub.createPubsubPacket(pubSubManager.getServiceJid(), type, ext, ns); - } + } - protected PubSub sendPubsubPacket(PubSub packet) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - return pubSubManager.sendPubsubPacket(packet); - } + protected PubSub sendPubsubPacket(PubSub packet) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + return pubSubManager.sendPubsubPacket(packet); + } - private static List getSubscriptionIds(Stanza packet) - { - HeadersExtension headers = (HeadersExtension)packet.getExtension("headers", "http://jabber.org/protocol/shim"); - List values = null; + private static List getSubscriptionIds(Stanza packet) + { + HeadersExtension headers = (HeadersExtension)packet.getExtension("headers", "http://jabber.org/protocol/shim"); + List values = null; - if (headers != null) - { - values = new ArrayList(headers.getHeaders().size()); + if (headers != null) + { + values = new ArrayList(headers.getHeaders().size()); - for (Header header : headers.getHeaders()) - { - values.add(header.getValue()); - } - } - return values; - } + for (Header header : headers.getHeaders()) + { + values.add(header.getValue()); + } + } + return values; + } - /** - * This class translates low level item publication events into api level objects for - * user consumption. - * - * @author Robin Collier - */ - public class ItemEventTranslator implements StanzaListener - { - @SuppressWarnings("rawtypes") + /** + * This class translates low level item publication events into api level objects for + * user consumption. + * + * @author Robin Collier + */ + public class ItemEventTranslator implements StanzaListener + { + @SuppressWarnings("rawtypes") private ItemEventListener listener; - public ItemEventTranslator(@SuppressWarnings("rawtypes") ItemEventListener eventListener) - { - listener = eventListener; - } + public ItemEventTranslator(@SuppressWarnings("rawtypes") ItemEventListener eventListener) + { + listener = eventListener; + } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) public void processStanza(Stanza packet) - { + { // CHECKSTYLE:OFF - EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); + EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); // CHECKSTYLE:ON - ItemsExtension itemsElem = (ItemsExtension)event.getEvent(); + ItemsExtension itemsElem = (ItemsExtension)event.getEvent(); ItemPublishEvent eventItems = new ItemPublishEvent(itemsElem.getNode(), itemsElem.getItems(), getSubscriptionIds(packet), DelayInformationManager.getDelayTimestamp(packet)); - listener.handlePublishedItems(eventItems); - } - } + listener.handlePublishedItems(eventItems); + } + } - /** - * This class translates low level item deletion events into api level objects for - * user consumption. - * - * @author Robin Collier - */ - public class ItemDeleteTranslator implements StanzaListener - { - private ItemDeleteListener listener; + /** + * This class translates low level item deletion events into api level objects for + * user consumption. + * + * @author Robin Collier + */ + public class ItemDeleteTranslator implements StanzaListener + { + private ItemDeleteListener listener; - public ItemDeleteTranslator(ItemDeleteListener eventListener) - { - listener = eventListener; - } + public ItemDeleteTranslator(ItemDeleteListener eventListener) + { + listener = eventListener; + } - public void processStanza(Stanza packet) - { + @Override + public void processStanza(Stanza packet) + { // CHECKSTYLE:OFF - EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); + EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); - List extList = event.getExtensions(); + List extList = event.getExtensions(); - if (extList.get(0).getElementName().equals(PubSubElementType.PURGE_EVENT.getElementName())) - { - listener.handlePurge(); - } - else - { - ItemsExtension itemsElem = (ItemsExtension)event.getEvent(); - @SuppressWarnings("unchecked") + if (extList.get(0).getElementName().equals(PubSubElementType.PURGE_EVENT.getElementName())) + { + listener.handlePurge(); + } + else + { + ItemsExtension itemsElem = (ItemsExtension)event.getEvent(); + @SuppressWarnings("unchecked") Collection pubItems = (Collection) itemsElem.getItems(); - List items = new ArrayList(pubItems.size()); + List items = new ArrayList(pubItems.size()); - for (RetractItem item : pubItems) - { - items.add(item.getId()); - } + for (RetractItem item : pubItems) + { + items.add(item.getId()); + } - ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet)); - listener.handleDeletedItems(eventItems); - } + ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet)); + listener.handleDeletedItems(eventItems); + } // CHECKSTYLE:ON - } - } + } + } - /** - * This class translates low level node configuration events into api level objects for - * user consumption. - * - * @author Robin Collier - */ - public class NodeConfigTranslator implements StanzaListener - { - private NodeConfigListener listener; + /** + * This class translates low level node configuration events into api level objects for + * user consumption. + * + * @author Robin Collier + */ + public static class NodeConfigTranslator implements StanzaListener + { + private NodeConfigListener listener; - public NodeConfigTranslator(NodeConfigListener eventListener) - { - listener = eventListener; - } + public NodeConfigTranslator(NodeConfigListener eventListener) + { + listener = eventListener; + } - public void processStanza(Stanza packet) - { -// CHECKSTYLE:OFF - EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); - ConfigurationEvent config = (ConfigurationEvent)event.getEvent(); -// CHECKSTYLE:ON + @Override + public void processStanza(Stanza packet) + { + EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); + ConfigurationEvent config = (ConfigurationEvent)event.getEvent(); - listener.handleNodeConfiguration(config); - } - } + listener.handleNodeConfiguration(config); + } + } - /** - * Filter for {@link StanzaListener} to filter out events not specific to the - * event type expected for this node. - * - * @author Robin Collier - */ - class EventContentFilter extends FlexibleStanzaTypeFilter - { + /** + * Filter for {@link StanzaListener} to filter out events not specific to the + * event type expected for this node. + * + * @author Robin Collier + */ + class EventContentFilter extends FlexibleStanzaTypeFilter + { private final String firstElement; private final String secondElement; private final boolean allowEmpty; - EventContentFilter(String elementName) - { + EventContentFilter(String elementName) + { this(elementName, null); - } + } - EventContentFilter(String firstLevelEelement, String secondLevelElement) - { - firstElement = firstLevelEelement; - secondElement = secondLevelElement; + EventContentFilter(String firstLevelEelement, String secondLevelElement) + { + firstElement = firstLevelEelement; + secondElement = secondLevelElement; allowEmpty = firstElement.equals(EventElementType.items.toString()) && "item".equals(secondLevelElement); - } + } + @Override public boolean acceptSpecific(Message message) { EventElement event = EventElement.from(message); - if (event == null) - return false; + if (event == null) + return false; - NodeExtension embedEvent = event.getEvent(); + NodeExtension embedEvent = event.getEvent(); - if (embedEvent == null) - return false; + if (embedEvent == null) + return false; - if (embedEvent.getElementName().equals(firstElement)) - { - if (!embedEvent.getNode().equals(getId())) - return false; + if (embedEvent.getElementName().equals(firstElement)) + { + if (!embedEvent.getNode().equals(getId())) + return false; - if (secondElement == null) - return true; + if (secondElement == null) + return true; - if (embedEvent instanceof EmbeddedPacketExtension) - { - List secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions(); + if (embedEvent instanceof EmbeddedPacketExtension) + { + List secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions(); // XEP-0060 allows no elements on second level for notifications. See schema or // for example § 4.3: @@ -746,11 +744,11 @@ abstract public class Node return true; } - if (secondLevelList.size() > 0 && secondLevelList.get(0).getElementName().equals(secondElement)) - return true; - } - } - return false; - } - } + if (secondLevelList.size() > 0 && secondLevelList.get(0).getElementName().equals(secondElement)) + return true; + } + } + return false; + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeEvent.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeEvent.java index 1d92e50be..c75cc41dd 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeEvent.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeEvent.java @@ -18,15 +18,15 @@ package org.jivesoftware.smackx.pubsub; abstract public class NodeEvent { - private String nodeId; + private String nodeId; - protected NodeEvent(String id) - { - nodeId = id; - } + protected NodeEvent(String id) + { + nodeId = id; + } - public String getNodeId() - { - return nodeId; - } + public String getNodeId() + { + return nodeId; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeExtension.java index 58d05da35..41393b7f6 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeExtension.java @@ -28,61 +28,64 @@ import org.jivesoftware.smack.packet.ExtensionElement; */ public class NodeExtension implements ExtensionElement { - private final PubSubElementType element; - private final String node; + private final PubSubElementType element; + private final String node; - /** - * Constructs a NodeExtension with an element name specified - * by {@link PubSubElementType} and the specified node id. - * - * @param elem Defines the element name and namespace - * @param nodeId Specifies the id of the node - */ - public NodeExtension(PubSubElementType elem, String nodeId) - { - element = elem; - this.node = nodeId; - } + /** + * Constructs a NodeExtension with an element name specified + * by {@link PubSubElementType} and the specified node id. + * + * @param elem Defines the element name and namespace + * @param nodeId Specifies the id of the node + */ + public NodeExtension(PubSubElementType elem, String nodeId) + { + element = elem; + this.node = nodeId; + } - /** - * Constructs a NodeExtension with an element name specified - * by {@link PubSubElementType}. - * - * @param elem Defines the element name and namespace - */ - public NodeExtension(PubSubElementType elem) - { - this(elem, null); - } + /** + * Constructs a NodeExtension with an element name specified + * by {@link PubSubElementType}. + * + * @param elem Defines the element name and namespace + */ + public NodeExtension(PubSubElementType elem) + { + this(elem, null); + } - /** - * Gets the node id. - * - * @return The node id - */ - public String getNode() - { - return node; - } + /** + * Gets the node id. + * + * @return The node id + */ + public String getNode() + { + return node; + } - public String getElementName() - { - return element.getElementName(); - } + @Override + public String getElementName() + { + return element.getElementName(); + } - public String getNamespace() - { - return element.getNamespace().getXmlns(); - } + @Override + public String getNamespace() + { + return element.getNamespace().getXmlns(); + } - public CharSequence toXML() - { - return '<' + getElementName() + (node == null ? "" : " node='" + node + '\'') + "/>"; - } + @Override + public CharSequence toXML() + { + return '<' + getElementName() + (node == null ? "" : " node='" + node + '\'') + "/>"; + } - @Override - public String toString() - { - return getClass().getName() + " - content [" + toXML() + "]"; - } + @Override + public String toString() + { + return getClass().getName() + " - content [" + toXML() + "]"; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeType.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeType.java index bd29f1901..08146d5c4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeType.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/NodeType.java @@ -23,6 +23,6 @@ package org.jivesoftware.smackx.pubsub; */ public enum NodeType { - leaf, - collection; + leaf, + collection; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/OptionsExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/OptionsExtension.java index 4da9969c1..2c1969876 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/OptionsExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/OptionsExtension.java @@ -25,35 +25,35 @@ import org.jivesoftware.smack.util.XmlStringBuilder; */ public class OptionsExtension extends NodeExtension { - protected String jid; - protected String id; + protected String jid; + protected String id; - public OptionsExtension(String subscriptionJid) - { - this(subscriptionJid, null, null); - } + public OptionsExtension(String subscriptionJid) + { + this(subscriptionJid, null, null); + } - public OptionsExtension(String subscriptionJid, String nodeId) - { - this(subscriptionJid, nodeId, null); - } + public OptionsExtension(String subscriptionJid, String nodeId) + { + this(subscriptionJid, nodeId, null); + } - public OptionsExtension(String jid, String nodeId, String subscriptionId) - { - super(PubSubElementType.OPTIONS, nodeId); - this.jid = jid; - id = subscriptionId; - } + public OptionsExtension(String jid, String nodeId, String subscriptionId) + { + super(PubSubElementType.OPTIONS, nodeId); + this.jid = jid; + id = subscriptionId; + } - public String getJid() - { - return jid; - } + public String getJid() + { + return jid; + } - public String getId() - { - return id; - } + public String getId() + { + return id; + } @Override public XmlStringBuilder toXML() { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PayloadItem.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PayloadItem.java index 40e8e4131..c20c49de3 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PayloadItem.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PayloadItem.java @@ -49,98 +49,98 @@ import org.jivesoftware.smackx.pubsub.provider.ItemProvider; */ public class PayloadItem extends Item { - private E payload; + private E payload; - /** - * Create an Item with no id and a payload The id will be set by the server. - * - * @param payloadExt A {@link ExtensionElement} which represents the payload data. - */ - public PayloadItem(E payloadExt) - { - super(); + /** + * Create an Item with no id and a payload The id will be set by the server. + * + * @param payloadExt A {@link ExtensionElement} which represents the payload data. + */ + public PayloadItem(E payloadExt) + { + super(); - if (payloadExt == null) - throw new IllegalArgumentException("payload cannot be 'null'"); - payload = payloadExt; - } + if (payloadExt == null) + throw new IllegalArgumentException("payload cannot be 'null'"); + payload = payloadExt; + } - /** - * Create an Item with an id and payload. - * - * @param itemId The id of this item. It can be null if we want the server to set the id. - * @param payloadExt A {@link ExtensionElement} which represents the payload data. - */ - public PayloadItem(String itemId, E payloadExt) - { - super(itemId); + /** + * Create an Item with an id and payload. + * + * @param itemId The id of this item. It can be null if we want the server to set the id. + * @param payloadExt A {@link ExtensionElement} which represents the payload data. + */ + public PayloadItem(String itemId, E payloadExt) + { + super(itemId); - if (payloadExt == null) - throw new IllegalArgumentException("payload cannot be 'null'"); - payload = payloadExt; - } + if (payloadExt == null) + throw new IllegalArgumentException("payload cannot be 'null'"); + payload = payloadExt; + } - /** - * Create an Item with an id, node id and payload. - * - *

- * Note: This is not valid for publishing an item to a node, only receiving from - * one as part of {@link Message}. If used to create an Item to publish - * (via {@link LeafNode#publish(Item)}, the server may return an - * error for an invalid packet. - *

- * - * @param itemId The id of this item. - * @param nodeId The id of the node the item was published to. - * @param payloadExt A {@link ExtensionElement} which represents the payload data. - */ - public PayloadItem(String itemId, String nodeId, E payloadExt) - { - super(itemId, nodeId); + /** + * Create an Item with an id, node id and payload. + * + *

+ * Note: This is not valid for publishing an item to a node, only receiving from + * one as part of {@link Message}. If used to create an Item to publish + * (via {@link LeafNode#publish(Item)}, the server may return an + * error for an invalid packet. + *

+ * + * @param itemId The id of this item. + * @param nodeId The id of the node the item was published to. + * @param payloadExt A {@link ExtensionElement} which represents the payload data. + */ + public PayloadItem(String itemId, String nodeId, E payloadExt) + { + super(itemId, nodeId); - if (payloadExt == null) - throw new IllegalArgumentException("payload cannot be 'null'"); - payload = payloadExt; - } + if (payloadExt == null) + throw new IllegalArgumentException("payload cannot be 'null'"); + payload = payloadExt; + } - /** - * Get the payload associated with this Item. Customising the payload - * parsing from the server can be accomplished as described in {@link ItemProvider}. - * - * @return The payload as a {@link ExtensionElement}. - */ - public E getPayload() - { - return payload; - } + /** + * Get the payload associated with this Item. Customising the payload + * parsing from the server can be accomplished as described in {@link ItemProvider}. + * + * @return The payload as a {@link ExtensionElement}. + */ + public E getPayload() + { + return payload; + } - @Override - public String toXML() - { - StringBuilder builder = new StringBuilder("'); - builder.append(payload.toXML()); - builder.append("
"); + builder.append('>'); + builder.append(payload.toXML()); + builder.append("
"); - return builder.toString(); - } + return builder.toString(); + } - @Override - public String toString() - { - return getClass().getName() + " | Content [" + toXML() + "]"; - } + @Override + public String toString() + { + return getClass().getName() + " | Content [" + toXML() + "]"; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PresenceState.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PresenceState.java index 0f4a83d05..f6ca9f928 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PresenceState.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PresenceState.java @@ -24,5 +24,5 @@ package org.jivesoftware.smackx.pubsub; */ public enum PresenceState { - chat, online, away, xa, dnd + chat, online, away, xa, dnd } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubElementType.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubElementType.java index 0f6e32ccc..ef0ac70f5 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubElementType.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubElementType.java @@ -28,58 +28,58 @@ import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace; */ public enum PubSubElementType { - CREATE("create", PubSubNamespace.BASIC), - DELETE("delete", PubSubNamespace.OWNER), - DELETE_EVENT("delete", PubSubNamespace.EVENT), - CONFIGURE("configure", PubSubNamespace.BASIC), - CONFIGURE_OWNER("configure", PubSubNamespace.OWNER), - CONFIGURATION("configuration", PubSubNamespace.EVENT), - OPTIONS("options", PubSubNamespace.BASIC), - DEFAULT("default", PubSubNamespace.OWNER), - ITEMS("items", PubSubNamespace.BASIC), - ITEMS_EVENT("items", PubSubNamespace.EVENT), - ITEM("item", PubSubNamespace.BASIC), - ITEM_EVENT("item", PubSubNamespace.EVENT), - PUBLISH("publish", PubSubNamespace.BASIC), - PUBLISH_OPTIONS("publish-options", PubSubNamespace.BASIC), - PURGE_OWNER("purge", PubSubNamespace.OWNER), - PURGE_EVENT("purge", PubSubNamespace.EVENT), - RETRACT("retract", PubSubNamespace.BASIC), - AFFILIATIONS("affiliations", PubSubNamespace.BASIC), - SUBSCRIBE("subscribe", PubSubNamespace.BASIC), - SUBSCRIPTION("subscription", PubSubNamespace.BASIC), - SUBSCRIPTIONS("subscriptions", PubSubNamespace.BASIC), - UNSUBSCRIBE("unsubscribe", PubSubNamespace.BASIC); + CREATE("create", PubSubNamespace.BASIC), + DELETE("delete", PubSubNamespace.OWNER), + DELETE_EVENT("delete", PubSubNamespace.EVENT), + CONFIGURE("configure", PubSubNamespace.BASIC), + CONFIGURE_OWNER("configure", PubSubNamespace.OWNER), + CONFIGURATION("configuration", PubSubNamespace.EVENT), + OPTIONS("options", PubSubNamespace.BASIC), + DEFAULT("default", PubSubNamespace.OWNER), + ITEMS("items", PubSubNamespace.BASIC), + ITEMS_EVENT("items", PubSubNamespace.EVENT), + ITEM("item", PubSubNamespace.BASIC), + ITEM_EVENT("item", PubSubNamespace.EVENT), + PUBLISH("publish", PubSubNamespace.BASIC), + PUBLISH_OPTIONS("publish-options", PubSubNamespace.BASIC), + PURGE_OWNER("purge", PubSubNamespace.OWNER), + PURGE_EVENT("purge", PubSubNamespace.EVENT), + RETRACT("retract", PubSubNamespace.BASIC), + AFFILIATIONS("affiliations", PubSubNamespace.BASIC), + SUBSCRIBE("subscribe", PubSubNamespace.BASIC), + SUBSCRIPTION("subscription", PubSubNamespace.BASIC), + SUBSCRIPTIONS("subscriptions", PubSubNamespace.BASIC), + UNSUBSCRIBE("unsubscribe", PubSubNamespace.BASIC); - private String eName; - private PubSubNamespace nSpace; + private final String eName; + private final PubSubNamespace nSpace; - private PubSubElementType(String elemName, PubSubNamespace ns) - { - eName = elemName; - nSpace = ns; - } + private PubSubElementType(String elemName, PubSubNamespace ns) + { + eName = elemName; + nSpace = ns; + } - public PubSubNamespace getNamespace() - { - return nSpace; - } + public PubSubNamespace getNamespace() + { + return nSpace; + } - public String getElementName() - { - return eName; - } + public String getElementName() + { + return eName; + } - public static PubSubElementType valueOfFromElemName(String elemName, String namespace) - { - int index = namespace.lastIndexOf('#'); - String fragment = (index == -1 ? null : namespace.substring(index+1)); + public static PubSubElementType valueOfFromElemName(String elemName, String namespace) + { + int index = namespace.lastIndexOf('#'); + String fragment = (index == -1 ? null : namespace.substring(index+1)); - if (fragment != null) - { - return valueOf((elemName + '_' + fragment).toUpperCase(Locale.US)); - } - return valueOf(elemName.toUpperCase(Locale.US).replace('-', '_')); - } + if (fragment != null) + { + return valueOf((elemName + '_' + fragment).toUpperCase(Locale.US)); + } + return valueOf(elemName.toUpperCase(Locale.US).replace('-', '_')); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java index 452c8af3a..37a08ba45 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java @@ -127,114 +127,114 @@ public final class PubSubManager extends Manager { return pubSubManager; } - /** - * Create a pubsub manager associated to the specified connection where - * the pubsub requests require a specific to address for packets. - * - * @param connection The XMPP connection - * @param toAddress The pubsub specific to address (required for some servers) - */ - PubSubManager(XMPPConnection connection, BareJid toAddress) - { - super(connection); - pubSubService = toAddress; - } + /** + * Create a pubsub manager associated to the specified connection where + * the pubsub requests require a specific to address for packets. + * + * @param connection The XMPP connection + * @param toAddress The pubsub specific to address (required for some servers) + */ + PubSubManager(XMPPConnection connection, BareJid toAddress) + { + super(connection); + pubSubService = toAddress; + } - /** - * Creates an instant node, if supported. - * - * @return The node that was created - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public LeafNode createNode() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub reply = sendPubsubPacket(Type.set, new NodeExtension(PubSubElementType.CREATE), null); - NodeExtension elem = reply.getExtension("create", PubSubNamespace.BASIC.getXmlns()); + /** + * Creates an instant node, if supported. + * + * @return The node that was created + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public LeafNode createNode() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub reply = sendPubsubPacket(Type.set, new NodeExtension(PubSubElementType.CREATE), null); + NodeExtension elem = reply.getExtension("create", PubSubNamespace.BASIC.getXmlns()); - LeafNode newNode = new LeafNode(this, elem.getNode()); - nodeMap.put(newNode.getId(), newNode); + LeafNode newNode = new LeafNode(this, elem.getNode()); + nodeMap.put(newNode.getId(), newNode); - return newNode; - } + return newNode; + } - /** - * Creates a node with default configuration. - * - * @param nodeId The id of the node, which must be unique within the - * pubsub service - * @return The node that was created - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public LeafNode createNode(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - return (LeafNode) createNode(nodeId, null); - } + /** + * Creates a node with default configuration. + * + * @param nodeId The id of the node, which must be unique within the + * pubsub service + * @return The node that was created + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public LeafNode createNode(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + return (LeafNode) createNode(nodeId, null); + } - /** - * Creates a node with specified configuration. - * - * Note: This is the only way to create a collection node. - * - * @param nodeId The name of the node, which must be unique within the - * pubsub service - * @param config The configuration for the node - * @return The node that was created - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public Node createNode(String nodeId, Form config) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub request = PubSub.createPubsubPacket(pubSubService, Type.set, new NodeExtension(PubSubElementType.CREATE, nodeId), null); - boolean isLeafNode = true; + /** + * Creates a node with specified configuration. + * + * Note: This is the only way to create a collection node. + * + * @param nodeId The name of the node, which must be unique within the + * pubsub service + * @param config The configuration for the node + * @return The node that was created + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public Node createNode(String nodeId, Form config) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub request = PubSub.createPubsubPacket(pubSubService, Type.set, new NodeExtension(PubSubElementType.CREATE, nodeId), null); + boolean isLeafNode = true; - if (config != null) - { - request.addExtension(new FormNode(FormNodeType.CONFIGURE, config)); - FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName()); + if (config != null) + { + request.addExtension(new FormNode(FormNodeType.CONFIGURE, config)); + FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName()); - if (nodeTypeField != null) - isLeafNode = nodeTypeField.getValues().get(0).equals(NodeType.leaf.toString()); - } + if (nodeTypeField != null) + isLeafNode = nodeTypeField.getValues().get(0).equals(NodeType.leaf.toString()); + } - // Errors will cause exceptions in getReply, so it only returns - // on success. - sendPubsubPacket(request); - Node newNode = isLeafNode ? new LeafNode(this, nodeId) : new CollectionNode(this, nodeId); - nodeMap.put(newNode.getId(), newNode); + // Errors will cause exceptions in getReply, so it only returns + // on success. + sendPubsubPacket(request); + Node newNode = isLeafNode ? new LeafNode(this, nodeId) : new CollectionNode(this, nodeId); + nodeMap.put(newNode.getId(), newNode); - return newNode; - } + return newNode; + } - /** - * Retrieves the requested node, if it exists. It will throw an - * exception if it does not. - * - * @param id - The unique id of the node - * @return the node - * @throws XMPPErrorException The node does not exist - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ + /** + * Retrieves the requested node, if it exists. It will throw an + * exception if it does not. + * + * @param id - The unique id of the node + * @return the node + * @throws XMPPErrorException The node does not exist + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ public T getNode(String id) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - Node node = nodeMap.get(id); + { + Node node = nodeMap.get(id); - if (node == null) - { - DiscoverInfo info = new DiscoverInfo(); - info.setTo(pubSubService); - info.setNode(id); + if (node == null) + { + DiscoverInfo info = new DiscoverInfo(); + info.setTo(pubSubService); + info.setNode(id); - DiscoverInfo infoReply = connection().createStanzaCollectorAndSend(info).nextResultOrThrow(); + DiscoverInfo infoReply = connection().createStanzaCollectorAndSend(info).nextResultOrThrow(); if (infoReply.hasIdentity(PubSub.ELEMENT, "leaf")) { node = new LeafNode(this, id); @@ -253,104 +253,104 @@ public final class PubSubManager extends Manager { + id + "', but it did not contain an Identity of type 'leaf' or 'collection' (and category 'pubsub'), which is not allowed according to XEP-60 5.3."); } - nodeMap.put(id, node); - } - @SuppressWarnings("unchecked") - T res = (T) node; - return res; - } + nodeMap.put(id, node); + } + @SuppressWarnings("unchecked") + T res = (T) node; + return res; + } - /** - * Get all the nodes that currently exist as a child of the specified - * collection node. If the service does not support collection nodes - * then all nodes will be returned. - * - * To retrieve contents of the root collection node (if it exists), - * or there is no root collection node, pass null as the nodeId. - * - * @param nodeId - The id of the collection node for which the child - * nodes will be returned. - * @return {@link DiscoverItems} representing the existing nodes - * @throws XMPPErrorException - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException - * @throws InterruptedException - */ - public DiscoverItems discoverNodes(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - DiscoverItems items = new DiscoverItems(); + /** + * Get all the nodes that currently exist as a child of the specified + * collection node. If the service does not support collection nodes + * then all nodes will be returned. + * + * To retrieve contents of the root collection node (if it exists), + * or there is no root collection node, pass null as the nodeId. + * + * @param nodeId - The id of the collection node for which the child + * nodes will be returned. + * @return {@link DiscoverItems} representing the existing nodes + * @throws XMPPErrorException + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException + * @throws InterruptedException + */ + public DiscoverItems discoverNodes(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + DiscoverItems items = new DiscoverItems(); - if (nodeId != null) - items.setNode(nodeId); - items.setTo(pubSubService); - DiscoverItems nodeItems = connection().createStanzaCollectorAndSend(items).nextResultOrThrow(); - return nodeItems; - } + if (nodeId != null) + items.setNode(nodeId); + items.setTo(pubSubService); + DiscoverItems nodeItems = connection().createStanzaCollectorAndSend(items).nextResultOrThrow(); + return nodeItems; + } - /** - * Gets the subscriptions on the root node. - * - * @return List of exceptions - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public List getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - Stanza reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.SUBSCRIPTIONS), null); - SubscriptionsExtension subElem = reply.getExtension(PubSubElementType.SUBSCRIPTIONS.getElementName(), PubSubElementType.SUBSCRIPTIONS.getNamespace().getXmlns()); - return subElem.getSubscriptions(); - } + /** + * Gets the subscriptions on the root node. + * + * @return List of exceptions + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public List getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + Stanza reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.SUBSCRIPTIONS), null); + SubscriptionsExtension subElem = reply.getExtension(PubSubElementType.SUBSCRIPTIONS.getElementName(), PubSubElementType.SUBSCRIPTIONS.getNamespace().getXmlns()); + return subElem.getSubscriptions(); + } - /** - * Gets the affiliations on the root node. - * - * @return List of affiliations - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - * - */ - public List getAffiliations() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - PubSub reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.AFFILIATIONS), null); - AffiliationsExtension listElem = reply.getExtension(PubSubElementType.AFFILIATIONS); - return listElem.getAffiliations(); - } + /** + * Gets the affiliations on the root node. + * + * @return List of affiliations + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * + */ + public List getAffiliations() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + PubSub reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.AFFILIATIONS), null); + AffiliationsExtension listElem = reply.getExtension(PubSubElementType.AFFILIATIONS); + return listElem.getAffiliations(); + } - /** - * Delete the specified node. - * - * @param nodeId - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public void deleteNode(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - sendPubsubPacket(Type.set, new NodeExtension(PubSubElementType.DELETE, nodeId), PubSubElementType.DELETE.getNamespace()); - nodeMap.remove(nodeId); - } + /** + * Delete the specified node. + * + * @param nodeId + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public void deleteNode(String nodeId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + sendPubsubPacket(Type.set, new NodeExtension(PubSubElementType.DELETE, nodeId), PubSubElementType.DELETE.getNamespace()); + nodeMap.remove(nodeId); + } - /** - * Returns the default settings for Node configuration. - * - * @return configuration form containing the default settings. - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public ConfigureForm getDefaultConfiguration() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - // Errors will cause exceptions in getReply, so it only returns - // on success. - PubSub reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.DEFAULT), PubSubElementType.DEFAULT.getNamespace()); - return NodeUtils.getFormFromPacket(reply, PubSubElementType.DEFAULT); - } + /** + * Returns the default settings for Node configuration. + * + * @return configuration form containing the default settings. + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public ConfigureForm getDefaultConfiguration() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + // Errors will cause exceptions in getReply, so it only returns + // on success. + PubSub reply = sendPubsubPacket(Type.get, new NodeExtension(PubSubElementType.DEFAULT), PubSubElementType.DEFAULT.getNamespace()); + return NodeUtils.getFormFromPacket(reply, PubSubElementType.DEFAULT); + } /** * Get the JID of the PubSub service managed by this manager. @@ -361,21 +361,21 @@ public final class PubSubManager extends Manager { return pubSubService; } - /** - * Gets the supported features of the servers pubsub implementation - * as a standard {@link DiscoverInfo} instance. - * - * @return The supported features - * @throws XMPPErrorException - * @throws NoResponseException - * @throws NotConnectedException - * @throws InterruptedException - */ - public DiscoverInfo getSupportedFeatures() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException - { - ServiceDiscoveryManager mgr = ServiceDiscoveryManager.getInstanceFor(connection()); - return mgr.discoverInfo(pubSubService); - } + /** + * Gets the supported features of the servers pubsub implementation + * as a standard {@link DiscoverInfo} instance. + * + * @return The supported features + * @throws XMPPErrorException + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + */ + public DiscoverInfo getSupportedFeatures() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException + { + ServiceDiscoveryManager mgr = ServiceDiscoveryManager.getInstanceFor(connection()); + return mgr.discoverInfo(pubSubService); + } /** * Check if it is possible to create PubSub nodes on this service. It could be possible that the @@ -424,13 +424,13 @@ public final class PubSubManager extends Manager { throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { // CHECKSTYLE:OFF - PubSub pubSub = new PubSub(to, type, ns); - for (ExtensionElement pe : extList) { - pubSub.addExtension(pe); - } + PubSub pubSub = new PubSub(to, type, ns); + for (ExtensionElement pe : extList) { + pubSub.addExtension(pe); + } // CHECKSTYLE:ON return sendPubsubPacket(pubSub); - } + } PubSub sendPubsubPacket(PubSub packet) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { @@ -439,7 +439,7 @@ public final class PubSubManager extends Manager { return null; } return (PubSub) resultIQ; - } + } /** * Get the "default" PubSub service for a given XMPP connection. The default PubSub service is diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishItem.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishItem.java index 8eb63c723..7229fb8a4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishItem.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishItem.java @@ -26,48 +26,48 @@ import java.util.Collection; */ public class PublishItem extends NodeExtension { - protected Collection items; + protected Collection items; - /** - * Construct a request to publish an item to a node. - * - * @param nodeId The node to publish to - * @param toPublish The {@link Item} to publish - */ - public PublishItem(String nodeId, T toPublish) - { - super(PubSubElementType.PUBLISH, nodeId); - items = new ArrayList(1); - items.add(toPublish); - } + /** + * Construct a request to publish an item to a node. + * + * @param nodeId The node to publish to + * @param toPublish The {@link Item} to publish + */ + public PublishItem(String nodeId, T toPublish) + { + super(PubSubElementType.PUBLISH, nodeId); + items = new ArrayList(1); + items.add(toPublish); + } - /** - * Construct a request to publish multiple items to a node. - * - * @param nodeId The node to publish to - * @param toPublish The list of {@link Item} to publish - */ - public PublishItem(String nodeId, Collection toPublish) - { - super(PubSubElementType.PUBLISH, nodeId); - items = toPublish; - } + /** + * Construct a request to publish multiple items to a node. + * + * @param nodeId The node to publish to + * @param toPublish The list of {@link Item} to publish + */ + public PublishItem(String nodeId, Collection toPublish) + { + super(PubSubElementType.PUBLISH, nodeId); + items = toPublish; + } - @Override - public String toXML() - { - StringBuilder builder = new StringBuilder("<"); - builder.append(getElementName()); - builder.append(" node='"); - builder.append(getNode()); - builder.append("'>"); + @Override + public String toXML() + { + StringBuilder builder = new StringBuilder("<"); + builder.append(getElementName()); + builder.append(" node='"); + builder.append(getNode()); + builder.append("'>"); - for (Item item : items) - { - builder.append(item.toXML()); - } - builder.append(""); + for (Item item : items) + { + builder.append(item.toXML()); + } + builder.append(""); - return builder.toString(); - } + return builder.toString(); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishModel.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishModel.java index 5e26ac7f9..4e207ddb1 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishModel.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PublishModel.java @@ -24,12 +24,12 @@ package org.jivesoftware.smackx.pubsub; */ public enum PublishModel { - /** Only publishers may publish. */ - publishers, + /** Only publishers may publish. */ + publishers, - /** Only subscribers may publish. */ - subscribers, + /** Only subscribers may publish. */ + subscribers, - /** Anyone may publish. */ - open; + /** Anyone may publish. */ + open; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/RetractItem.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/RetractItem.java index 8d21e93ce..6d3411680 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/RetractItem.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/RetractItem.java @@ -26,37 +26,40 @@ import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace; */ public class RetractItem implements ExtensionElement { - private String id; + private String id; - /** - * Construct a RetractItem with the specified id. - * - * @param itemId The id if the item deleted - */ - public RetractItem(String itemId) - { - if (itemId == null) - throw new IllegalArgumentException("itemId must not be 'null'"); - id = itemId; - } + /** + * Construct a RetractItem with the specified id. + * + * @param itemId The id if the item deleted + */ + public RetractItem(String itemId) + { + if (itemId == null) + throw new IllegalArgumentException("itemId must not be 'null'"); + id = itemId; + } - public String getId() - { - return id; - } + public String getId() + { + return id; + } - public String getElementName() - { - return "retract"; - } + @Override + public String getElementName() + { + return "retract"; + } - public String getNamespace() - { - return PubSubNamespace.EVENT.getXmlns(); - } + @Override + public String getNamespace() + { + return PubSubNamespace.EVENT.getXmlns(); + } - public String toXML() - { - return ""; - } + @Override + public String toXML() + { + return ""; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SimplePayload.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SimplePayload.java index a142b49db..1e747f62d 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SimplePayload.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SimplePayload.java @@ -26,44 +26,46 @@ import org.jivesoftware.smack.packet.ExtensionElement; */ public class SimplePayload implements ExtensionElement { - private final String elemName; - private final String ns; - private final CharSequence payload; + private final String elemName; + private final String ns; + private final CharSequence payload; - /** - * Construct a SimplePayload object with the specified element name, - * namespace and content. The content must be well formed XML. - * - * @param elementName The root element name (of the payload) - * @param namespace The namespace of the payload, null if there is none - * @param xmlPayload The payload data - */ - public SimplePayload(String elementName, String namespace, CharSequence xmlPayload) - { - elemName = elementName; - payload = xmlPayload; - ns = namespace; - } + /** + * Construct a SimplePayload object with the specified element name, + * namespace and content. The content must be well formed XML. + * + * @param elementName The root element name (of the payload) + * @param namespace The namespace of the payload, null if there is none + * @param xmlPayload The payload data + */ + public SimplePayload(String elementName, String namespace, CharSequence xmlPayload) + { + elemName = elementName; + payload = xmlPayload; + ns = namespace; + } - public String getElementName() - { - return elemName; - } + @Override + public String getElementName() + { + return elemName; + } - public String getNamespace() - { - return ns; - } + @Override + public String getNamespace() + { + return ns; + } - @Override - public CharSequence toXML() - { - return payload; - } + @Override + public CharSequence toXML() + { + return payload; + } - @Override - public String toString() - { - return getClass().getName() + "payload [" + toXML() + "]"; - } + @Override + public String toString() + { + return getClass().getName() + "payload [" + toXML() + "]"; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeExtension.java index 08485ab7d..ca4f82b6a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeExtension.java @@ -23,41 +23,41 @@ package org.jivesoftware.smackx.pubsub; */ public class SubscribeExtension extends NodeExtension { - protected String jid; + protected String jid; - public SubscribeExtension(String subscribeJid) - { - super(PubSubElementType.SUBSCRIBE); - jid = subscribeJid; - } + public SubscribeExtension(String subscribeJid) + { + super(PubSubElementType.SUBSCRIBE); + jid = subscribeJid; + } - public SubscribeExtension(String subscribeJid, String nodeId) - { - super(PubSubElementType.SUBSCRIBE, nodeId); - jid = subscribeJid; - } + public SubscribeExtension(String subscribeJid, String nodeId) + { + super(PubSubElementType.SUBSCRIBE, nodeId); + jid = subscribeJid; + } - public String getJid() - { - return jid; - } + public String getJid() + { + return jid; + } - @Override - public String toXML() - { - StringBuilder builder = new StringBuilder("<"); - builder.append(getElementName()); + @Override + public String toXML() + { + StringBuilder builder = new StringBuilder("<"); + builder.append(getElementName()); - if (getNode() != null) - { - builder.append(" node='"); - builder.append(getNode()); - builder.append('\''); - } - builder.append(" jid='"); - builder.append(getJid()); - builder.append("'/>"); + if (getNode() != null) + { + builder.append(" node='"); + builder.append(getNode()); + builder.append('\''); + } + builder.append(" jid='"); + builder.append(getJid()); + builder.append("'/>"); - return builder.toString(); - } + return builder.toString(); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeForm.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeForm.java index 00397dc62..d6a1ff84d 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeForm.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeForm.java @@ -40,202 +40,202 @@ import org.jivesoftware.smackx.xdata.packet.DataForm; */ public class SubscribeForm extends Form { - public SubscribeForm(DataForm configDataForm) - { - super(configDataForm); - } + public SubscribeForm(DataForm configDataForm) + { + super(configDataForm); + } - public SubscribeForm(Form subscribeOptionsForm) - { - super(subscribeOptionsForm.getDataFormToSend()); - } + public SubscribeForm(Form subscribeOptionsForm) + { + super(subscribeOptionsForm.getDataFormToSend()); + } - public SubscribeForm(DataForm.Type formType) - { - super(formType); - } + public SubscribeForm(DataForm.Type formType) + { + super(formType); + } - /** - * Determines if an entity wants to receive notifications. - * - * @return true if want to receive, false otherwise - */ - public boolean isDeliverOn() - { - return parseBoolean(getFieldValue(SubscribeOptionFields.deliver)); - } + /** + * Determines if an entity wants to receive notifications. + * + * @return true if want to receive, false otherwise + */ + public boolean isDeliverOn() + { + return parseBoolean(getFieldValue(SubscribeOptionFields.deliver)); + } - /** - * Sets whether an entity wants to receive notifications. - * - * @param deliverNotifications - */ - public void setDeliverOn(boolean deliverNotifications) - { - addField(SubscribeOptionFields.deliver, FormField.Type.bool); - setAnswer(SubscribeOptionFields.deliver.getFieldName(), deliverNotifications); - } + /** + * Sets whether an entity wants to receive notifications. + * + * @param deliverNotifications + */ + public void setDeliverOn(boolean deliverNotifications) + { + addField(SubscribeOptionFields.deliver, FormField.Type.bool); + setAnswer(SubscribeOptionFields.deliver.getFieldName(), deliverNotifications); + } - /** - * Determines if notifications should be delivered as aggregations or not. - * - * @return true to aggregate, false otherwise - */ - public boolean isDigestOn() - { - return parseBoolean(getFieldValue(SubscribeOptionFields.digest)); - } + /** + * Determines if notifications should be delivered as aggregations or not. + * + * @return true to aggregate, false otherwise + */ + public boolean isDigestOn() + { + return parseBoolean(getFieldValue(SubscribeOptionFields.digest)); + } - /** - * Sets whether notifications should be delivered as aggregations or not. - * - * @param digestOn true to aggregate, false otherwise - */ - public void setDigestOn(boolean digestOn) - { - addField(SubscribeOptionFields.deliver, FormField.Type.bool); - setAnswer(SubscribeOptionFields.deliver.getFieldName(), digestOn); - } + /** + * Sets whether notifications should be delivered as aggregations or not. + * + * @param digestOn true to aggregate, false otherwise + */ + public void setDigestOn(boolean digestOn) + { + addField(SubscribeOptionFields.deliver, FormField.Type.bool); + setAnswer(SubscribeOptionFields.deliver.getFieldName(), digestOn); + } - /** - * Gets the minimum number of milliseconds between sending notification digests. - * - * @return The frequency in milliseconds - */ - public int getDigestFrequency() - { - return Integer.parseInt(getFieldValue(SubscribeOptionFields.digest_frequency)); - } + /** + * Gets the minimum number of milliseconds between sending notification digests. + * + * @return The frequency in milliseconds + */ + public int getDigestFrequency() + { + return Integer.parseInt(getFieldValue(SubscribeOptionFields.digest_frequency)); + } - /** - * Sets the minimum number of milliseconds between sending notification digests. - * - * @param frequency The frequency in milliseconds - */ - public void setDigestFrequency(int frequency) - { - addField(SubscribeOptionFields.digest_frequency, FormField.Type.text_single); - setAnswer(SubscribeOptionFields.digest_frequency.getFieldName(), frequency); - } + /** + * Sets the minimum number of milliseconds between sending notification digests. + * + * @param frequency The frequency in milliseconds + */ + public void setDigestFrequency(int frequency) + { + addField(SubscribeOptionFields.digest_frequency, FormField.Type.text_single); + setAnswer(SubscribeOptionFields.digest_frequency.getFieldName(), frequency); + } - /** - * Get the time at which the leased subscription will expire, or has expired. - * - * @return The expiry date - */ - public Date getExpiry() - { - String dateTime = getFieldValue(SubscribeOptionFields.expire); - try - { - return XmppDateTime.parseDate(dateTime); - } - catch (ParseException e) - { - UnknownFormatConversionException exc = new UnknownFormatConversionException(dateTime); - exc.initCause(e); - throw exc; - } - } + /** + * Get the time at which the leased subscription will expire, or has expired. + * + * @return The expiry date + */ + public Date getExpiry() + { + String dateTime = getFieldValue(SubscribeOptionFields.expire); + try + { + return XmppDateTime.parseDate(dateTime); + } + catch (ParseException e) + { + UnknownFormatConversionException exc = new UnknownFormatConversionException(dateTime); + exc.initCause(e); + throw exc; + } + } - /** - * Sets the time at which the leased subscription will expire, or has expired. - * - * @param expire The expiry date - */ - public void setExpiry(Date expire) - { - addField(SubscribeOptionFields.expire, FormField.Type.text_single); - setAnswer(SubscribeOptionFields.expire.getFieldName(), XmppDateTime.formatXEP0082Date(expire)); - } + /** + * Sets the time at which the leased subscription will expire, or has expired. + * + * @param expire The expiry date + */ + public void setExpiry(Date expire) + { + addField(SubscribeOptionFields.expire, FormField.Type.text_single); + setAnswer(SubscribeOptionFields.expire.getFieldName(), XmppDateTime.formatXEP0082Date(expire)); + } - /** - * Determines whether the entity wants to receive an XMPP message body in - * addition to the payload format. - * - * @return true to receive the message body, false otherwise - */ - public boolean isIncludeBody() - { - return parseBoolean(getFieldValue(SubscribeOptionFields.include_body)); - } + /** + * Determines whether the entity wants to receive an XMPP message body in + * addition to the payload format. + * + * @return true to receive the message body, false otherwise + */ + public boolean isIncludeBody() + { + return parseBoolean(getFieldValue(SubscribeOptionFields.include_body)); + } - /** - * Sets whether the entity wants to receive an XMPP message body in - * addition to the payload format. - * - * @param include true to receive the message body, false otherwise - */ - public void setIncludeBody(boolean include) - { - addField(SubscribeOptionFields.include_body, FormField.Type.bool); - setAnswer(SubscribeOptionFields.include_body.getFieldName(), include); - } + /** + * Sets whether the entity wants to receive an XMPP message body in + * addition to the payload format. + * + * @param include true to receive the message body, false otherwise + */ + public void setIncludeBody(boolean include) + { + addField(SubscribeOptionFields.include_body, FormField.Type.bool); + setAnswer(SubscribeOptionFields.include_body.getFieldName(), include); + } - /** - * Gets the {@link PresenceState} for which an entity wants to receive - * notifications. - * - * @return the list of states - */ - public List getShowValues() - { - ArrayList result = new ArrayList(5); + /** + * Gets the {@link PresenceState} for which an entity wants to receive + * notifications. + * + * @return the list of states + */ + public List getShowValues() + { + ArrayList result = new ArrayList(5); - for (String state : getFieldValues(SubscribeOptionFields.show_values)) - { - result.add(PresenceState.valueOf(state)); - } - return result; - } + for (String state : getFieldValues(SubscribeOptionFields.show_values)) + { + result.add(PresenceState.valueOf(state)); + } + return result; + } - /** - * Sets the list of {@link PresenceState} for which an entity wants - * to receive notifications. - * - * @param stateValues The list of states - */ - public void setShowValues(Collection stateValues) - { - ArrayList values = new ArrayList(stateValues.size()); + /** + * Sets the list of {@link PresenceState} for which an entity wants + * to receive notifications. + * + * @param stateValues The list of states + */ + public void setShowValues(Collection stateValues) + { + ArrayList values = new ArrayList(stateValues.size()); - for (PresenceState state : stateValues) - { - values.add(state.toString()); - } - addField(SubscribeOptionFields.show_values, FormField.Type.list_multi); - setAnswer(SubscribeOptionFields.show_values.getFieldName(), values); - } + for (PresenceState state : stateValues) + { + values.add(state.toString()); + } + addField(SubscribeOptionFields.show_values, FormField.Type.list_multi); + setAnswer(SubscribeOptionFields.show_values.getFieldName(), values); + } - static private boolean parseBoolean(String fieldValue) - { - return ("1".equals(fieldValue) || "true".equals(fieldValue)); - } + static private boolean parseBoolean(String fieldValue) + { + return ("1".equals(fieldValue) || "true".equals(fieldValue)); + } - private String getFieldValue(SubscribeOptionFields field) - { - FormField formField = getField(field.getFieldName()); + private String getFieldValue(SubscribeOptionFields field) + { + FormField formField = getField(field.getFieldName()); - return formField.getValues().get(0); - } + return formField.getValues().get(0); + } - private List getFieldValues(SubscribeOptionFields field) - { - FormField formField = getField(field.getFieldName()); + private List getFieldValues(SubscribeOptionFields field) + { + FormField formField = getField(field.getFieldName()); - return formField.getValues(); - } + return formField.getValues(); + } - private void addField(SubscribeOptionFields nodeField, FormField.Type type) - { - String fieldName = nodeField.getFieldName(); + private void addField(SubscribeOptionFields nodeField, FormField.Type type) + { + String fieldName = nodeField.getFieldName(); - if (getField(fieldName) == null) - { - FormField field = new FormField(fieldName); - field.setType(type); - addField(field); - } - } + if (getField(fieldName) == null) + { + FormField field = new FormField(fieldName); + field.setType(type); + addField(field); + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeOptionFields.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeOptionFields.java index e1c2f84bd..c3ba4a6a2 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeOptionFields.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscribeOptionFields.java @@ -26,77 +26,77 @@ import java.util.Calendar; */ public enum SubscribeOptionFields { - /** - * Whether an entity wants to receive or disable notifications. - * - *

Value: boolean

- */ - deliver, + /** + * Whether an entity wants to receive or disable notifications. + * + *

Value: boolean

+ */ + deliver, - /** - * Whether an entity wants to receive digests (aggregations) of - * notifications or all notifications individually. - * - *

Value: boolean

- */ - digest, + /** + * Whether an entity wants to receive digests (aggregations) of + * notifications or all notifications individually. + * + *

Value: boolean

+ */ + digest, - /** - * The minimum number of seconds between sending any two notifications digests. - * - *

Value: int

- */ - digest_frequency, + /** + * The minimum number of seconds between sending any two notifications digests. + * + *

Value: int

+ */ + digest_frequency, - /** - * Expire. - *

Value: {@link Calendar}

- */ - expire, + /** + * Expire. + *

Value: {@link Calendar}

+ */ + expire, - /** - * Whether an entity wants to receive an XMPP message body in addition to - * the payload format. - * - *

Value: boolean

- */ - include_body, + /** + * Whether an entity wants to receive an XMPP message body in addition to + * the payload format. + * + *

Value: boolean

+ */ + include_body, - /** - * The presence states for which an entity wants to receive notifications. - * - *

Value: {@link PresenceState}

- */ - show_values, + /** + * The presence states for which an entity wants to receive notifications. + * + *

Value: {@link PresenceState}

+ */ + show_values, - /** - * Subscription type. - * - *

Value:

- */ - subscription_type, + /** + * Subscription type. + * + *

Value:

+ */ + subscription_type, - /** - * Subscription depth. - * - *

Value:

- */ - subscription_depth; + /** + * Subscription depth. + * + *

Value:

+ */ + subscription_depth; - public String getFieldName() - { - if (this == show_values) - return "pubsub#" + toString().replace('_', '-'); - return "pubsub#" + toString(); - } + public String getFieldName() + { + if (this == show_values) + return "pubsub#" + toString().replace('_', '-'); + return "pubsub#" + toString(); + } - static public SubscribeOptionFields valueOfFromElement(String elementName) - { - String portion = elementName.substring(elementName.lastIndexOf('#' + 1)); + static public SubscribeOptionFields valueOfFromElement(String elementName) + { + String portion = elementName.substring(elementName.lastIndexOf('#' + 1)); - if ("show-values".equals(portion)) - return show_values; - else - return valueOf(portion); - } + if ("show-values".equals(portion)) + return show_values; + else + return valueOf(portion); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Subscription.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Subscription.java index 4308639bc..bc4d0ac68 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Subscription.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Subscription.java @@ -23,141 +23,142 @@ package org.jivesoftware.smackx.pubsub; */ public class Subscription extends NodeExtension { - protected String jid; - protected String id; - protected State state; - protected boolean configRequired = false; + protected String jid; + protected String id; + protected State state; + protected boolean configRequired = false; - public enum State - { - subscribed, unconfigured, pending, none - } + public enum State + { + subscribed, unconfigured, pending, none + } - /** - * Used to constructs a subscription request to the root node with the specified - * JID. - * - * @param subscriptionJid The subscriber JID - */ - public Subscription(String subscriptionJid) - { - this(subscriptionJid, null, null, null); - } + /** + * Used to constructs a subscription request to the root node with the specified + * JID. + * + * @param subscriptionJid The subscriber JID + */ + public Subscription(String subscriptionJid) + { + this(subscriptionJid, null, null, null); + } - /** - * Used to constructs a subscription request to the specified node with the specified - * JID. - * - * @param subscriptionJid The subscriber JID - * @param nodeId The node id - */ - public Subscription(String subscriptionJid, String nodeId) - { - this(subscriptionJid, nodeId, null, null); - } + /** + * Used to constructs a subscription request to the specified node with the specified + * JID. + * + * @param subscriptionJid The subscriber JID + * @param nodeId The node id + */ + public Subscription(String subscriptionJid, String nodeId) + { + this(subscriptionJid, nodeId, null, null); + } - /** - * Constructs a representation of a subscription reply to the specified node - * and JID. The server will have supplied the subscription id and current state. - * - * @param jid The JID the request was made under - * @param nodeId The node subscribed to - * @param subscriptionId The id of this subscription - * @param state The current state of the subscription - */ - public Subscription(String jid, String nodeId, String subscriptionId, State state) - { - super(PubSubElementType.SUBSCRIPTION, nodeId); - this.jid = jid; - id = subscriptionId; - this.state = state; - } + /** + * Constructs a representation of a subscription reply to the specified node + * and JID. The server will have supplied the subscription id and current state. + * + * @param jid The JID the request was made under + * @param nodeId The node subscribed to + * @param subscriptionId The id of this subscription + * @param state The current state of the subscription + */ + public Subscription(String jid, String nodeId, String subscriptionId, State state) + { + super(PubSubElementType.SUBSCRIPTION, nodeId); + this.jid = jid; + id = subscriptionId; + this.state = state; + } - /** - * Constructs a representation of a subscription reply to the specified node - * and JID. The server will have supplied the subscription id and current state - * and whether the subscription need to be configured. - * - * @param jid The JID the request was made under - * @param nodeId The node subscribed to - * @param subscriptionId The id of this subscription - * @param state The current state of the subscription - * @param configRequired Is configuration required to complete the subscription - */ - public Subscription(String jid, String nodeId, String subscriptionId, State state, boolean configRequired) - { - super(PubSubElementType.SUBSCRIPTION, nodeId); - this.jid = jid; - id = subscriptionId; - this.state = state; - this.configRequired = configRequired; - } + /** + * Constructs a representation of a subscription reply to the specified node + * and JID. The server will have supplied the subscription id and current state + * and whether the subscription need to be configured. + * + * @param jid The JID the request was made under + * @param nodeId The node subscribed to + * @param subscriptionId The id of this subscription + * @param state The current state of the subscription + * @param configRequired Is configuration required to complete the subscription + */ + public Subscription(String jid, String nodeId, String subscriptionId, State state, boolean configRequired) + { + super(PubSubElementType.SUBSCRIPTION, nodeId); + this.jid = jid; + id = subscriptionId; + this.state = state; + this.configRequired = configRequired; + } - /** - * Gets the JID the subscription is created for. - * - * @return The JID - */ - public String getJid() - { - return jid; - } + /** + * Gets the JID the subscription is created for. + * + * @return The JID + */ + public String getJid() + { + return jid; + } - /** - * Gets the subscription id. - * - * @return The subscription id - */ - public String getId() - { - return id; - } + /** + * Gets the subscription id. + * + * @return The subscription id + */ + public String getId() + { + return id; + } - /** - * Gets the current subscription state. - * - * @return Current subscription state - */ - public State getState() - { - return state; - } + /** + * Gets the current subscription state. + * + * @return Current subscription state + */ + public State getState() + { + return state; + } - /** - * This value is only relevant when the {@link #getState()} is {@link State#unconfigured}. - * - * @return true if configuration is required, false otherwise - */ - public boolean isConfigRequired() - { - return configRequired; - } + /** + * This value is only relevant when the {@link #getState()} is {@link State#unconfigured}. + * + * @return true if configuration is required, false otherwise + */ + public boolean isConfigRequired() + { + return configRequired; + } - public String toXML() - { - StringBuilder builder = new StringBuilder(""); - return builder.toString(); - } + builder.append("/>"); + return builder.toString(); + } - private static void appendAttribute(StringBuilder builder, String att, String value) - { - builder.append(' '); - builder.append(att); - builder.append("='"); - builder.append(value); - builder.append('\''); - } + private static void appendAttribute(StringBuilder builder, String att, String value) + { + builder.append(' '); + builder.append(att); + builder.append("='"); + builder.append(value); + builder.append('\''); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionEvent.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionEvent.java index adcfc3918..2d087847c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionEvent.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionEvent.java @@ -26,53 +26,53 @@ import java.util.List; */ abstract public class SubscriptionEvent extends NodeEvent { - private List subIds = Collections.emptyList(); + private List subIds = Collections.emptyList(); - /** - * Construct an event with no subscription id's. This can - * occur when there is only one subscription to a node. The - * event may or may not report the subscription id along - * with the event. - * - * @param nodeId The id of the node the event came from - */ - protected SubscriptionEvent(String nodeId) - { - super(nodeId); - } + /** + * Construct an event with no subscription id's. This can + * occur when there is only one subscription to a node. The + * event may or may not report the subscription id along + * with the event. + * + * @param nodeId The id of the node the event came from + */ + protected SubscriptionEvent(String nodeId) + { + super(nodeId); + } - /** - * Construct an event with multiple subscriptions. - * - * @param nodeId The id of the node the event came from - * @param subscriptionIds The list of subscription id's - */ - protected SubscriptionEvent(String nodeId, List subscriptionIds) - { - super(nodeId); + /** + * Construct an event with multiple subscriptions. + * + * @param nodeId The id of the node the event came from + * @param subscriptionIds The list of subscription id's + */ + protected SubscriptionEvent(String nodeId, List subscriptionIds) + { + super(nodeId); - if (subscriptionIds != null) - subIds = subscriptionIds; - } + if (subscriptionIds != null) + subIds = subscriptionIds; + } - /** - * Get the subscriptions this event is associated with. - * - * @return List of subscription id's - */ - public List getSubscriptions() - { - return Collections.unmodifiableList(subIds); - } + /** + * Get the subscriptions this event is associated with. + * + * @return List of subscription id's + */ + public List getSubscriptions() + { + return Collections.unmodifiableList(subIds); + } - /** - * Set the list of subscription id's for this event. - * - * @param subscriptionIds The list of subscription id's - */ - protected void setSubscriptions(List subscriptionIds) - { - if (subscriptionIds != null) - subIds = subscriptionIds; - } + /** + * Set the list of subscription id's for this event. + * + * @param subscriptionIds The list of subscription id's + */ + protected void setSubscriptions(List subscriptionIds) + { + if (subscriptionIds != null) + subIds = subscriptionIds; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionsExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionsExtension.java index dad68e891..59b64f16f 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionsExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/SubscriptionsExtension.java @@ -26,74 +26,74 @@ import java.util.List; */ public class SubscriptionsExtension extends NodeExtension { - protected List items = Collections.emptyList(); + protected List items = Collections.emptyList(); - /** - * Subscriptions to the root node. - * - * @param subList The list of subscriptions - */ - public SubscriptionsExtension(List subList) - { - super(PubSubElementType.SUBSCRIPTIONS); + /** + * Subscriptions to the root node. + * + * @param subList The list of subscriptions + */ + public SubscriptionsExtension(List subList) + { + super(PubSubElementType.SUBSCRIPTIONS); - if (subList != null) - items = subList; - } + if (subList != null) + items = subList; + } - /** - * Subscriptions to the specified node. - * - * @param nodeId The node subscribed to - * @param subList The list of subscriptions - */ - public SubscriptionsExtension(String nodeId, List subList) - { - super(PubSubElementType.SUBSCRIPTIONS, nodeId); + /** + * Subscriptions to the specified node. + * + * @param nodeId The node subscribed to + * @param subList The list of subscriptions + */ + public SubscriptionsExtension(String nodeId, List subList) + { + super(PubSubElementType.SUBSCRIPTIONS, nodeId); - if (subList != null) - items = subList; - } + if (subList != null) + items = subList; + } - /** - * Gets the list of subscriptions. - * - * @return List of subscriptions - */ - public List getSubscriptions() - { - return items; - } + /** + * Gets the list of subscriptions. + * + * @return List of subscriptions + */ + public List getSubscriptions() + { + return items; + } - @Override - public CharSequence toXML() - { - if ((items == null) || (items.size() == 0)) - { - return super.toXML(); - } - else - { - StringBuilder builder = new StringBuilder("<"); - builder.append(getElementName()); + @Override + public CharSequence toXML() + { + if ((items == null) || (items.size() == 0)) + { + return super.toXML(); + } + else + { + StringBuilder builder = new StringBuilder("<"); + builder.append(getElementName()); - if (getNode() != null) - { - builder.append(" node='"); - builder.append(getNode()); - builder.append('\''); - } - builder.append('>'); + if (getNode() != null) + { + builder.append(" node='"); + builder.append(getNode()); + builder.append('\''); + } + builder.append('>'); - for (Subscription item : items) - { - builder.append(item.toXML()); - } + for (Subscription item : items) + { + builder.append(item.toXML()); + } - builder.append("'); - return builder.toString(); - } - } + builder.append("'); + return builder.toString(); + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/UnsubscribeExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/UnsubscribeExtension.java index db9103a6d..0e4d9c009 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/UnsubscribeExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/UnsubscribeExtension.java @@ -26,35 +26,35 @@ import org.jivesoftware.smack.util.XmlStringBuilder; */ public class UnsubscribeExtension extends NodeExtension { - protected String jid; - protected String id; + protected String jid; + protected String id; - public UnsubscribeExtension(String subscriptionJid) - { - this(subscriptionJid, null, null); - } + public UnsubscribeExtension(String subscriptionJid) + { + this(subscriptionJid, null, null); + } - public UnsubscribeExtension(String subscriptionJid, String nodeId) - { - this(subscriptionJid, nodeId, null); - } + public UnsubscribeExtension(String subscriptionJid, String nodeId) + { + this(subscriptionJid, nodeId, null); + } - public UnsubscribeExtension(String jid, String nodeId, String subscriptionId) - { - super(PubSubElementType.UNSUBSCRIBE, nodeId); - this.jid = jid; - id = subscriptionId; - } + public UnsubscribeExtension(String jid, String nodeId, String subscriptionId) + { + super(PubSubElementType.UNSUBSCRIBE, nodeId); + this.jid = jid; + id = subscriptionId; + } - public String getJid() - { - return jid; - } + public String getJid() + { + return jid; + } - public String getId() - { - return id; - } + public String getId() + { + return id; + } @Override public XmlStringBuilder toXML() { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemDeleteListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemDeleteListener.java index 24b9faef8..7b72ae52e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemDeleteListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemDeleteListener.java @@ -28,17 +28,17 @@ import org.jivesoftware.smackx.pubsub.LeafNode; */ public interface ItemDeleteListener { - /** - * Called when items are deleted from a node the listener is - * registered with. - * - * @param items The event with item deletion details - */ - void handleDeletedItems(ItemDeleteEvent items); + /** + * Called when items are deleted from a node the listener is + * registered with. + * + * @param items The event with item deletion details + */ + void handleDeletedItems(ItemDeleteEvent items); - /** - * Called when all items are deleted from a node the listener is - * registered with. - */ - void handlePurge(); + /** + * Called when all items are deleted from a node the listener is + * registered with. + */ + void handlePurge(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemEventListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemEventListener.java index 9724de58d..6d4c6a9a4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemEventListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/ItemEventListener.java @@ -29,11 +29,11 @@ import org.jivesoftware.smackx.pubsub.LeafNode; */ public interface ItemEventListener { - /** - * Called whenever an item is published to the node the listener - * is registered with. - * - * @param items The publishing details. - */ - void handlePublishedItems(ItemPublishEvent items); + /** + * Called whenever an item is published to the node the listener + * is registered with. + * + * @param items The publishing details. + */ + void handlePublishedItems(ItemPublishEvent items); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/NodeConfigListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/NodeConfigListener.java index 55a97d05c..03bd71d9a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/NodeConfigListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/listener/NodeConfigListener.java @@ -28,11 +28,11 @@ import org.jivesoftware.smackx.pubsub.LeafNode; */ public interface NodeConfigListener { - /** - * Called whenever the node the listener - * is registered with is configured. - * - * @param config The configuration details. - */ - void handleNodeConfiguration(ConfigurationEvent config); + /** + * Called whenever the node the listener + * is registered with is configured. + * + * @param config The configuration details. + */ + void handleNodeConfiguration(ConfigurationEvent config); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSub.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSub.java index cf6e97efc..79bd54fbd 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSub.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSub.java @@ -33,11 +33,11 @@ public class PubSub extends IQ public static final String ELEMENT = "pubsub"; public static final String NAMESPACE = "http://jabber.org/protocol/pubsub"; - public PubSub() { + public PubSub() { super(ELEMENT, NAMESPACE); - } + } - public PubSub(PubSubNamespace ns) { + public PubSub(PubSubNamespace ns) { super(ELEMENT, ns.getXmlns()); } @@ -49,9 +49,9 @@ public class PubSub extends IQ @SuppressWarnings("unchecked") public PE getExtension(PubSubElementType elem) - { - return (PE) getExtension(elem.getElementName(), elem.getNamespace().getXmlns()); - } + { + return (PE) getExtension(elem.getElementName(), elem.getNamespace().getXmlns()); + } /** * Returns the XML representation of a pubsub element according the specification. diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSubNamespace.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSubNamespace.java index b8a16db83..da8822447 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSubNamespace.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/packet/PubSubNamespace.java @@ -26,45 +26,45 @@ import java.util.Locale; */ public enum PubSubNamespace { - BASIC(null), - ERROR("errors"), - EVENT("event"), - OWNER("owner"); + BASIC(null), + ERROR("errors"), + EVENT("event"), + OWNER("owner"); private final String fragment; private final String fullNamespace; - private PubSubNamespace(String fragment) - { - this.fragment = fragment; + private PubSubNamespace(String fragment) + { + this.fragment = fragment; if (fragment != null) { fullNamespace = PubSub.NAMESPACE + '#' + fragment; } else { fullNamespace = PubSub.NAMESPACE; } - } + } - public String getXmlns() - { + public String getXmlns() + { return fullNamespace; - } + } - public String getFragment() - { - return fragment; - } + public String getFragment() + { + return fragment; + } - public static PubSubNamespace valueOfFromXmlns(String ns) - { - int index = ns.lastIndexOf('#'); + public static PubSubNamespace valueOfFromXmlns(String ns) + { + int index = ns.lastIndexOf('#'); - if (index != -1) - { - String suffix = ns.substring(ns.lastIndexOf('#')+1); - return valueOf(suffix.toUpperCase(Locale.US)); - } - else - return BASIC; - } + if (index != -1) + { + String suffix = ns.substring(ns.lastIndexOf('#')+1); + return valueOf(suffix.toUpperCase(Locale.US)); + } + else + return BASIC; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/AffiliationsProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/AffiliationsProvider.java index 195cbc8a7..f1ba37f67 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/AffiliationsProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/AffiliationsProvider.java @@ -31,11 +31,11 @@ import org.jivesoftware.smackx.pubsub.AffiliationsExtension; * @author Robin Collier */public class AffiliationsProvider extends EmbeddedExtensionProvider { - @SuppressWarnings("unchecked") - @Override - protected AffiliationsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { + @SuppressWarnings("unchecked") + @Override + protected AffiliationsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { return new AffiliationsExtension((List)content); - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ConfigEventProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ConfigEventProvider.java index e6cb6f7ca..bd3da7331 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ConfigEventProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ConfigEventProvider.java @@ -33,12 +33,12 @@ import org.jivesoftware.smackx.xdata.packet.DataForm; */ public class ConfigEventProvider extends EmbeddedExtensionProvider { - @Override - protected ConfigurationEvent createReturnExtension(String currentElement, String currentNamespace, Map attMap, List content) - { - if (content.size() == 0) - return new ConfigurationEvent(attMap.get("node")); - else - return new ConfigurationEvent(attMap.get("node"), new ConfigureForm((DataForm)content.iterator().next())); - } + @Override + protected ConfigurationEvent createReturnExtension(String currentElement, String currentNamespace, Map attMap, List content) + { + if (content.size() == 0) + return new ConfigurationEvent(attMap.get("node")); + else + return new ConfigurationEvent(attMap.get("node"), new ConfigureForm((DataForm)content.iterator().next())); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/EventProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/EventProvider.java index d4a237e57..2e252c2a0 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/EventProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/EventProvider.java @@ -33,11 +33,9 @@ import org.jivesoftware.smackx.pubsub.NodeExtension; */ public class EventProvider extends EmbeddedExtensionProvider { - @Override - protected EventElement createReturnExtension(String currentElement, String currentNamespace, Map attMap, List content) - { -// CHECKSTYLE:OFF - return new EventElement(EventElementType.valueOf(content.get(0).getElementName()), (NodeExtension)content.get(0)); -// CHECKSTYLE:ON - } + @Override + protected EventElement createReturnExtension(String currentElement, String currentNamespace, Map attMap, List content) + { + return new EventElement(EventElementType.valueOf(content.get(0).getElementName()), (NodeExtension)content.get(0)); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/FormNodeProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/FormNodeProvider.java index 86f16bd6e..2766d9334 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/FormNodeProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/FormNodeProvider.java @@ -34,9 +34,9 @@ import org.jivesoftware.smackx.xdata.packet.DataForm; */ public class FormNodeProvider extends EmbeddedExtensionProvider { - @Override - protected FormNode createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { + @Override + protected FormNode createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { return new FormNode(FormNodeType.valueOfFromElementName(currentElement, currentNamespace), attributeMap.get("node"), new Form((DataForm)content.iterator().next())); - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ItemsProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ItemsProvider.java index 6c52862d3..4e1f4c167 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ItemsProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/ItemsProvider.java @@ -32,10 +32,10 @@ import org.jivesoftware.smackx.pubsub.ItemsExtension; public class ItemsProvider extends EmbeddedExtensionProvider { - @Override - protected ItemsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { + @Override + protected ItemsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { return new ItemsExtension(ItemsExtension.ItemsElementType.items, attributeMap.get("node"), content); - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/PubSubProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/PubSubProvider.java index b23fd5ec1..e5938c63e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/PubSubProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/PubSubProvider.java @@ -53,5 +53,5 @@ public class PubSubProvider extends IQProvider } } return pubsub; - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/RetractEventProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/RetractEventProvider.java index f329caf0d..c3d14fa70 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/RetractEventProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/RetractEventProvider.java @@ -32,10 +32,10 @@ import org.jivesoftware.smackx.pubsub.RetractItem; */ public class RetractEventProvider extends EmbeddedExtensionProvider { - @Override - protected RetractItem createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { - return new RetractItem(attributeMap.get("id")); - } + @Override + protected RetractItem createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { + return new RetractItem(attributeMap.get("id")); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SimpleNodeProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SimpleNodeProvider.java index 31782fa11..b2d853eca 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SimpleNodeProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SimpleNodeProvider.java @@ -32,9 +32,9 @@ import org.jivesoftware.smackx.pubsub.PubSubElementType; */ public class SimpleNodeProvider extends EmbeddedExtensionProvider { - @Override - protected NodeExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { + @Override + protected NodeExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { return new NodeExtension(PubSubElementType.valueOfFromElemName(currentElement, currentNamespace), attributeMap.get("node")); - } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionProvider.java index fd6ca04e0..afc7dfc57 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionProvider.java @@ -34,25 +34,25 @@ public class SubscriptionProvider extends ExtensionElementProvider @Override public Subscription parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException { - String jid = parser.getAttributeValue(null, "jid"); - String nodeId = parser.getAttributeValue(null, "node"); - String subId = parser.getAttributeValue(null, "subid"); - String state = parser.getAttributeValue(null, "subscription"); - boolean isRequired = false; + String jid = parser.getAttributeValue(null, "jid"); + String nodeId = parser.getAttributeValue(null, "node"); + String subId = parser.getAttributeValue(null, "subid"); + String state = parser.getAttributeValue(null, "subscription"); + boolean isRequired = false; - int tag = parser.next(); + int tag = parser.next(); - if ((tag == XmlPullParser.START_TAG) && parser.getName().equals("subscribe-options")) - { - tag = parser.next(); + if ((tag == XmlPullParser.START_TAG) && parser.getName().equals("subscribe-options")) + { + tag = parser.next(); - if ((tag == XmlPullParser.START_TAG) && parser.getName().equals("required")) - isRequired = true; + if ((tag == XmlPullParser.START_TAG) && parser.getName().equals("required")) + isRequired = true; - while (tag != XmlPullParser.END_TAG && !parser.getName().equals("subscribe-options")) tag = parser.next(); - } - while (parser.getEventType() != XmlPullParser.END_TAG) parser.next(); - return new Subscription(jid, nodeId, subId, (state == null ? null : Subscription.State.valueOf(state)), isRequired); - } + while (tag != XmlPullParser.END_TAG && !parser.getName().equals("subscribe-options")) tag = parser.next(); + } + while (parser.getEventType() != XmlPullParser.END_TAG) parser.next(); + return new Subscription(jid, nodeId, subId, (state == null ? null : Subscription.State.valueOf(state)), isRequired); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionsProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionsProvider.java index 69e4fb183..d642df63b 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionsProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionsProvider.java @@ -32,11 +32,11 @@ import org.jivesoftware.smackx.pubsub.SubscriptionsExtension; */ public class SubscriptionsProvider extends EmbeddedExtensionProvider { - @SuppressWarnings("unchecked") - @Override - protected SubscriptionsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) - { - return new SubscriptionsExtension(attributeMap.get("node"), (List)content); - } + @SuppressWarnings("unchecked") + @Override + protected SubscriptionsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) + { + return new SubscriptionsExtension(attributeMap.get("node"), (List)content); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/util/NodeUtils.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/util/NodeUtils.java index 0c7687c2d..acf67c68c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/util/NodeUtils.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/util/NodeUtils.java @@ -29,17 +29,17 @@ import org.jivesoftware.smackx.xdata.Form; */ public class NodeUtils { - /** - * Get a {@link ConfigureForm} from a packet. - * - * @param packet - * @param elem - * @return The configuration form - */ - public static ConfigureForm getFormFromPacket(Stanza packet, PubSubElementType elem) - { - FormNode config = packet.getExtension(elem.getElementName(), elem.getNamespace().getXmlns()); - Form formReply = config.getForm(); - return new ConfigureForm(formReply); - } + /** + * Get a {@link ConfigureForm} from a packet. + * + * @param packet + * @param elem + * @return The configuration form + */ + public static ConfigureForm getFormFromPacket(Stanza packet, PubSubElementType elem) + { + FormNode config = packet.getExtension(elem.getElementName(), elem.getNamespace().getXmlns()); + Form formReply = config.getForm(); + return new ConfigureForm(formReply); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java index eee423261..bc8e1dff6 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java @@ -83,6 +83,7 @@ public final class DeliveryReceiptManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java index 622f003fb..888d4d127 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java @@ -36,16 +36,19 @@ public class DeliveryReceiptRequest implements ExtensionElement { public static final String ELEMENT = "request"; + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return DeliveryReceipt.NAMESPACE; } + @Override public String toXML() { return ""; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/Header.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/Header.java index f6461488c..2cb8f9000 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/Header.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/Header.java @@ -44,10 +44,12 @@ public class Header implements ExtensionElement { return value; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return HeadersExtension.NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/HeadersExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/HeadersExtension.java index 215c0f37e..62f0cc28e 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/HeadersExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/shim/packet/HeadersExtension.java @@ -48,10 +48,12 @@ public class HeadersExtension implements ExtensionElement { return headers; } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/si/packet/StreamInitiation.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/si/packet/StreamInitiation.java index d6879a580..582268aad 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/si/packet/StreamInitiation.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/si/packet/StreamInitiation.java @@ -317,14 +317,17 @@ public class StreamInitiation extends IQ { return isRanged; } + @Override public String getElementName() { return "file"; } + @Override public String getNamespace() { return "http://jabber.org/protocol/si/profile/file-transfer"; } + @Override public String toXML() { StringBuilder buffer = new StringBuilder(); @@ -370,7 +373,7 @@ public class StreamInitiation extends IQ { * @author Alexander Wenckus * */ - public class Feature implements ExtensionElement { + public static class Feature implements ExtensionElement { private final DataForm data; @@ -392,21 +395,24 @@ public class StreamInitiation extends IQ { return data; } + @Override public String getNamespace() { return "http://jabber.org/protocol/feature-neg"; } + @Override public String getElementName() { return "feature"; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf .append(""); - buf.append(data.toXML()); - buf.append(""); - return buf.toString(); - } - } + buf.append(data.toXML()); + buf.append(""); + return buf.toString(); + } + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/si/provider/StreamInitiationProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/si/provider/StreamInitiationProvider.java index 8563ebe0e..f19b458f3 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/si/provider/StreamInitiationProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/si/provider/StreamInitiationProvider.java @@ -41,51 +41,51 @@ public class StreamInitiationProvider extends IQProvider { @Override public StreamInitiation parse(XmlPullParser parser, int initialDepth) throws Exception { - boolean done = false; + boolean done = false; - // si - String id = parser.getAttributeValue("", "id"); - String mimeType = parser.getAttributeValue("", "mime-type"); + // si + String id = parser.getAttributeValue("", "id"); + String mimeType = parser.getAttributeValue("", "mime-type"); - StreamInitiation initiation = new StreamInitiation(); + StreamInitiation initiation = new StreamInitiation(); - // file - String name = null; - String size = null; - String hash = null; - String date = null; - String desc = null; - boolean isRanged = false; + // file + String name = null; + String size = null; + String hash = null; + String date = null; + String desc = null; + boolean isRanged = false; - // feature - DataForm form = null; - DataFormProvider dataFormProvider = new DataFormProvider(); + // feature + DataForm form = null; + DataFormProvider dataFormProvider = new DataFormProvider(); - int eventType; - String elementName; - String namespace; - while (!done) { - eventType = parser.next(); - elementName = parser.getName(); - namespace = parser.getNamespace(); - if (eventType == XmlPullParser.START_TAG) { - if (elementName.equals("file")) { - name = parser.getAttributeValue("", "name"); - size = parser.getAttributeValue("", "size"); - hash = parser.getAttributeValue("", "hash"); - date = parser.getAttributeValue("", "date"); - } else if (elementName.equals("desc")) { - desc = parser.nextText(); - } else if (elementName.equals("range")) { - isRanged = true; - } else if (elementName.equals("x") - && namespace.equals("jabber:x:data")) { - form = dataFormProvider.parse(parser); - } - } else if (eventType == XmlPullParser.END_TAG) { - if (elementName.equals("si")) { - done = true; - } else if (elementName.equals("file")) { + int eventType; + String elementName; + String namespace; + while (!done) { + eventType = parser.next(); + elementName = parser.getName(); + namespace = parser.getNamespace(); + if (eventType == XmlPullParser.START_TAG) { + if (elementName.equals("file")) { + name = parser.getAttributeValue("", "name"); + size = parser.getAttributeValue("", "size"); + hash = parser.getAttributeValue("", "hash"); + date = parser.getAttributeValue("", "date"); + } else if (elementName.equals("desc")) { + desc = parser.nextText(); + } else if (elementName.equals("range")) { + isRanged = true; + } else if (elementName.equals("x") + && namespace.equals("jabber:x:data")) { + form = dataFormProvider.parse(parser); + } + } else if (eventType == XmlPullParser.END_TAG) { + if (elementName.equals("si")) { + done = true; + } else if (elementName.equals("file")) { long fileSize = 0; if(size != null && size.trim().length() !=0){ try { @@ -106,21 +106,21 @@ public class StreamInitiationProvider extends IQProvider { } File file = new File(name, fileSize); - file.setHash(hash); - file.setDate(fileDate); - file.setDesc(desc); - file.setRanged(isRanged); - initiation.setFile(file); - } - } - } + file.setHash(hash); + file.setDate(fileDate); + file.setDesc(desc); + file.setRanged(isRanged); + initiation.setFile(file); + } + } + } - initiation.setSessionID(id); - initiation.setMimeType(mimeType); + initiation.setSessionID(id); + initiation.setMimeType(mimeType); - initiation.setFeatureNegotiationForm(form); + initiation.setFeatureNegotiationForm(form); - return initiation; - } + return initiation; + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/time/EntityTimeManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/time/EntityTimeManager.java index 3e2a08632..d075871fe 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/time/EntityTimeManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/time/EntityTimeManager.java @@ -43,6 +43,7 @@ public final class EntityTimeManager extends Manager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { getInstanceFor(connection); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java index 433b5ea4c..fd9a9e7a3 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java @@ -728,6 +728,7 @@ public class VCard extends IQ { // Used in tests: + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -776,6 +777,7 @@ public class VCard extends IQ { return workPhones.equals(vCard.workPhones); } + @Override public int hashCode() { int result; result = homePhones.hashCode(); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/FormField.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/FormField.java index 11c6a939e..0a024c7d7 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/FormField.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/FormField.java @@ -364,6 +364,7 @@ public class FormField implements NamedElement { return ELEMENT; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(this); // Add attributes @@ -455,6 +456,7 @@ public class FormField implements NamedElement { return ELEMENT; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); // Add attribute diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java index b68d57ab7..c2581db74 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java @@ -171,10 +171,12 @@ public class DataForm implements ExtensionElement { } } + @Override public String getElementName() { return ELEMENT; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayout.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayout.java index a499b89e7..593ba4a95 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayout.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayout.java @@ -124,6 +124,7 @@ public class DataLayout implements ExtensionElement { this.var = var; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(this); buf.attribute("var", getVar()); @@ -181,6 +182,7 @@ public class DataLayout implements ExtensionElement { return this.sectionLayout; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(this); buf.optAttribute("label", getLabel()); @@ -211,6 +213,7 @@ public class DataLayout implements ExtensionElement { public static final String ELEMENT = "reportedref"; + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(this); buf.closeEmptyElement(); @@ -236,6 +239,7 @@ public class DataLayout implements ExtensionElement { this.text = text; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(); buf.element(ELEMENT, getText()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatavalidation/packet/ValidateElement.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatavalidation/packet/ValidateElement.java index 4aeb61b30..28777f426 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatavalidation/packet/ValidateElement.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdatavalidation/packet/ValidateElement.java @@ -144,6 +144,7 @@ public abstract class ValidateElement implements ExtensionElement { buf.emptyElement(METHOD); } + @Override public void checkConsistency(FormField formField) { checkListRangeConsistency(formField); if (formField.getType() != null) { @@ -186,6 +187,7 @@ public abstract class ValidateElement implements ExtensionElement { buf.emptyElement(METHOD); } + @Override public void checkConsistency(FormField formField) { checkListRangeConsistency(formField); if (formField.getType() != null) { @@ -253,6 +255,7 @@ public abstract class ValidateElement implements ExtensionElement { return max; } + @Override public void checkConsistency(FormField formField) { checkNonMultiConsistency(formField, METHOD); if (getDatatype().equals(ValidateElement.DATATYPE_XS_STRING)) { @@ -302,6 +305,7 @@ public abstract class ValidateElement implements ExtensionElement { buf.element("regex", getRegex()); } + @Override public void checkConsistency(FormField formField) { checkNonMultiConsistency(formField, METHOD); } @@ -340,6 +344,7 @@ public abstract class ValidateElement implements ExtensionElement { this.max = max; } + @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(this); buf.optLongAttribute("min", getMin()); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLManager.java index 10c96c936..0dd8cf8bf 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLManager.java @@ -40,6 +40,7 @@ import java.util.List; public class XHTMLManager { static { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { // Enable the XHTML support on every established connection XHTMLManager.setServiceEnabled(connection, true); diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLText.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLText.java index e72099f31..cd4f47f6c 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLText.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/XHTMLText.java @@ -400,6 +400,7 @@ public class XHTMLText { * * @return the text of the XHTMLText */ + @Override public String toString() { return text.toString(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/packet/XHTMLExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/packet/XHTMLExtension.java index 858e32650..f5b9227e9 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/packet/XHTMLExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/packet/XHTMLExtension.java @@ -48,6 +48,7 @@ public class XHTMLExtension implements ExtensionElement { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return ELEMENT; } @@ -58,6 +59,7 @@ public class XHTMLExtension implements ExtensionElement { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-extensions/src/main/resources/org.jivesoftware.smack.extensions/extensions.providers b/smack-extensions/src/main/resources/org.jivesoftware.smack.extensions/extensions.providers index 15247d647..41705f0ca 100644 --- a/smack-extensions/src/main/resources/org.jivesoftware.smack.extensions/extensions.providers +++ b/smack-extensions/src/main/resources/org.jivesoftware.smack.extensions/extensions.providers @@ -16,35 +16,35 @@ org.jivesoftware.smackx.time.provider.TimeProvider - + active http://jabber.org/protocol/chatstates - org.jivesoftware.smackx.chatstates.packet.ChatStateExtension$Provider + org.jivesoftware.smackx.chatstates.provider.ChatStateExtensionProvider composing http://jabber.org/protocol/chatstates - org.jivesoftware.smackx.chatstates.packet.ChatStateExtension$Provider + org.jivesoftware.smackx.chatstates.provider.ChatStateExtensionProvider paused http://jabber.org/protocol/chatstates - org.jivesoftware.smackx.chatstates.packet.ChatStateExtension$Provider + org.jivesoftware.smackx.chatstates.provider.ChatStateExtensionProvider inactive http://jabber.org/protocol/chatstates - org.jivesoftware.smackx.chatstates.packet.ChatStateExtension$Provider + org.jivesoftware.smackx.chatstates.provider.ChatStateExtensionProvider gone http://jabber.org/protocol/chatstates - org.jivesoftware.smackx.chatstates.packet.ChatStateExtension$Provider + org.jivesoftware.smackx.chatstates.provider.ChatStateExtensionProvider diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/blocking/UnblockContactsIQTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/blocking/UnblockContactsIQTest.java index 3d4f8a943..4145e60fa 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/blocking/UnblockContactsIQTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/blocking/UnblockContactsIQTest.java @@ -36,7 +36,7 @@ public class UnblockContactsIQTest { + "" + "" + "" + "" + "
"; - String unblockAllIQExample = "" + "" + String unblockAllIQExample = "" + "" + ""; String unblockAllPushIQExample = "" diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bob/BoBIQTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bob/BoBIQTest.java index dab9c9e81..3308c6f73 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bob/BoBIQTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bob/BoBIQTest.java @@ -19,6 +19,7 @@ package org.jivesoftware.smackx.bob; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.test.util.SmackTestSuite; import org.jivesoftware.smack.util.PacketParserUtils; +import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.bob.element.BoBIQ; import org.junit.Assert; import org.junit.Test; @@ -50,7 +51,7 @@ public class BoBIQTest extends SmackTestSuite { BoBIQ bobIQ = PacketParserUtils.parseStanza(sampleBoBIQResponse); BoBHash bobHash = new BoBHash("8f35fef110ffc5df08d579a50083ff9308fb6242", "sha1"); - BoBData bobData = new BoBData("image/png", "sarasade2354j2".getBytes(), 86400); + BoBData bobData = new BoBData("image/png", "sarasade2354j2".getBytes(StringUtils.UTF8), 86400); BoBIQ createdBoBIQ = new BoBIQ(bobHash, bobData); createdBoBIQ.setStanzaId("sarasa"); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManagerTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManagerTest.java index 185842226..de7ab078f 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManagerTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamManagerTest.java @@ -164,6 +164,7 @@ public class InBandBytestreamManagerTest extends InitExtensions { protocol.addResponse(null, new Verification() { + @Override public void verify(Open request, IQ response) { assertEquals(StanzaType.MESSAGE, request.getStanza()); } diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionMessageTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionMessageTest.java index 0ebc90ab0..22c416a1b 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionMessageTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionMessageTest.java @@ -102,6 +102,7 @@ public class InBandBytestreamSessionMessageTest extends InitExtensions { long lastSeq = 0; + @Override public void verify(Message request, IQ response) { DataPacketExtension dpe = (DataPacketExtension) request.getExtension( DataPacketExtension.ELEMENT, DataPacketExtension.NAMESPACE); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionTest.java index 5aab18902..f399d2b9d 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/InBandBytestreamSessionTest.java @@ -103,6 +103,7 @@ public class InBandBytestreamSessionTest extends InitExtensions { long lastSeq = 0; + @Override public void verify(Data request, IQ response) { assertEquals(lastSeq++, request.getDataPacketExtension().getSeq()); } @@ -267,6 +268,7 @@ public class InBandBytestreamSessionTest extends InitExtensions { // compares the data of each packet with the control data Verification dataVerification = new Verification() { + @Override public void verify(Data request, IQ response) { byte[] decodedData = request.getDataPacketExtension().getDecodedData(); int seq = (int) request.getDataPacketExtension().getSeq(); @@ -372,6 +374,7 @@ public class InBandBytestreamSessionTest extends InitExtensions { // verify reply to invalid data packet is an error protocol.addResponse(null, Verification.requestTypeERROR, new Verification() { + @Override public void verify(IQ request, IQ response) { assertEquals(XMPPError.Condition.unexpected_request, request.getError().getCondition()); @@ -410,6 +413,7 @@ public class InBandBytestreamSessionTest extends InitExtensions { // verify reply to invalid data packet is an error protocol.addResponse(null, Verification.requestTypeERROR, new Verification() { + @Override public void verify(IQ request, IQ response) { assertEquals(XMPPError.Condition.bad_request, request.getError().getCondition()); @@ -639,6 +643,7 @@ public class InBandBytestreamSessionTest extends InitExtensions { Thread closer = new Thread(new Runnable() { + @Override public void run() { try { Thread.sleep(200); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtensionTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtensionTest.java index 435609026..5409333b3 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtensionTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/ibb/packet/DataPacketExtensionTest.java @@ -20,8 +20,10 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import java.io.UnsupportedEncodingException; import java.util.Properties; +import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.InitExtensions; import org.junit.Test; @@ -68,13 +70,13 @@ public class DataPacketExtensionTest extends InitExtensions { } @Test - public void shouldReturnNullIfDataIsInvalid() { + public void shouldReturnNullIfDataIsInvalid() throws UnsupportedEncodingException { // pad character is not at end of data DataPacketExtension data = new DataPacketExtension("sessionID", 0, "BBBB=CCC"); assertNull(data.getDecodedData()); // invalid Base64 character - data = new DataPacketExtension("sessionID", 0, new String(new byte[] { 123 })); + data = new DataPacketExtension("sessionID", 0, new String(new byte[] { 123 }, StringUtils.UTF8)); assertNull(data.getDecodedData()); } diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ByteStreamManagerTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ByteStreamManagerTest.java index 118e22f2a..65976c575 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ByteStreamManagerTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ByteStreamManagerTest.java @@ -604,6 +604,7 @@ public class Socks5ByteStreamManagerTest { // return used stream host info as response to the bytestream initiation protocol.addResponse(streamHostUsedPacket, new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { // verify SOCKS5 Bytestream request assertEquals(response.getSessionID(), request.getSessionID()); @@ -698,6 +699,7 @@ public class Socks5ByteStreamManagerTest { // return used stream host info as response to the bytestream initiation protocol.addResponse(streamHostUsedPacket, new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { assertEquals(response.getSessionID(), request.getSessionID()); assertEquals(1, request.getStreamHosts().size()); @@ -714,6 +716,7 @@ public class Socks5ByteStreamManagerTest { // return proxy activation response if proxy should be activated protocol.addResponse(activationResponse, new Verification() { + @Override public void verify(Bytestream request, IQ response) { assertEquals(targetJID, request.getToActivate().getTarget()); } @@ -796,6 +799,7 @@ public class Socks5ByteStreamManagerTest { // return used stream host info as response to the bytestream initiation protocol.addResponse(streamHostUsedPacket, new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { assertEquals(response.getSessionID(), request.getSessionID()); StreamHost streamHost1 = request.getStreamHosts().get(0); @@ -862,6 +866,7 @@ public class Socks5ByteStreamManagerTest { Verification streamHostUsedVerification1 = new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { assertEquals(response.getSessionID(), request.getSessionID()); assertEquals(2, request.getStreamHosts().size()); @@ -898,6 +903,7 @@ public class Socks5ByteStreamManagerTest { Verification streamHostUsedVerification2 = new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { assertEquals(response.getSessionID(), request.getSessionID()); assertEquals(2, request.getStreamHosts().size()); @@ -946,6 +952,7 @@ public class Socks5ByteStreamManagerTest { Verification streamHostUsedVerification = new Verification() { + @Override public void verify(Bytestream request, Bytestream response) { assertEquals(response.getSessionID(), request.getSessionID()); assertEquals(2, request.getStreamHosts().size()); @@ -1079,6 +1086,7 @@ public class Socks5ByteStreamManagerTest { // return proxy activation response if proxy should be activated protocol.addResponse(activationResponse, new Verification() { + @Override public void verify(Bytestream request, IQ response) { assertEquals(targetJID, request.getToActivate().getTarget()); } diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiatorTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiatorTest.java index 7616597eb..7a7bab2f2 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiatorTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientForInitiatorTest.java @@ -254,6 +254,7 @@ public class Socks5ClientForInitiatorTest { protocol.addResponse(activationResponse, Verification.correspondingSenderReceiver, Verification.requestTypeSET, new Verification() { + @Override public void verify(Bytestream request, IQ response) { // verify that the correct stream should be activated assertNotNull(request.getToActivate()); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientTest.java index aab52d2a7..e658020fd 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ClientTest.java @@ -29,6 +29,7 @@ import java.net.Socket; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.util.NetworkUtil; +import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost; import org.junit.After; import org.junit.Before; @@ -236,7 +237,7 @@ public class Socks5ClientTest { // reply with full SOCKS5 message with an error code (01 = general SOCKS server // failure) out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00, (byte) 0x03 }); - byte[] address = digest.getBytes(); + byte[] address = digest.getBytes(StringUtils.UTF8); out.write(address.length); out.write(address); out.write(new byte[] { (byte) 0x00, (byte) 0x00 }); @@ -295,7 +296,7 @@ public class Socks5ClientTest { out.write(new byte[] { (byte) 0x05, (byte) 0x00 }); out.flush(); - byte[] address = digest.getBytes(); + byte[] address = digest.getBytes(StringUtils.UTF8); assertEquals((byte) 0x05, (byte) in.read()); // version assertEquals((byte) 0x01, (byte) in.read()); // connect request diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ProxyTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ProxyTest.java index f909bebe8..b2d3da710 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ProxyTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5ProxyTest.java @@ -32,6 +32,7 @@ import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; +import org.jivesoftware.smack.util.StringUtils; import org.junit.After; import org.junit.Test; @@ -272,7 +273,7 @@ public class Socks5ProxyTest { proxy.start(); assertTrue(proxy.isRunning()); - String digest = new String(new byte[] { (byte) 0xAA }); + String digest = new String(new byte[] { (byte) 0xAA }, StringUtils.UTF8); // add digest to allow connection proxy.addTransfer(digest); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5TestProxy.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5TestProxy.java index 64d696f9b..d3b60e2a3 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5TestProxy.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5TestProxy.java @@ -30,6 +30,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.SmackException; +import org.jivesoftware.smack.util.StringUtils; /** * Simple SOCKS5 proxy for testing purposes. It is almost the same as the Socks5Proxy class but the @@ -206,6 +207,7 @@ public final class Socks5TestProxy { */ class Socks5ServerProcess implements Runnable { + @Override public void run() { while (true) { Socket socket = null; @@ -295,7 +297,7 @@ public final class Socks5TestProxy { byte[] connectionRequest = Socks5Utils.receiveSocks5Message(in); // extract digest - String responseDigest = new String(connectionRequest, 5, connectionRequest[4]); + String responseDigest = new String(connectionRequest, 5, connectionRequest[4], StringUtils.UTF8); connectionRequest[1] = (byte) 0x00; // set return status to 0 (success) out.write(connectionRequest); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ConfigureFormTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ConfigureFormTest.java index a3686b1a8..1197aaa7b 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ConfigureFormTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ConfigureFormTest.java @@ -41,56 +41,56 @@ import org.junit.Test; */ public class ConfigureFormTest { - @Test - public void checkChildrenAssocPolicy() - { - ConfigureForm form = new ConfigureForm(DataForm.Type.submit); - form.setChildrenAssociationPolicy(ChildrenAssociationPolicy.owners); - assertEquals(ChildrenAssociationPolicy.owners, form.getChildrenAssociationPolicy()); - } + @Test + public void checkChildrenAssocPolicy() + { + ConfigureForm form = new ConfigureForm(DataForm.Type.submit); + form.setChildrenAssociationPolicy(ChildrenAssociationPolicy.owners); + assertEquals(ChildrenAssociationPolicy.owners, form.getChildrenAssociationPolicy()); + } - @Test - public void getConfigFormWithInsufficientPriviliges() throws XMPPException, SmackException, IOException, InterruptedException - { - ThreadedDummyConnection con = ThreadedDummyConnection.newInstance(); - PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); - DiscoverInfo info = new DiscoverInfo(); - Identity ident = new Identity("pubsub", null, "leaf"); - info.addIdentity(ident); - con.addIQReply(info); + @Test + public void getConfigFormWithInsufficientPriviliges() throws XMPPException, SmackException, IOException, InterruptedException + { + ThreadedDummyConnection con = ThreadedDummyConnection.newInstance(); + PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); + DiscoverInfo info = new DiscoverInfo(); + Identity ident = new Identity("pubsub", null, "leaf"); + info.addIdentity(ident); + con.addIQReply(info); - Node node = mgr.getNode("princely_musings"); + Node node = mgr.getNode("princely_musings"); - PubSub errorIq = new PubSub(); - XMPPError.Builder error = XMPPError.getBuilder(Condition.forbidden); - errorIq.setError(error); - con.addIQReply(errorIq); + PubSub errorIq = new PubSub(); + XMPPError.Builder error = XMPPError.getBuilder(Condition.forbidden); + errorIq.setError(error); + con.addIQReply(errorIq); - try - { - node.getNodeConfiguration(); - } - catch (XMPPErrorException e) - { - Assert.assertEquals(XMPPError.Type.AUTH, e.getXMPPError().getType()); - } - } + try + { + node.getNodeConfiguration(); + } + catch (XMPPErrorException e) + { + Assert.assertEquals(XMPPError.Type.AUTH, e.getXMPPError().getType()); + } + } - @Test (expected=SmackException.class) - public void getConfigFormWithTimeout() throws XMPPException, SmackException, InterruptedException - { - ThreadedDummyConnection con = new ThreadedDummyConnection(); - PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); - DiscoverInfo info = new DiscoverInfo(); - Identity ident = new Identity("pubsub", null, "leaf"); - info.addIdentity(ident); - con.addIQReply(info); + @Test (expected=SmackException.class) + public void getConfigFormWithTimeout() throws XMPPException, SmackException, InterruptedException + { + ThreadedDummyConnection con = new ThreadedDummyConnection(); + PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); + DiscoverInfo info = new DiscoverInfo(); + Identity ident = new Identity("pubsub", null, "leaf"); + info.addIdentity(ident); + con.addIQReply(info); - Node node = mgr.getNode("princely_musings"); + Node node = mgr.getNode("princely_musings"); - SmackConfiguration.setDefaultReplyTimeout(100); - con.setTimeout(); + SmackConfiguration.setDefaultReplyTimeout(100); + con.setTimeout(); - node.getNodeConfiguration(); - } + node.getNodeConfiguration(); + } } diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ItemValidationTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ItemValidationTest.java index c870f139d..2ef6cb4b0 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ItemValidationTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/pubsub/ItemValidationTest.java @@ -37,63 +37,63 @@ import org.xmlpull.v1.XmlPullParser; * */ public class ItemValidationTest extends InitExtensions { - private ThreadedDummyConnection connection; + private ThreadedDummyConnection connection; - @Before - public void setUp() throws Exception - { - // Uncomment this to enable debug output - // SmackConfiguration.DEBUG = true; + @Before + public void setUp() throws Exception + { + // Uncomment this to enable debug output + // SmackConfiguration.DEBUG = true; - connection = new ThreadedDummyConnection(); - connection.connect(); - connection.login(); - } + connection = new ThreadedDummyConnection(); + connection.connect(); + connection.login(); + } - @After - public void tearDown() throws Exception - { - if (connection != null) - connection.disconnect(); - } + @After + public void tearDown() throws Exception + { + if (connection != null) + connection.disconnect(); + } - @Test - public void verifyBasicItem() throws Exception - { - Item simpleItem = new Item(); - String simpleCtrl = ""; - assertXMLEqual(simpleCtrl, simpleItem.toXML()); + @Test + public void verifyBasicItem() throws Exception + { + Item simpleItem = new Item(); + String simpleCtrl = ""; + assertXMLEqual(simpleCtrl, simpleItem.toXML()); - Item idItem = new Item("uniqueid"); - String idCtrl = ""; - assertXMLEqual(idCtrl, idItem.toXML()); + Item idItem = new Item("uniqueid"); + String idCtrl = ""; + assertXMLEqual(idCtrl, idItem.toXML()); - Item itemWithNodeId = new Item("testId", "testNode"); - String nodeIdCtrl = ""; - assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); - } + Item itemWithNodeId = new Item("testId", "testNode"); + String nodeIdCtrl = ""; + assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); + } - @Test - public void verifyPayloadItem() throws Exception - { - SimplePayload payload = new SimplePayload(null, null, "This is the payload"); + @Test + public void verifyPayloadItem() throws Exception + { + SimplePayload payload = new SimplePayload(null, null, "This is the payload"); - PayloadItem simpleItem = new PayloadItem(payload); - String simpleCtrl = "" + payload.toXML() + ""; - assertXMLEqual(simpleCtrl, simpleItem.toXML()); + PayloadItem simpleItem = new PayloadItem(payload); + String simpleCtrl = "" + payload.toXML() + ""; + assertXMLEqual(simpleCtrl, simpleItem.toXML()); - PayloadItem idItem = new PayloadItem("uniqueid", payload); - String idCtrl = "" + payload.toXML() + ""; - assertXMLEqual(idCtrl, idItem.toXML()); + PayloadItem idItem = new PayloadItem("uniqueid", payload); + String idCtrl = "" + payload.toXML() + ""; + assertXMLEqual(idCtrl, idItem.toXML()); - PayloadItem itemWithNodeId = new PayloadItem("testId", "testNode", payload); - String nodeIdCtrl = "" + payload.toXML() + ""; - assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); - } + PayloadItem itemWithNodeId = new PayloadItem("testId", "testNode", payload); + String nodeIdCtrl = "" + payload.toXML() + ""; + assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); + } - @Test - public void parseBasicItem() throws Exception - { + @Test + public void parseBasicItem() throws Exception + { XmlPullParser parser = PacketParserUtils.getParserFor( "" + "" + @@ -116,7 +116,7 @@ public class ItemValidationTest extends InitExtensions { ExtensionElement itemExt = ((ItemsExtension)event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof Item); assertEquals("testid1", ((Item)itemExt).getId()); - } + } @Test public void parseSimplePayloadItem() throws Exception diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/receipts/DeliveryReceiptTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/receipts/DeliveryReceiptTest.java index 5cf88e6d4..a2f128125 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/receipts/DeliveryReceiptTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/receipts/DeliveryReceiptTest.java @@ -119,7 +119,7 @@ public class DeliveryReceiptTest extends InitExtensions { c.processStanza(m); Stanza reply = c.getSentPacket(); - DeliveryReceipt r = DeliveryReceipt.from((Message) reply); + DeliveryReceipt r = DeliveryReceipt.from((Message) reply); assertThat("romeo@montague.com", equalsCharSequence(reply.getTo())); assertEquals("test-receipt-request", r.getId()); } diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatavalidation/provider/DataValidationTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatavalidation/provider/DataValidationTest.java index 915cbd650..c29dc8dbc 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatavalidation/provider/DataValidationTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatavalidation/provider/DataValidationTest.java @@ -88,7 +88,7 @@ public class DataValidationTest { assertEquals("min-val", rdv.getMin()); assertEquals("max-val", rdv.getMax()); assertNotNull(rdv.getListRange()); - assertEquals(new Long(111), rdv.getListRange().getMin()); + assertEquals(Long.valueOf(111), rdv.getListRange().getMin()); assertEquals(999, rdv.getListRange().getMax().intValue()); diff --git a/smack-extensions/src/test/java/org/jivesoftware/util/ConnectionUtils.java b/smack-extensions/src/test/java/org/jivesoftware/util/ConnectionUtils.java index 22625e306..b895e800c 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/util/ConnectionUtils.java +++ b/smack-extensions/src/test/java/org/jivesoftware/util/ConnectionUtils.java @@ -92,6 +92,7 @@ public class ConnectionUtils { // mock send method Answer addIncoming = new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { protocol.getRequests().add((Stanza) invocation.getArguments()[0]); return null; @@ -101,6 +102,7 @@ public class ConnectionUtils { // mock receive methods Answer answer = new Answer() { + @Override public Stanza answer(InvocationOnMock invocation) throws Throwable { return protocol.getResponses().poll(); } diff --git a/smack-extensions/src/test/java/org/jivesoftware/util/Verification.java b/smack-extensions/src/test/java/org/jivesoftware/util/Verification.java index 06edde76c..42593a8b2 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/util/Verification.java +++ b/smack-extensions/src/test/java/org/jivesoftware/util/Verification.java @@ -39,6 +39,7 @@ public interface Verification { */ public static Verification correspondingSenderReceiver = new Verification() { + @Override public void verify(Stanza request, Stanza response) { assertEquals(response.getFrom(), request.getTo()); } @@ -50,6 +51,7 @@ public interface Verification { */ public static Verification requestTypeGET = new Verification() { + @Override public void verify(IQ request, Stanza response) { assertEquals(IQ.Type.get, request.getType()); } @@ -61,6 +63,7 @@ public interface Verification { */ public static Verification requestTypeSET = new Verification() { + @Override public void verify(IQ request, Stanza response) { assertEquals(IQ.Type.set, request.getType()); } @@ -72,6 +75,7 @@ public interface Verification { */ public static Verification requestTypeRESULT = new Verification() { + @Override public void verify(IQ request, Stanza response) { assertEquals(IQ.Type.result, request.getType()); } @@ -83,6 +87,7 @@ public interface Verification { */ public static Verification requestTypeERROR = new Verification() { + @Override public void verify(IQ request, Stanza response) { assertEquals(IQ.Type.error, request.getType()); } diff --git a/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java b/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java index 5c59136e9..897c06423 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java @@ -151,6 +151,7 @@ public final class ChatManager extends Manager{ // Add a listener for all message packets so that we can deliver // messages to the best Chat instance available. connection.addSyncStanzaListener(new StanzaListener() { + @Override public void processStanza(Stanza packet) { Message message = (Message) packet; Chat chat; diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/Roster.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/Roster.java index 71d01fa42..e7e6dbce2 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/Roster.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/Roster.java @@ -46,9 +46,11 @@ import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.SmackException.NotLoggedInException; import org.jivesoftware.smack.XMPPConnectionRegistry; import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.PresenceTypeFilter; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.filter.StanzaTypeFilter; +import org.jivesoftware.smack.filter.ToMatchesFilter; import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ.Type; @@ -124,6 +126,8 @@ public final class Roster extends Manager { private static final StanzaFilter PRESENCE_PACKET_FILTER = StanzaTypeFilter.PRESENCE; + private static final StanzaFilter OUTGOING_USER_UNAVAILABLE_PRESENCE = new AndFilter(PresenceTypeFilter.UNAVAILABLE, ToMatchesFilter.MATCH_NO_TO_SET); + private static boolean rosterLoadedAtLoginDefault = true; /** @@ -326,7 +330,7 @@ public final class Roster extends Manager { // state). setOfflinePresences(); } - }, PresenceTypeFilter.UNAVAILABLE); + }, OUTGOING_USER_UNAVAILABLE_PRESENCE); // If the connection is already established, call reload if (connection.isAuthenticated()) { @@ -1564,7 +1568,7 @@ public final class Roster extends Manager { @Override public void processStanza(Stanza packet) { final XMPPConnection connection = connection(); - LOGGER.fine("RosterResultListener received stanza"); + LOGGER.log(Level.FINE, "RosterResultListener received {}", packet); Collection addedEntries = new ArrayList<>(); Collection updatedEntries = new ArrayList<>(); Collection deletedEntries = new ArrayList<>(); diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntries.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntries.java index 18f114df7..267277009 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntries.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntries.java @@ -20,6 +20,6 @@ import java.util.Collection; public interface RosterEntries { - public void rosterEntries(Collection rosterEntries); + public void rosterEntries(Collection rosterEntries); } diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntry.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntry.java index e3d237339..edac93801 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntry.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/RosterEntry.java @@ -222,6 +222,7 @@ public final class RosterEntry extends Manager { connection().sendStanza(unsubscribed); } + @Override public String toString() { StringBuilder buf = new StringBuilder(); if (getName() != null) { @@ -249,6 +250,7 @@ public final class RosterEntry extends Manager { return getJid().hashCode(); } + @Override public boolean equals(Object object) { if (this == object) { return true; diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/packet/RosterPacket.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/packet/RosterPacket.java index 0dc36c41f..9d9ed1a3d 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/packet/RosterPacket.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/packet/RosterPacket.java @@ -270,6 +270,7 @@ public class RosterPacket extends IQ { groupNames.remove(groupName); } + @Override public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); xml.attribute("jid", jid); diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/rosterstore/DirectoryRosterStore.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/rosterstore/DirectoryRosterStore.java index 816d87890..7d63dafa3 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/rosterstore/DirectoryRosterStore.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/rosterstore/DirectoryRosterStore.java @@ -185,9 +185,11 @@ public final class DirectoryRosterStore implements RosterStore { resetEntries(Collections.emptyList(), ""); } + @SuppressWarnings("DefaultCharset") private static Item readEntry(File file) { Reader reader; try { + // TODO: Should use Files.newBufferedReader() but it is not available on Android. reader = new FileReader(file); } catch (FileNotFoundException e) { LOGGER.log(Level.FINE, "Roster entry file not found", e); diff --git a/smack-im/src/test/java/org/jivesoftware/smack/chat/ChatConnectionTest.java b/smack-im/src/test/java/org/jivesoftware/smack/chat/ChatConnectionTest.java index 1c4d8a950..fcae16b0b 100644 --- a/smack-im/src/test/java/org/jivesoftware/smack/chat/ChatConnectionTest.java +++ b/smack-im/src/test/java/org/jivesoftware/smack/chat/ChatConnectionTest.java @@ -34,7 +34,7 @@ import org.junit.Test; import org.jxmpp.jid.Jid; import org.jxmpp.jid.JidTestUtil; -@SuppressWarnings("deprecation") +@SuppressWarnings({"deprecation", "ReferenceEquality"}) public class ChatConnectionTest { private DummyConnection dc; @@ -347,7 +347,7 @@ public class ChatConnectionTest { waitListener.waitAndReset(); } - class TestChatManagerListener extends WaitForPacketListener implements ChatManagerListener { + static class TestChatManagerListener extends WaitForPacketListener implements ChatManagerListener { private Chat newChat; private ChatMessageListener listener; @@ -372,7 +372,7 @@ public class ChatConnectionTest { } } - private class TestChatServer extends Thread { + private static class TestChatServer extends Thread { private Stanza chatPacket; private DummyConnection con; diff --git a/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterTest.java b/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterTest.java index 10ffd1c3d..fe3e87c8b 100644 --- a/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterTest.java +++ b/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterTest.java @@ -145,6 +145,7 @@ public class RosterTest extends InitSmackIm { // Adding the new roster item final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() { + @Override void verifyUpdateRequest(final RosterPacket updateRequest) { final Item item = updateRequest.getRosterItems().iterator().next(); assertEquals("The provided JID doesn't match the requested!", @@ -216,6 +217,7 @@ public class RosterTest extends InitSmackIm { // Updating the roster item final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() { + @Override void verifyUpdateRequest(final RosterPacket updateRequest) { final Item item = updateRequest.getRosterItems().iterator().next(); assertEquals("The provided JID doesn't match the requested!", @@ -289,6 +291,7 @@ public class RosterTest extends InitSmackIm { // Delete a roster item final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() { + @Override void verifyUpdateRequest(final RosterPacket updateRequest) { final Item item = updateRequest.getRosterItems().iterator().next(); assertEquals("The provided JID doesn't match the requested!", @@ -410,6 +413,7 @@ public class RosterTest extends InitSmackIm { // Adding the new roster item final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() { + @Override void verifyUpdateRequest(final RosterPacket updateRequest) { final Item item = updateRequest.getRosterItems().iterator().next(); assertSame("The provided JID doesn't match the requested!", @@ -656,6 +660,7 @@ public class RosterTest extends InitSmackIm { */ abstract void verifyUpdateRequest(final RosterPacket updateRequest); + @Override public void run() { try { while (true) { @@ -712,21 +717,25 @@ public class RosterTest extends InitSmackIm { private final List addressesDeleted = new CopyOnWriteArrayList<>(); private final List addressesUpdated = new CopyOnWriteArrayList<>(); + @Override public synchronized void entriesAdded(Collection addresses) { addressesAdded.addAll(addresses); reportInvoked(); } + @Override public synchronized void entriesDeleted(Collection addresses) { addressesDeleted.addAll(addresses); reportInvoked(); } + @Override public synchronized void entriesUpdated(Collection addresses) { addressesUpdated.addAll(addresses); reportInvoked(); } + @Override public void presenceChanged(Presence presence) { reportInvoked(); } @@ -794,6 +803,7 @@ public class RosterTest extends InitSmackIm { /** * Reset the lists of added, deleted or updated items. */ + @Override public synchronized void reset() { super.reset(); addressesAdded.clear(); diff --git a/smack-im/src/test/java/org/jivesoftware/smack/roster/SubscriptionPreApprovalTest.java b/smack-im/src/test/java/org/jivesoftware/smack/roster/SubscriptionPreApprovalTest.java index 634a7def8..176d42463 100644 --- a/smack-im/src/test/java/org/jivesoftware/smack/roster/SubscriptionPreApprovalTest.java +++ b/smack-im/src/test/java/org/jivesoftware/smack/roster/SubscriptionPreApprovalTest.java @@ -155,6 +155,7 @@ public class SubscriptionPreApprovalTest extends InitSmackIm { */ abstract void verifyPreApprovalRequest(final Presence preApproval); + @Override public void run() { try { while (true) { diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferIntegrationTest.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferIntegrationTest.java index 59d527230..dd54a6a84 100644 --- a/smack-integration-test/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferIntegrationTest.java +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferIntegrationTest.java @@ -20,6 +20,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; import java.util.Arrays; import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest; @@ -43,7 +44,16 @@ public class FileTransferIntegrationTest extends AbstractSmackIntegrationTest { ftManagerTwo = FileTransferManager.getInstanceFor(conTwo); } - private static final byte[] dataToSend = StringUtils.insecureRandomString(1024 * 4 * 5).getBytes(); + private static final byte[] dataToSend; + + static { + try { + dataToSend = StringUtils.insecureRandomString(1024 * 4 * 5).getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + } @SmackIntegrationTest public void fileTransferTest() throws Exception { diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/xdata/FormTest.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/xdata/FormTest.java index 3749b83e9..5abf686f0 100644 --- a/smack-integration-test/src/main/java/org/jivesoftware/smackx/xdata/FormTest.java +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/xdata/FormTest.java @@ -50,7 +50,7 @@ public class FormTest extends AbstractSmackIntegrationTest { * @throws NotConnectedException */ @SuppressWarnings("deprecation") - @SmackIntegrationTest + @SmackIntegrationTest public void testFilloutForm() throws NotConnectedException, InterruptedException { Form formToSend = new Form(DataForm.Type.form); formToSend.setInstructions( diff --git a/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Base64.java b/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Base64.java index f0744bbd1..c2e71e7d8 100644 --- a/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Base64.java +++ b/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Base64.java @@ -16,6 +16,7 @@ */ package org.jivesoftware.smack.util.stringencoder.java7; +import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; @@ -514,7 +515,7 @@ public final class Base64 } // end try catch (java.io.UnsupportedEncodingException uue) { - return new String( baos.toByteArray() ); + return new String( baos.toByteArray(), Charset.defaultCharset() ); } // end catch } // end encode @@ -642,7 +643,7 @@ public final class Base64 } // end try catch (java.io.UnsupportedEncodingException uue) { - return new String( baos.toByteArray() ); + return new String( baos.toByteArray(), Charset.defaultCharset() ); } // end catch } // end if: compress @@ -687,7 +688,7 @@ public final class Base64 } // end try catch (java.io.UnsupportedEncodingException uue) { - return new String( outBuff, 0, e ); + return new String( outBuff, 0, e , Charset.defaultCharset()); } // end catch } // end else: don't compress @@ -887,7 +888,7 @@ public final class Base64 } // end try catch( java.io.UnsupportedEncodingException uee ) { - bytes = s.getBytes(); + bytes = s.getBytes( Charset.defaultCharset() ); } // end catch // @@ -1289,6 +1290,7 @@ public final class Base64 * @return next byte * @since 1.3 */ + @Override public int read() throws java.io.IOException { // Do we need to get data? @@ -1417,6 +1419,7 @@ public final class Base64 * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ + @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; @@ -1530,6 +1533,7 @@ public final class Base64 * @param theByte the byte to write * @since 1.3 */ + @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? @@ -1591,6 +1595,7 @@ public final class Base64 * @param len max number of bytes to read into array * @since 1.3 */ + @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? @@ -1636,6 +1641,7 @@ public final class Base64 * * @since 1.3 */ + @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written diff --git a/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Java7Base64UrlSafeEncoder.java b/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Java7Base64UrlSafeEncoder.java index 3b9cfa451..0154511b9 100644 --- a/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Java7Base64UrlSafeEncoder.java +++ b/smack-java7/src/main/java/org/jivesoftware/smack/util/stringencoder/java7/Java7Base64UrlSafeEncoder.java @@ -16,6 +16,9 @@ */ package org.jivesoftware.smack.util.stringencoder.java7; +import java.io.UnsupportedEncodingException; + +import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.stringencoder.StringEncoder; @@ -44,12 +47,26 @@ public final class Java7Base64UrlSafeEncoder implements StringEncoder { return instance; } + @Override public String encode(String s) { - return Base64.encodeBytes(s.getBytes(), BASE64_ENCODER_FLAGS); + byte[] bytes; + try { + bytes = s.getBytes(StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + return Base64.encodeBytes(bytes, BASE64_ENCODER_FLAGS); } + @Override public String decode(String s) { - return new String(Base64.decode(s, BASE64_ENCODER_FLAGS)); + try { + return new String(Base64.decode(s, BASE64_ENCODER_FLAGS), StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/ContentNegotiator.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/ContentNegotiator.java index 48f596875..9278c31b2 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/ContentNegotiator.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/ContentNegotiator.java @@ -60,6 +60,7 @@ public class ContentNegotiator extends JingleNegotiator { transportNegotiators = new ArrayList(); } + @Override public List dispatchIncomingPacket(IQ iq, String id) throws XMPPException, SmackException, InterruptedException { List responses = new ArrayList(); @@ -139,6 +140,7 @@ public class ContentNegotiator extends JingleNegotiator { /** * Called from above when starting a new session. */ + @Override protected void doStart() { // JingleContent result = new JingleContent(creator, name); @@ -154,6 +156,7 @@ public class ContentNegotiator extends JingleNegotiator { /** * Prepare to close the media manager. */ + @Override public void close() { destroyMediaNegotiator(); destroyTransportNegotiator(); @@ -324,6 +327,7 @@ public class ContentNegotiator extends JingleNegotiator { * The negotiator state for the ContentNegotiators is a special case. * It is a roll-up of the sub-negotiator states. */ + @Override public JingleNegotiatorState getNegotiatorState() { JingleNegotiatorState result = JingleNegotiatorState.PENDING; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleActionEnum.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleActionEnum.java index 591ea6006..9c524a7c7 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleActionEnum.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleActionEnum.java @@ -36,7 +36,7 @@ public enum JingleActionEnum { SESSION_TERMINATE("session-terminate"), TRANSPORT_INFO("transport-info"); - private String actionCode; + private final String actionCode; private JingleActionEnum(String inActionCode) { actionCode = inActionCode; @@ -46,6 +46,7 @@ public enum JingleActionEnum { * Returns the String value for an Action. */ + @Override public String toString() { return actionCode; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleException.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleException.java index 6406ff7a4..48a08e678 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleException.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleException.java @@ -26,9 +26,9 @@ import org.jivesoftware.smackx.jingleold.packet.JingleError; * @author Alvaro Saurin */ public class JingleException extends XMPPException { - private static final long serialVersionUID = -1521230401958103382L; + private static final long serialVersionUID = -1521230401958103382L; - private final JingleError error; + private final JingleError error; /** * Default constructor. diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java index 74dbe6b01..b8f727251 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java @@ -186,9 +186,9 @@ import org.jxmpp.jid.Jid; @SuppressWarnings("SynchronizeOnNonFinalField") public class JingleManager implements JingleSessionListener { - private static final Logger LOGGER = Logger.getLogger(JingleManager.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleManager.class.getName()); - // non-static + // non-static final List jingleSessions = new ArrayList(); @@ -219,15 +219,19 @@ public class JingleManager implements JingleSessionListener { Roster.getInstanceFor(connection).addRosterListener(new RosterListener() { + @Override public void entriesAdded(Collection addresses) { } + @Override public void entriesUpdated(Collection addresses) { } + @Override public void entriesDeleted(Collection addresses) { } + @Override public void presenceChanged(Presence presence) { if (!presence.isAvailable()) { Jid xmppAddress = presence.getFrom(); @@ -264,6 +268,7 @@ public class JingleManager implements JingleSessionListener { // The ServiceDiscoveryManager class should have been already // initialized XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override public void connectionCreated(XMPPConnection connection) { JingleManager.setServiceEnabled(connection, true); } @@ -411,9 +416,11 @@ public class JingleManager implements JingleSessionListener { } } + @Override public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) { } + @Override public void sessionDeclined(String reason, JingleSession jingleSession) { jingleSession.removeListener(this); jingleSessions.remove(jingleSession); @@ -421,21 +428,25 @@ public class JingleManager implements JingleSessionListener { LOGGER.severe("Declined:" + reason); } + @Override public void sessionRedirected(String redirection, JingleSession jingleSession) { jingleSession.removeListener(this); jingleSessions.remove(jingleSession); } + @Override public void sessionClosed(String reason, JingleSession jingleSession) { jingleSession.removeListener(this); jingleSessions.remove(jingleSession); } + @Override public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) { jingleSession.removeListener(this); jingleSessions.remove(jingleSession); } + @Override public void sessionMediaReceived(JingleSession jingleSession, String participant) { // Do Nothing } @@ -447,6 +458,7 @@ public class JingleManager implements JingleSessionListener { private void initJingleSessionRequestListeners() { StanzaFilter initRequestFilter = new StanzaFilter() { // Return true if we accept this packet + @Override public boolean accept(Stanza pin) { if (pin instanceof IQ) { IQ iq = (IQ) pin; @@ -467,6 +479,7 @@ public class JingleManager implements JingleSessionListener { // Start a packet listener for session initiation requests connection.addAsyncStanzaListener(new StanzaListener() { + @Override public void processStanza(Stanza packet) { triggerSessionRequested((Jingle) packet); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleNegotiator.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleNegotiator.java index 0cb75fd45..255d12cbc 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleNegotiator.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleNegotiator.java @@ -42,9 +42,9 @@ import org.jivesoftware.smackx.jingleold.listeners.JingleListener; */ public abstract class JingleNegotiator { - private static final Logger LOGGER = Logger.getLogger(JingleNegotiator.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleNegotiator.class.getName()); - //private XMPPConnection connection; // The connection associated + //private XMPPConnection connection; // The connection associated protected JingleSession session; @@ -238,12 +238,12 @@ public abstract class JingleNegotiator { // CHECKSTYLE:OFF public void start() { - isStarted = true; - doStart(); + isStarted = true; + doStart(); } public boolean isStarted() { - return isStarted; + return isStarted; } // CHECKSTYLE:ON diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSession.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSession.java index a26b5a98d..46ea8f969 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSession.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSession.java @@ -62,9 +62,9 @@ import org.jxmpp.jid.Jid; */ public class JingleSession extends JingleNegotiator implements MediaReceivedListener { - private static final Logger LOGGER = Logger.getLogger(JingleSession.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleSession.class.getName()); - // static + // static private static final HashMap sessions = new HashMap(); private static final Random randomGenerator = new Random(); @@ -158,6 +158,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList return initiator; } + @Override public XMPPConnection getConnection() { return connection; } @@ -299,13 +300,13 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList // Each content negotiator may pass back a list of JingleContent for addition to the response packet. // CHECKSTYLE:OFF for (ContentNegotiator contentNegotiator : contentNegotiators) { - // If at this point the content negotiator isn't started, it's because we sent a session-init jingle - // packet from startOutgoing() and we're waiting for the other side to let us know they're ready - // to take jingle packets. (This packet might be a session-terminate, but that will get handled - // later. - if (!contentNegotiator.isStarted()) { - contentNegotiator.start(); - } + // If at this point the content negotiator isn't started, it's because we sent a session-init jingle + // packet from startOutgoing() and we're waiting for the other side to let us know they're ready + // to take jingle packets. (This packet might be a session-terminate, but that will get handled + // later. + if (!contentNegotiator.isStarted()) { + contentNegotiator.start(); + } responses.addAll(contentNegotiator.dispatchIncomingPacket(iq, responseId)); } // CHECKSTYLE:ON @@ -350,6 +351,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList * @throws SmackException * @throws InterruptedException */ + @Override public List dispatchIncomingPacket(IQ iq, String id) throws XMPPException, SmackException, InterruptedException { List responses = new ArrayList(); IQ response = null; @@ -475,7 +477,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList // The the packet. // CHECKSTYLE:OFF if ((getConnection() != null) && (getConnection().isConnected())) - getConnection().sendStanza(jout); + getConnection().sendStanza(jout); // CHECKSTYLE:ON } return jout; @@ -534,6 +536,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList * * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return Jingle.getSessionHash(getSid(), getInitiator()); } @@ -543,6 +546,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList * * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -649,11 +653,11 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList private void removeConnectionListener() { // CHECKSTYLE:OFF - if (connectionListener != null) { - getConnection().removeConnectionListener(connectionListener); + if (connectionListener != null) { + getConnection().removeConnectionListener(connectionListener); - LOGGER.fine("JINGLE SESSION: REMOVE CONNECTION LISTENER"); - } + LOGGER.fine("JINGLE SESSION: REMOVE CONNECTION LISTENER"); + } // CHECKSTYLE:ON } @@ -678,6 +682,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList LOGGER.fine("UpdatePacketListener"); packetListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { try { receivePacketAndRespond((IQ) packet); @@ -688,6 +693,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList }; packetFilter = new StanzaFilter() { + @Override public boolean accept(Stanza packet) { if (packet instanceof IQ) { @@ -803,9 +809,11 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList public void setupListeners() { JingleMediaListener jingleMediaListener = new JingleMediaListener() { + @Override public void mediaClosed(PayloadType cand) { } + @Override public void mediaEstablished(PayloadType pt) throws NotConnectedException, InterruptedException { if (isFullyEstablished()) { Jingle jout = new Jingle(JingleActionEnum.SESSION_ACCEPT); @@ -827,13 +835,14 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList JingleTransportListener jingleTransportListener = new JingleTransportListener() { + @Override public void transportEstablished(TransportCandidate local, TransportCandidate remote) throws NotConnectedException, InterruptedException { if (isFullyEstablished()) { // CHECKSTYLE:OFF - // Indicate that this session is active. - setSessionState(JingleSessionStateActive.getInstance()); + // Indicate that this session is active. + setSessionState(JingleSessionStateActive.getInstance()); - for (ContentNegotiator contentNegotiator : contentNegotiators) { + for (ContentNegotiator contentNegotiator : contentNegotiators) { // CHECKSTYLE:ON if (contentNegotiator.getNegotiatorState() == JingleNegotiatorState.SUCCEEDED) contentNegotiator.triggerContentEstablished(); @@ -855,9 +864,11 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList } } + @Override public void transportClosed(TransportCandidate cand) { } + @Override public void transportClosedOnError(XMPPException e) { } }; @@ -995,6 +1006,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList /** * Terminate negotiations. */ + @Override public void close() { if (isClosed()) return; @@ -1056,6 +1068,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList /** * Called when new Media is received. */ + @Override public void mediaReceived(String participant) { triggerMediaReceived(participant); } @@ -1131,6 +1144,7 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList //updatePacketListener(); } + @Override protected void doStart() { } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionRequest.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionRequest.java index f6bfb3256..cc703960e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionRequest.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionRequest.java @@ -35,9 +35,9 @@ import org.jxmpp.jid.Jid; */ public class JingleSessionRequest { - private static final Logger LOGGER = Logger.getLogger(JingleSessionRequest.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleSessionRequest.class.getName()); - private final Jingle jingle; // The Jingle packet + private final Jingle jingle; // The Jingle packet private final JingleManager manager; // The manager associated to this @@ -130,15 +130,15 @@ public class JingleSessionRequest { JingleSession session = null; synchronized (manager) { try { - session = manager.createIncomingJingleSession(this); - // Acknowledge the IQ reception - session.setSid(this.getSessionID()); - //session.sendAck(this.getJingle()); - session.updatePacketListener(); - session.terminate("Declined"); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Exception in reject", e); - } + session = manager.createIncomingJingleSession(this); + // Acknowledge the IQ reception + session.setSid(this.getSessionID()); + //session.sendAck(this.getJingle()); + session.updatePacketListener(); + session.terminate("Declined"); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Exception in reject", e); + } } } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionState.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionState.java index 6b7c9d9cd..2d1408274 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionState.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionState.java @@ -61,6 +61,7 @@ public abstract class JingleSessionState { /** * For debugging just emit the short name of the class. */ + @Override public String toString() { return this.getClass().getSimpleName(); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateActive.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateActive.java index 016eddb20..b2371281e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateActive.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateActive.java @@ -48,16 +48,19 @@ public class JingleSessionStateActive extends JingleSessionState { return INSTANCE; } + @Override public void enter() { // TODO Auto-generated method stub } + @Override public void exit() { // TODO Auto-generated method stub } + @Override public IQ processJingle(JingleSession session, Jingle jingle, JingleActionEnum action) { IQ response = null; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateEnded.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateEnded.java index c632bcb4a..207d0069b 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateEnded.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateEnded.java @@ -29,9 +29,9 @@ import org.jivesoftware.smackx.jingleold.packet.JingleError; */ public class JingleSessionStateEnded extends JingleSessionState { - private static final Logger LOGGER = Logger.getLogger(JingleSessionStateEnded.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleSessionStateEnded.class.getName()); - private static JingleSessionStateEnded INSTANCE = null; + private static JingleSessionStateEnded INSTANCE = null; protected JingleSessionStateEnded() { // Prevent instantiation of the class. @@ -49,12 +49,14 @@ public class JingleSessionStateEnded extends JingleSessionState { return INSTANCE; } + @Override public void enter() { LOGGER.fine("Session Ended"); LOGGER.fine("-------------------------------------------------------------------"); } + @Override public void exit() { // TODO Auto-generated method stub @@ -63,6 +65,7 @@ public class JingleSessionStateEnded extends JingleSessionState { /** * Pretty much nothing is valid for receiving once we've ended the session. */ + @Override public IQ processJingle(JingleSession session, Jingle jingle, JingleActionEnum action) { IQ response = null; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStatePending.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStatePending.java index 0abe322e5..9d3cce1e3 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStatePending.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStatePending.java @@ -48,16 +48,19 @@ public class JingleSessionStatePending extends JingleSessionState { return INSTANCE; } + @Override public void enter() { // TODO Auto-generated method stub } + @Override public void exit() { // TODO Auto-generated method stub } + @Override public IQ processJingle(JingleSession session, Jingle jingle, JingleActionEnum action) { IQ response = null; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateUnknown.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateUnknown.java index a69439dbf..f5fa1d2c8 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateUnknown.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleSessionStateUnknown.java @@ -59,16 +59,19 @@ public class JingleSessionStateUnknown extends JingleSessionState { return INSTANCE; } + @Override public void enter() { // TODO Auto-generated method stub } + @Override public void exit() { // TODO Auto-generated method stub } + @Override public IQ processJingle(JingleSession session, Jingle jingle, JingleActionEnum action) throws SmackException, InterruptedException { IQ response = null; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/ContentInfo.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/ContentInfo.java index 513de4ee6..2f0ceb9b9 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/ContentInfo.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/ContentInfo.java @@ -49,6 +49,7 @@ public abstract class ContentInfo { this.value = value; } + @Override public String toString() { return value; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java index 807a58484..ec6447776 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/MediaNegotiator.java @@ -46,9 +46,9 @@ import org.jivesoftware.smackx.jingleold.packet.JingleError; */ public class MediaNegotiator extends JingleNegotiator { - private static final Logger LOGGER = Logger.getLogger(MediaNegotiator.class.getName()); + private static final Logger LOGGER = Logger.getLogger(MediaNegotiator.class.getName()); - //private JingleSession session; // The session this negotiation + //private JingleSession session; // The session this negotiation private final JingleMediaManager mediaManager; @@ -105,6 +105,7 @@ public class MediaNegotiator extends JingleNegotiator { * @throws NotConnectedException * @throws InterruptedException */ + @Override public List dispatchIncomingPacket(IQ iq, String id) throws XMPPException, NotConnectedException, InterruptedException { List responses = new ArrayList(); IQ response = null; @@ -510,6 +511,7 @@ public class MediaNegotiator extends JingleNegotiator { /** * Called from above when starting a new session. */ + @Override protected void doStart() { } @@ -517,6 +519,7 @@ public class MediaNegotiator extends JingleNegotiator { /** * Terminate the jmf negotiator. */ + @Override public void close() { super.close(); triggerMediaClosed(getBestCommonAudioPt()); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/PayloadType.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/PayloadType.java index c6301b3c3..bd1215006 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/PayloadType.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/media/PayloadType.java @@ -149,6 +149,7 @@ public class PayloadType { * * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { final int PRIME = 31; int result = 1; @@ -163,6 +164,7 @@ public class PayloadType { * * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -333,6 +335,7 @@ public class PayloadType { * * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); @@ -345,6 +348,7 @@ public class PayloadType { * * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/JMFInit.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/JMFInit.java index 04c17de02..43dd3a95b 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/JMFInit.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/JMFInit.java @@ -32,11 +32,11 @@ import com.sun.media.util.Registry; public class JMFInit extends Frame implements Runnable { - private static final long serialVersionUID = 6476412003260641680L; + private static final long serialVersionUID = 6476412003260641680L; - private static final Logger LOGGER = Logger.getLogger(JMFInit.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JMFInit.class.getName()); - private String tempDir = "/tmp"; + private String tempDir = "/tmp"; private boolean done = false; @@ -78,6 +78,7 @@ public class JMFInit extends Frame implements Runnable { */ } + @Override public void run() { detectDirectAudio(); detectS8DirectAudio(); @@ -108,7 +109,7 @@ public class JMFInit extends Frame implements Runnable { Class dsauto; try { dsauto = Class.forName("DirectSoundAuto"); - dsauto.newInstance(); + dsauto.getConstructor().newInstance(); message("Finished detecting DirectSound capturer"); } catch (ThreadDeath td) { @@ -121,7 +122,7 @@ public class JMFInit extends Frame implements Runnable { Class jsauto; try { jsauto = Class.forName("JavaSoundAuto"); - jsauto.newInstance(); + jsauto.getConstructor().newInstance(); message("Finished detecting javasound capturer"); } catch (ThreadDeath td) { @@ -194,7 +195,7 @@ public class JMFInit extends Frame implements Runnable { // Find the renderer class and instantiate it. cls = Class.forName(dar); - Renderer rend = (Renderer) cls.newInstance(); + Renderer rend = (Renderer) cls.getConstructor().newInstance(); try { // Set the format and open the device AudioFormat af = new AudioFormat(AudioFormat.LINEAR, 44100, 16, @@ -239,7 +240,7 @@ public class JMFInit extends Frame implements Runnable { // Find the renderer class and instantiate it. cls = Class.forName(dar); - Renderer rend = (Renderer) cls.newInstance(); + Renderer rend = (Renderer) cls.getConstructor().newInstance(); if (rend instanceof ExclusiveUse && !((ExclusiveUse) rend).isExclusive()) { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioChannel.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioChannel.java index 20e134b64..dd2932986 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioChannel.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioChannel.java @@ -69,9 +69,9 @@ import org.jivesoftware.smackx.jingleold.media.JingleMediaSession; */ public class AudioChannel { - private static final Logger LOGGER = Logger.getLogger(AudioChannel.class.getName()); + private static final Logger LOGGER = Logger.getLogger(AudioChannel.class.getName()); - private MediaLocator locator; + private MediaLocator locator; private String localIpAddress; private String remoteIpAddress; private int localPort; @@ -482,6 +482,7 @@ public class AudioChannel { class StateListener implements ControllerListener { + @Override public void controllerUpdate(ControllerEvent ce) { // If there was an error during configure or diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioMediaSession.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioMediaSession.java index 0347ee9d9..262b32936 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioMediaSession.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioMediaSession.java @@ -40,9 +40,9 @@ import org.jivesoftware.smackx.jingleold.nat.TransportCandidate; */ public class AudioMediaSession extends JingleMediaSession { - private static final Logger LOGGER = Logger.getLogger(AudioMediaSession.class.getName()); + private static final Logger LOGGER = Logger.getLogger(AudioMediaSession.class.getName()); - private AudioChannel audioChannel; + private AudioChannel audioChannel; /** * Creates a org.jivesoftware.jingleaudio.jmf.AudioMediaSession with defined payload type, remote and local candidates. @@ -61,6 +61,7 @@ public class AudioMediaSession extends JingleMediaSession { /** * Initialize the Audio Channel to make it able to send and receive audio. */ + @Override public void initialize() { String ip; @@ -90,6 +91,7 @@ public class AudioMediaSession extends JingleMediaSession { /** * Starts transmission and for NAT Traversal reasons start receiving also. */ + @Override public void startTrasmit() { audioChannel.start(); } @@ -100,6 +102,7 @@ public class AudioMediaSession extends JingleMediaSession { * * @param active active state */ + @Override public void setTrasmit(boolean active) { audioChannel.setTrasmit(active); } @@ -107,6 +110,7 @@ public class AudioMediaSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void startReceive() { // Do nothing } @@ -114,6 +118,7 @@ public class AudioMediaSession extends JingleMediaSession { /** * Stops transmission and for NAT Traversal reasons stop receiving also. */ + @Override public void stopTrasmit() { if (audioChannel != null) audioChannel.stop(); @@ -122,6 +127,7 @@ public class AudioMediaSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void stopReceive() { // Do nothing } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioReceiver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioReceiver.java index d19a3bb9f..0f26d5463 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioReceiver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioReceiver.java @@ -47,9 +47,9 @@ import org.jivesoftware.smackx.jingleold.media.JingleMediaSession; public class AudioReceiver implements ReceiveStreamListener, SessionListener, ControllerListener { - private static final Logger LOGGER = Logger.getLogger(AudioReceiver.class.getName()); + private static final Logger LOGGER = Logger.getLogger(AudioReceiver.class.getName()); - boolean dataReceived = false; + boolean dataReceived = false; final Object dataSync; JingleMediaSession jingleMediaSession; @@ -62,6 +62,7 @@ public class AudioReceiver implements ReceiveStreamListener, SessionListener, /** * JingleSessionListener. */ + @Override public synchronized void update(SessionEvent evt) { if (evt instanceof NewParticipantEvent) { Participant p = ((NewParticipantEvent) evt).getParticipant(); @@ -72,6 +73,7 @@ public class AudioReceiver implements ReceiveStreamListener, SessionListener, /** * ReceiveStreamListener. */ + @Override public synchronized void update(ReceiveStreamEvent evt) { Participant participant = evt.getParticipant(); // could be null. @@ -147,6 +149,7 @@ public class AudioReceiver implements ReceiveStreamListener, SessionListener, /** * ControllerListener for the Players. */ + @Override public synchronized void controllerUpdate(ControllerEvent ce) { Player p = (Player) ce.getSourceController(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java index af4b99493..00f2bb150 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java @@ -40,9 +40,9 @@ import org.jivesoftware.smackx.jingleold.nat.TransportCandidate; */ public class JmfMediaManager extends JingleMediaManager { - private static final Logger LOGGER = Logger.getLogger(JmfMediaManager.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JmfMediaManager.class.getName()); - public static final String MEDIA_NAME = "JMF"; + public static final String MEDIA_NAME = "JMF"; private List payloads = new ArrayList(); @@ -75,6 +75,7 @@ public class JmfMediaManager extends JingleMediaManager { * @param local local Candidate * @return JingleMediaSession */ + @Override public JingleMediaSession createMediaSession(final PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, final JingleSession jingleSession) { return new AudioMediaSession(payloadType, remote, local, mediaLocator, jingleSession); } @@ -93,6 +94,7 @@ public class JmfMediaManager extends JingleMediaManager { * * @return The Payload List */ + @Override public List getPayloads() { return payloads; } @@ -160,6 +162,7 @@ public class JmfMediaManager extends JingleMediaManager { // @TODO Implement Linux Pre-Install } + @Override public String getName() { return MEDIA_NAME; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/AudioMediaSession.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/AudioMediaSession.java index 51d95fa7b..4cc76268e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/AudioMediaSession.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/AudioMediaSession.java @@ -52,9 +52,9 @@ import org.jivesoftware.smackx.jingleold.nat.TransportCandidate; public class AudioMediaSession extends JingleMediaSession implements MediaSessionListener { - private static final Logger LOGGER = Logger.getLogger(AudioMediaSession.class.getName()); + private static final Logger LOGGER = Logger.getLogger(AudioMediaSession.class.getName()); - private MediaSession mediaSession; + private MediaSession mediaSession; /** * Create a Session using Speex Codec. @@ -112,6 +112,7 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * Initialize the Audio Channel to make it able to send and receive audio. */ + @Override public void initialize() { String ip; @@ -155,6 +156,7 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * Starts transmission and for NAT Traversal reasons start receiving also. */ + @Override public void startTrasmit() { try { LOGGER.fine("start"); @@ -172,6 +174,7 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio * * @param active active state */ + @Override public void setTrasmit(boolean active) { // Do nothing } @@ -179,6 +182,7 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void startReceive() { // Do nothing } @@ -186,6 +190,7 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * Stops transmission and for NAT Traversal reasons stop receiving also. */ + @Override public void stopTrasmit() { if (mediaSession != null) mediaSession.close(); @@ -194,16 +199,20 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void stopReceive() { // Do nothing } + @Override public void newStreamIdentified(StreamPlayer streamPlayer) { } + @Override public void senderReportReceived(SenderReport report) { } + @Override public void streamClosed(StreamPlayer stream, boolean timeout) { } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/SpeexMediaManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/SpeexMediaManager.java index 50ec237c6..145382822 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/SpeexMediaManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jspeex/SpeexMediaManager.java @@ -40,9 +40,9 @@ import org.jivesoftware.smackx.jingleold.nat.TransportCandidate; */ public class SpeexMediaManager extends JingleMediaManager { - private static final Logger LOGGER = Logger.getLogger(SpeexMediaManager.class.getName()); + private static final Logger LOGGER = Logger.getLogger(SpeexMediaManager.class.getName()); - public static final String MEDIA_NAME = "Speex"; + public static final String MEDIA_NAME = "Speex"; private List payloads = new ArrayList(); @@ -60,6 +60,7 @@ public class SpeexMediaManager extends JingleMediaManager { * @param local local Candidate * @return JingleMediaSession */ + @Override public JingleMediaSession createMediaSession(PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, final JingleSession jingleSession) { return new AudioMediaSession(payloadType, remote, local, null,null); } @@ -76,6 +77,7 @@ public class SpeexMediaManager extends JingleMediaManager { * * @return The Payload List */ + @Override public List getPayloads() { return payloads; } @@ -125,6 +127,7 @@ public class SpeexMediaManager extends JingleMediaManager { // @TODO Implement Linux Pre-Install } + @Override public String getName() { return MEDIA_NAME; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/multi/MultiMediaManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/multi/MultiMediaManager.java index d8e094e7b..2a93f85c2 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/multi/MultiMediaManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/multi/MultiMediaManager.java @@ -58,6 +58,7 @@ public class MultiMediaManager extends JingleMediaManager { * * @return The Payload List */ + @Override public List getPayloads() { List list = new ArrayList(); if (preferredPayloadType != null) list.add(preferredPayloadType); @@ -78,6 +79,7 @@ public class MultiMediaManager extends JingleMediaManager { * @param local local Candidate * @return JingleMediaSession JingleMediaSession */ + @Override public JingleMediaSession createMediaSession(PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, final JingleSession jingleSession) { for (JingleMediaManager manager : managers) { if (manager.getPayloads().contains(payloadType)) { @@ -87,6 +89,7 @@ public class MultiMediaManager extends JingleMediaManager { return null; } + @Override public PayloadType getPreferredPayloadType() { if (preferredPayloadType != null) return preferredPayloadType; return super.getPreferredPayloadType(); @@ -96,6 +99,7 @@ public class MultiMediaManager extends JingleMediaManager { this.preferredPayloadType = preferredPayloadType; } + @Override public String getName() { return MEDIA_NAME; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareMediaManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareMediaManager.java index 8a5efa4b2..34b030fe1 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareMediaManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareMediaManager.java @@ -61,6 +61,7 @@ public class ScreenShareMediaManager extends JingleMediaManager { * * @return The Payload List */ + @Override public List getPayloads() { return payloads; } @@ -73,6 +74,7 @@ public class ScreenShareMediaManager extends JingleMediaManager { * @param local local Candidate * @return JingleMediaSession JingleMediaSession */ + @Override public JingleMediaSession createMediaSession(PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, final JingleSession jingleSession) { ScreenShareSession session = null; session = new ScreenShareSession(payloadType, remote, local, "Screen", jingleSession); @@ -85,6 +87,7 @@ public class ScreenShareMediaManager extends JingleMediaManager { return session; } + @Override public PayloadType getPreferredPayloadType() { return super.getPreferredPayloadType(); } @@ -105,6 +108,7 @@ public class ScreenShareMediaManager extends JingleMediaManager { this.encoder = encoder; } + @Override public String getName() { return MEDIA_NAME; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareSession.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareSession.java index 4b0bcce45..f7bb39069 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareSession.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/ScreenShareSession.java @@ -50,9 +50,9 @@ import org.jivesoftware.smackx.jingleold.nat.TransportCandidate; */ public class ScreenShareSession extends JingleMediaSession { - private static final Logger LOGGER = Logger.getLogger(ScreenShareSession.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ScreenShareSession.class.getName()); - private ImageTransmitter transmitter = null; + private ImageTransmitter transmitter = null; private ImageReceiver receiver = null; private int width = 600; private int height = 600; @@ -74,6 +74,7 @@ public class ScreenShareSession extends JingleMediaSession { /** * Initialize the screen share channels. */ + @Override public void initialize() { JingleSession session = getJingleSession(); @@ -97,6 +98,7 @@ public class ScreenShareSession extends JingleMediaSession { window.setSize(600, 600); window.addWindowListener(new WindowAdapter() { + @Override public void windowClosed(WindowEvent e) { receiver.stop(); } @@ -120,6 +122,7 @@ public class ScreenShareSession extends JingleMediaSession { /** * Starts transmission and for NAT Traversal reasons start receiving also. */ + @Override public void startTrasmit() { new Thread(transmitter).start(); } @@ -130,6 +133,7 @@ public class ScreenShareSession extends JingleMediaSession { * * @param active active state */ + @Override public void setTrasmit(boolean active) { transmitter.setTransmit(true); } @@ -137,6 +141,7 @@ public class ScreenShareSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void startReceive() { // Do nothing } @@ -144,6 +149,7 @@ public class ScreenShareSession extends JingleMediaSession { /** * Stops transmission and for NAT Traversal reasons stop receiving also. */ + @Override public void stopTrasmit() { if (transmitter != null) { transmitter.stop(); @@ -153,6 +159,7 @@ public class ScreenShareSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void stopReceive() { if (receiver != null) { receiver.stop(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/AbstractBufferedImageOp.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/AbstractBufferedImageOp.java index 3c2165d36..9edb92662 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/AbstractBufferedImageOp.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/AbstractBufferedImageOp.java @@ -29,16 +29,19 @@ import java.awt.image.ColorModel; */ public abstract class AbstractBufferedImageOp implements BufferedImageOp, Cloneable { + @Override public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM) { if (dstCM == null) dstCM = src.getColorModel(); return new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), dstCM.isAlphaPremultiplied(), null); } + @Override public Rectangle2D getBounds2D(BufferedImage src) { return new Rectangle(0, 0, src.getWidth(), src.getHeight()); } + @Override public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) dstPt = new Point2D.Double(); @@ -46,13 +49,14 @@ public abstract class AbstractBufferedImageOp implements BufferedImageOp, Clonea return dstPt; } + @Override public RenderingHints getRenderingHints() { return null; } - /** - * A convenience method for getting ARGB pixels from an image. This tries to avoid the performance - * penalty of BufferedImage.getRGB unmanaging the image. + /** + * A convenience method for getting ARGB pixels from an image. This tries to avoid the performance + * penalty of BufferedImage.getRGB unmanaging the image. * @param image a BufferedImage object * @param x the left edge of the pixel block * @param y the right edge of the pixel block @@ -62,16 +66,16 @@ public abstract class AbstractBufferedImageOp implements BufferedImageOp, Clonea * @return the pixels * @see #setRGB */ - public int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { - int type = image.getType(); - if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) - return (int [])image.getRaster().getDataElements(x, y, width, height, pixels); - return image.getRGB(x, y, width, height, pixels, 0, width); + public int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { + int type = image.getType(); + if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) + return (int [])image.getRaster().getDataElements(x, y, width, height, pixels); + return image.getRGB(x, y, width, height, pixels, 0, width); } - /** - * A convenience method for setting ARGB pixels in an image. This tries to avoid the performance - * penalty of BufferedImage.setRGB unmanaging the image. + /** + * A convenience method for setting ARGB pixels in an image. This tries to avoid the performance + * penalty of BufferedImage.setRGB unmanaging the image. * @param image a BufferedImage object * @param x the left edge of the pixel block * @param y the right edge of the pixel block @@ -79,21 +83,22 @@ public abstract class AbstractBufferedImageOp implements BufferedImageOp, Clonea * @param height the height of the pixel arry * @param pixels the array of pixels to set * @see #getRGB - */ - public void setRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { - int type = image.getType(); - if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) - image.getRaster().setDataElements(x, y, width, height, pixels); - else - image.setRGB(x, y, width, height, pixels, 0, width); + */ + public void setRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { + int type = image.getType(); + if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) + image.getRaster().setDataElements(x, y, width, height, pixels); + else + image.setRGB(x, y, width, height, pixels, 0, width); } - public Object clone() { - try { - return super.clone(); - } - catch (CloneNotSupportedException e) { - return null; - } - } + @Override + public Object clone() { + try { + return super.clone(); + } + catch (CloneNotSupportedException e) { + return null; + } + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultDecoder.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultDecoder.java index 0495f54f4..86aad00a8 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultDecoder.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultDecoder.java @@ -26,6 +26,7 @@ import java.io.IOException; */ public class DefaultDecoder implements ImageDecoder { + @Override public BufferedImage decode(ByteArrayInputStream stream) throws IOException { return ImageIO.read(stream); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultEncoder.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultEncoder.java index 79f387361..ff2986cc6 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultEncoder.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/DefaultEncoder.java @@ -30,6 +30,7 @@ import java.util.logging.Logger; public class DefaultEncoder implements ImageEncoder{ private static final Logger LOGGER = Logger.getLogger(DefaultEncoder.class.getName()); + @Override public ByteArrayOutputStream encode(BufferedImage bufferedImage) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageReceiver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageReceiver.java index a6d9682d5..2f1a8564e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageReceiver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageReceiver.java @@ -37,8 +37,8 @@ import java.util.logging.Logger; public class ImageReceiver extends Canvas { private static final Logger LOGGER = Logger.getLogger(ImageReceiver.class.getName()); - private static final long serialVersionUID = -7000112305305269025L; - private boolean on = true; + private static final long serialVersionUID = -7000112305305269025L; + private boolean on = true; private DatagramSocket socket; private BufferedImage[][] tiles; private static final int tileWidth = ImageTransmitter.tileWidth; @@ -61,6 +61,7 @@ public class ImageReceiver extends Canvas { this.decoder = new DefaultDecoder(); new Thread(new Runnable() { + @Override public void run() { byte[] buf = new byte[1024]; DatagramPacket p = new DatagramPacket(buf, 1024); @@ -90,6 +91,7 @@ public class ImageReceiver extends Canvas { }).start(); new Thread(new Runnable() { + @Override public void run() { byte[] buf = new byte[1024]; DatagramPacket p = new DatagramPacket(buf, 1024); @@ -148,6 +150,7 @@ public class ImageReceiver extends Canvas { this.getGraphics().drawImage(bufferedImage, tileWidth * x, tileWidth * y, this); } + @Override public void paint(Graphics g) { for (int i = 0; i < tiles.length; i++) { for (int j = 0; j < tiles[0].length; j++) { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageTransmitter.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageTransmitter.java index 0f1392e29..a17be8df9 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageTransmitter.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/ImageTransmitter.java @@ -38,9 +38,9 @@ import java.util.logging.Logger; */ public class ImageTransmitter implements Runnable { - private static final Logger LOGGER = Logger.getLogger(ImageTransmitter.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ImageTransmitter.class.getName()); - private Robot robot; + private Robot robot; private InetAddress localHost; private InetAddress remoteHost; private int localPort; @@ -178,6 +178,7 @@ public class ImageTransmitter implements Runnable { } } + @Override public void run() { start(); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/OctTreeQuantizer.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/OctTreeQuantizer.java index 3f5755d80..922700a79 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/OctTreeQuantizer.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/OctTreeQuantizer.java @@ -29,260 +29,264 @@ import java.util.logging.Logger; */ public class OctTreeQuantizer implements Quantizer { - private static final Logger LOGGER = Logger.getLogger(OctTreeQuantizer.class.getName()); + private static final Logger LOGGER = Logger.getLogger(OctTreeQuantizer.class.getName()); - /** - * The greatest depth the tree is allowed to reach - */ - final static int MAX_LEVEL = 5; + /** + * The greatest depth the tree is allowed to reach + */ + final static int MAX_LEVEL = 5; - /** - * An Octtree node. - */ - class OctTreeNode { - int children; - int level; - OctTreeNode parent; - OctTreeNode[] leaf = new OctTreeNode[8]; - boolean isLeaf; - int count; - int totalRed; - int totalGreen; - int totalBlue; - int index; + /** + * An Octtree node. + */ + static class OctTreeNode { + int children; + int level; + OctTreeNode parent; + OctTreeNode[] leaf = new OctTreeNode[8]; + boolean isLeaf; + int count; + int totalRed; + int totalGreen; + int totalBlue; + int index; - /** - * A debugging method which prints the tree out. - */ - public void list(PrintStream s, int level) { - String indentStr = ""; - for (int i = 0; i < level; i++) - indentStr += " "; - if (count == 0) - LOGGER.fine(indentStr + index + ": count=" + count); - else - LOGGER.fine(indentStr + index + ": count=" + count + " red=" + (totalRed/count) + " green=" + (totalGreen / count) + " blue=" + (totalBlue / count)); - for (int i = 0; i < 8; i++) - if (leaf[i] != null) - leaf[i].list(s, level+2); - } - } + /** + * A debugging method which prints the tree out. + */ + public void list(PrintStream s, int level) { + String indentStr = ""; + for (int i = 0; i < level; i++) + indentStr += " "; + if (count == 0) + LOGGER.fine(indentStr + index + ": count=" + count); + else + LOGGER.fine(indentStr + index + ": count=" + count + " red=" + (totalRed/count) + " green=" + (totalGreen / count) + " blue=" + (totalBlue / count)); + for (int i = 0; i < 8; i++) + if (leaf[i] != null) + leaf[i].list(s, level+2); + } + } - private int nodes = 0; - private OctTreeNode root; - private int reduceColors; - private int maximumColors; - private int colors = 0; - private List> colorList; + private int nodes = 0; + private OctTreeNode root; + private int reduceColors; + private int maximumColors; + private int colors = 0; + private List> colorList; public OctTreeQuantizer() { - setup(256); - colorList = new ArrayList<>(MAX_LEVEL+1); - for (int i = 0; i < MAX_LEVEL+1; i++) - colorList.add(i, new Vector()); - root = new OctTreeNode(); - } + setup(256); + colorList = new ArrayList<>(MAX_LEVEL+1); + for (int i = 0; i < MAX_LEVEL+1; i++) + colorList.add(i, new Vector()); + root = new OctTreeNode(); + } - /** - * Initialize the quantizer. This should be called before adding any pixels. - * @param numColors the number of colors we're quantizing to. - */ - public void setup(int numColors) { - maximumColors = numColors; - reduceColors = Math.max(512, numColors * 2); - } + /** + * Initialize the quantizer. This should be called before adding any pixels. + * @param numColors the number of colors we're quantizing to. + */ + @Override + public void setup(int numColors) { + maximumColors = numColors; + reduceColors = Math.max(512, numColors * 2); + } - /** - * Add pixels to the quantizer. - * @param pixels the array of ARGB pixels - * @param offset the offset into the array - * @param count the count of pixels - */ - public void addPixels(int[] pixels, int offset, int count) { - for (int i = 0; i < count; i++) { - insertColor(pixels[i+offset]); - if (colors > reduceColors) - reduceTree(reduceColors); - } - } + /** + * Add pixels to the quantizer. + * @param pixels the array of ARGB pixels + * @param offset the offset into the array + * @param count the count of pixels + */ + @Override + public void addPixels(int[] pixels, int offset, int count) { + for (int i = 0; i < count; i++) { + insertColor(pixels[i+offset]); + if (colors > reduceColors) + reduceTree(reduceColors); + } + } /** * Get the color table index for a color. * @param rgb the color * @return the index */ - public int getIndexForColor(int rgb) { - int red = (rgb >> 16) & 0xff; - int green = (rgb >> 8) & 0xff; - int blue = rgb & 0xff; + @Override + public int getIndexForColor(int rgb) { + int red = (rgb >> 16) & 0xff; + int green = (rgb >> 8) & 0xff; + int blue = rgb & 0xff; - OctTreeNode node = root; + OctTreeNode node = root; - for (int level = 0; level <= MAX_LEVEL; level++) { - OctTreeNode child; - int bit = 0x80 >> level; + for (int level = 0; level <= MAX_LEVEL; level++) { + OctTreeNode child; + int bit = 0x80 >> level; - int index = 0; - if ((red & bit) != 0) - index += 4; - if ((green & bit) != 0) - index += 2; - if ((blue & bit) != 0) - index += 1; + int index = 0; + if ((red & bit) != 0) + index += 4; + if ((green & bit) != 0) + index += 2; + if ((blue & bit) != 0) + index += 1; - child = node.leaf[index]; + child = node.leaf[index]; - if (child == null) - return node.index; - else if (child.isLeaf) - return child.index; - else - node = child; - } - LOGGER.fine("getIndexForColor failed"); - return 0; - } + if (child == null) + return node.index; + else if (child.isLeaf) + return child.index; + else + node = child; + } + LOGGER.fine("getIndexForColor failed"); + return 0; + } - private void insertColor(int rgb) { - int red = (rgb >> 16) & 0xff; - int green = (rgb >> 8) & 0xff; - int blue = rgb & 0xff; + private void insertColor(int rgb) { + int red = (rgb >> 16) & 0xff; + int green = (rgb >> 8) & 0xff; + int blue = rgb & 0xff; - OctTreeNode node = root; + OctTreeNode node = root; -// LOGGER.fine("insertColor="+Integer.toHexString(rgb)); - for (int level = 0; level <= MAX_LEVEL; level++) { - OctTreeNode child; - int bit = 0x80 >> level; +// LOGGER.fine("insertColor="+Integer.toHexString(rgb)); + for (int level = 0; level <= MAX_LEVEL; level++) { + OctTreeNode child; + int bit = 0x80 >> level; - int index = 0; - if ((red & bit) != 0) - index += 4; - if ((green & bit) != 0) - index += 2; - if ((blue & bit) != 0) - index += 1; + int index = 0; + if ((red & bit) != 0) + index += 4; + if ((green & bit) != 0) + index += 2; + if ((blue & bit) != 0) + index += 1; - child = node.leaf[index]; + child = node.leaf[index]; - if (child == null) { - node.children++; + if (child == null) { + node.children++; - child = new OctTreeNode(); - child.parent = node; - node.leaf[index] = child; - node.isLeaf = false; - nodes++; - colorList.get(level).addElement(child); + child = new OctTreeNode(); + child.parent = node; + node.leaf[index] = child; + node.isLeaf = false; + nodes++; + colorList.get(level).addElement(child); - if (level == MAX_LEVEL) { - child.isLeaf = true; - child.count = 1; - child.totalRed = red; - child.totalGreen = green; - child.totalBlue = blue; - child.level = level; - colors++; - return; - } + if (level == MAX_LEVEL) { + child.isLeaf = true; + child.count = 1; + child.totalRed = red; + child.totalGreen = green; + child.totalBlue = blue; + child.level = level; + colors++; + return; + } - node = child; - } else if (child.isLeaf) { - child.count++; - child.totalRed += red; - child.totalGreen += green; - child.totalBlue += blue; - return; - } else - node = child; - } - LOGGER.fine("insertColor failed"); - } + node = child; + } else if (child.isLeaf) { + child.count++; + child.totalRed += red; + child.totalGreen += green; + child.totalBlue += blue; + return; + } else + node = child; + } + LOGGER.fine("insertColor failed"); + } - private void reduceTree(int numColors) { - for (int level = MAX_LEVEL-1; level >= 0; level--) { - Vector v = colorList.get(level); - if (v != null && v.size() > 0) { - for (int j = 0; j < v.size(); j++) { - OctTreeNode node = v.elementAt(j); - if (node.children > 0) { - for (int i = 0; i < 8; i++) { - OctTreeNode child = node.leaf[i]; - if (child != null) { - if (!child.isLeaf) - LOGGER.fine("not a leaf!"); - node.count += child.count; - node.totalRed += child.totalRed; - node.totalGreen += child.totalGreen; - node.totalBlue += child.totalBlue; - node.leaf[i] = null; - node.children--; - colors--; - nodes--; - colorList.get(level+1).removeElement(child); - } - } - node.isLeaf = true; - colors++; - if (colors <= numColors) - return; - } - } - } - } + private void reduceTree(int numColors) { + for (int level = MAX_LEVEL-1; level >= 0; level--) { + Vector v = colorList.get(level); + if (v != null && v.size() > 0) { + for (int j = 0; j < v.size(); j++) { + OctTreeNode node = v.elementAt(j); + if (node.children > 0) { + for (int i = 0; i < 8; i++) { + OctTreeNode child = node.leaf[i]; + if (child != null) { + if (!child.isLeaf) + LOGGER.fine("not a leaf!"); + node.count += child.count; + node.totalRed += child.totalRed; + node.totalGreen += child.totalGreen; + node.totalBlue += child.totalBlue; + node.leaf[i] = null; + node.children--; + colors--; + nodes--; + colorList.get(level+1).removeElement(child); + } + } + node.isLeaf = true; + colors++; + if (colors <= numColors) + return; + } + } + } + } - LOGGER.fine("Unable to reduce the OctTree"); - } + LOGGER.fine("Unable to reduce the OctTree"); + } /** * Build the color table. * @return the color table */ - public int[] buildColorTable() { - int[] table = new int[colors]; - buildColorTable(root, table, 0); - return table; - } + @Override + public int[] buildColorTable() { + int[] table = new int[colors]; + buildColorTable(root, table, 0); + return table; + } - /** - * A quick way to use the quantizer. Just create a table the right size and pass in the pixels. + /** + * A quick way to use the quantizer. Just create a table the right size and pass in the pixels. * @param inPixels the input colors * @param table the output color table */ - public void buildColorTable(int[] inPixels, int[] table) { - int count = inPixels.length; - maximumColors = table.length; - for (int i = 0; i < count; i++) { - insertColor(inPixels[i]); - if (colors > reduceColors) - reduceTree(reduceColors); - } - if (colors > maximumColors) - reduceTree(maximumColors); - buildColorTable(root, table, 0); - } + public void buildColorTable(int[] inPixels, int[] table) { + int count = inPixels.length; + maximumColors = table.length; + for (int i = 0; i < count; i++) { + insertColor(inPixels[i]); + if (colors > reduceColors) + reduceTree(reduceColors); + } + if (colors > maximumColors) + reduceTree(maximumColors); + buildColorTable(root, table, 0); + } - private int buildColorTable(OctTreeNode node, int[] table, int index) { - if (colors > maximumColors) - reduceTree(maximumColors); + private int buildColorTable(OctTreeNode node, int[] table, int index) { + if (colors > maximumColors) + reduceTree(maximumColors); - if (node.isLeaf) { - int count = node.count; - table[index] = 0xff000000 | - ((node.totalRed/count) << 16) | - ((node.totalGreen/count) << 8) | - node.totalBlue/count; - node.index = index++; - } else { - for (int i = 0; i < 8; i++) { - if (node.leaf[i] != null) { - node.index = index; - index = buildColorTable(node.leaf[i], table, index); - } - } - } - return index; - } + if (node.isLeaf) { + int count = node.count; + table[index] = 0xff000000 | + ((node.totalRed/count) << 16) | + ((node.totalGreen/count) << 8) | + node.totalBlue/count; + node.index = index++; + } else { + for (int i = 0; i < 8; i++) { + if (node.leaf[i] != null) { + node.index = index; + index = buildColorTable(node.leaf[i], table, index); + } + } + } + return index; + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/PixelUtils.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/PixelUtils.java index 20946dd66..525997ef0 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/PixelUtils.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/PixelUtils.java @@ -26,199 +26,199 @@ import java.util.Random; */ public class PixelUtils { - public final static int REPLACE = 0; - public final static int NORMAL = 1; - public final static int MIN = 2; - public final static int MAX = 3; - public final static int ADD = 4; - public final static int SUBTRACT = 5; - public final static int DIFFERENCE = 6; - public final static int MULTIPLY = 7; - public final static int HUE = 8; - public final static int SATURATION = 9; - public final static int VALUE = 10; - public final static int COLOR = 11; - public final static int SCREEN = 12; - public final static int AVERAGE = 13; - public final static int OVERLAY = 14; - public final static int CLEAR = 15; - public final static int EXCHANGE = 16; - public final static int DISSOLVE = 17; - public final static int DST_IN = 18; - public final static int ALPHA = 19; - public final static int ALPHA_TO_GRAY = 20; + public final static int REPLACE = 0; + public final static int NORMAL = 1; + public final static int MIN = 2; + public final static int MAX = 3; + public final static int ADD = 4; + public final static int SUBTRACT = 5; + public final static int DIFFERENCE = 6; + public final static int MULTIPLY = 7; + public final static int HUE = 8; + public final static int SATURATION = 9; + public final static int VALUE = 10; + public final static int COLOR = 11; + public final static int SCREEN = 12; + public final static int AVERAGE = 13; + public final static int OVERLAY = 14; + public final static int CLEAR = 15; + public final static int EXCHANGE = 16; + public final static int DISSOLVE = 17; + public final static int DST_IN = 18; + public final static int ALPHA = 19; + public final static int ALPHA_TO_GRAY = 20; - private static Random randomGenerator = new Random(); + private static Random randomGenerator = new Random(); - /** - * Clamp a value to the range 0..255. - */ - public static int clamp(int c) { - if (c < 0) - return 0; - if (c > 255) - return 255; - return c; - } + /** + * Clamp a value to the range 0..255. + */ + public static int clamp(int c) { + if (c < 0) + return 0; + if (c > 255) + return 255; + return c; + } - public static int interpolate(int v1, int v2, float f) { - return clamp((int)(v1+f*(v2-v1))); - } + public static int interpolate(int v1, int v2, float f) { + return clamp((int)(v1+f*(v2-v1))); + } - public static int brightness(int rgb) { - int r = (rgb >> 16) & 0xff; - int g = (rgb >> 8) & 0xff; - int b = rgb & 0xff; - return (r+g+b)/3; - } + public static int brightness(int rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + return (r+g+b)/3; + } - public static boolean nearColors(int rgb1, int rgb2, int tolerance) { - int r1 = (rgb1 >> 16) & 0xff; - int g1 = (rgb1 >> 8) & 0xff; - int b1 = rgb1 & 0xff; - int r2 = (rgb2 >> 16) & 0xff; - int g2 = (rgb2 >> 8) & 0xff; - int b2 = rgb2 & 0xff; - return Math.abs(r1-r2) <= tolerance && Math.abs(g1-g2) <= tolerance && Math.abs(b1-b2) <= tolerance; - } + public static boolean nearColors(int rgb1, int rgb2, int tolerance) { + int r1 = (rgb1 >> 16) & 0xff; + int g1 = (rgb1 >> 8) & 0xff; + int b1 = rgb1 & 0xff; + int r2 = (rgb2 >> 16) & 0xff; + int g2 = (rgb2 >> 8) & 0xff; + int b2 = rgb2 & 0xff; + return Math.abs(r1-r2) <= tolerance && Math.abs(g1-g2) <= tolerance && Math.abs(b1-b2) <= tolerance; + } - private final static float[] hsb1 = new float[3];//FIXME-not thread safe - private final static float[] hsb2 = new float[3];//FIXME-not thread safe + private final static float[] hsb1 = new float[3];//FIXME-not thread safe + private final static float[] hsb2 = new float[3];//FIXME-not thread safe - // Return rgb1 painted onto rgb2 - public static int combinePixels(int rgb1, int rgb2, int op) { - return combinePixels(rgb1, rgb2, op, 0xff); - } + // Return rgb1 painted onto rgb2 + public static int combinePixels(int rgb1, int rgb2, int op) { + return combinePixels(rgb1, rgb2, op, 0xff); + } - public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha, int channelMask) { - return (rgb2 & ~channelMask) | combinePixels(rgb1 & channelMask, rgb2, op, extraAlpha); - } + public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha, int channelMask) { + return (rgb2 & ~channelMask) | combinePixels(rgb1 & channelMask, rgb2, op, extraAlpha); + } - public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha) { - if (op == REPLACE) - return rgb1; - int a1 = (rgb1 >> 24) & 0xff; - int r1 = (rgb1 >> 16) & 0xff; - int g1 = (rgb1 >> 8) & 0xff; - int b1 = rgb1 & 0xff; - int a2 = (rgb2 >> 24) & 0xff; - int r2 = (rgb2 >> 16) & 0xff; - int g2 = (rgb2 >> 8) & 0xff; - int b2 = rgb2 & 0xff; + public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha) { + if (op == REPLACE) + return rgb1; + int a1 = (rgb1 >> 24) & 0xff; + int r1 = (rgb1 >> 16) & 0xff; + int g1 = (rgb1 >> 8) & 0xff; + int b1 = rgb1 & 0xff; + int a2 = (rgb2 >> 24) & 0xff; + int r2 = (rgb2 >> 16) & 0xff; + int g2 = (rgb2 >> 8) & 0xff; + int b2 = rgb2 & 0xff; - switch (op) { - case NORMAL: - break; - case MIN: - r1 = Math.min(r1, r2); - g1 = Math.min(g1, g2); - b1 = Math.min(b1, b2); - break; - case MAX: - r1 = Math.max(r1, r2); - g1 = Math.max(g1, g2); - b1 = Math.max(b1, b2); - break; - case ADD: - r1 = clamp(r1+r2); - g1 = clamp(g1+g2); - b1 = clamp(b1+b2); - break; - case SUBTRACT: - r1 = clamp(r2-r1); - g1 = clamp(g2-g1); - b1 = clamp(b2-b1); - break; - case DIFFERENCE: - r1 = clamp(Math.abs(r1-r2)); - g1 = clamp(Math.abs(g1-g2)); - b1 = clamp(Math.abs(b1-b2)); - break; - case MULTIPLY: - r1 = clamp(r1*r2/255); - g1 = clamp(g1*g2/255); - b1 = clamp(b1*b2/255); - break; - case DISSOLVE: - if ((randomGenerator.nextInt() & 0xff) <= a1) { - r1 = r2; - g1 = g2; - b1 = b2; - } - break; - case AVERAGE: - r1 = (r1+r2)/2; - g1 = (g1+g2)/2; - b1 = (b1+b2)/2; - break; - case HUE: - case SATURATION: - case VALUE: - case COLOR: - Color.RGBtoHSB(r1, g1, b1, hsb1); - Color.RGBtoHSB(r2, g2, b2, hsb2); - switch (op) { - case HUE: - hsb2[0] = hsb1[0]; - break; - case SATURATION: - hsb2[1] = hsb1[1]; - break; - case VALUE: - hsb2[2] = hsb1[2]; - break; - case COLOR: - hsb2[0] = hsb1[0]; - hsb2[1] = hsb1[1]; - break; - } - rgb1 = Color.HSBtoRGB(hsb2[0], hsb2[1], hsb2[2]); - r1 = (rgb1 >> 16) & 0xff; - g1 = (rgb1 >> 8) & 0xff; - b1 = rgb1 & 0xff; - break; - case SCREEN: - r1 = 255 - ((255 - r1) * (255 - r2)) / 255; - g1 = 255 - ((255 - g1) * (255 - g2)) / 255; - b1 = 255 - ((255 - b1) * (255 - b2)) / 255; - break; - case OVERLAY: - int m, s; - s = 255 - ((255 - r1) * (255 - r2)) / 255; - m = r1 * r2 / 255; - r1 = (s * r1 + m * (255 - r1)) / 255; - s = 255 - ((255 - g1) * (255 - g2)) / 255; - m = g1 * g2 / 255; - g1 = (s * g1 + m * (255 - g1)) / 255; - s = 255 - ((255 - b1) * (255 - b2)) / 255; - m = b1 * b2 / 255; - b1 = (s * b1 + m * (255 - b1)) / 255; - break; - case CLEAR: - r1 = g1 = b1 = 0xff; - break; - case DST_IN: - r1 = clamp((r2*a1)/255); - g1 = clamp((g2*a1)/255); - b1 = clamp((b2*a1)/255); - a1 = clamp((a2*a1)/255); - return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; - case ALPHA: - a1 = a1*a2/255; - return (a1 << 24) | (r2 << 16) | (g2 << 8) | b2; - case ALPHA_TO_GRAY: - int na = 255-a1; - return (a1 << 24) | (na << 16) | (na << 8) | na; - } - if (extraAlpha != 0xff || a1 != 0xff) { - a1 = a1*extraAlpha/255; - int a3 = (255-a1)*a2/255; - r1 = clamp((r1*a1+r2*a3)/255); - g1 = clamp((g1*a1+g2*a3)/255); - b1 = clamp((b1*a1+b2*a3)/255); - a1 = clamp(a1+a3); - } - return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; - } + switch (op) { + case NORMAL: + break; + case MIN: + r1 = Math.min(r1, r2); + g1 = Math.min(g1, g2); + b1 = Math.min(b1, b2); + break; + case MAX: + r1 = Math.max(r1, r2); + g1 = Math.max(g1, g2); + b1 = Math.max(b1, b2); + break; + case ADD: + r1 = clamp(r1+r2); + g1 = clamp(g1+g2); + b1 = clamp(b1+b2); + break; + case SUBTRACT: + r1 = clamp(r2-r1); + g1 = clamp(g2-g1); + b1 = clamp(b2-b1); + break; + case DIFFERENCE: + r1 = clamp(Math.abs(r1-r2)); + g1 = clamp(Math.abs(g1-g2)); + b1 = clamp(Math.abs(b1-b2)); + break; + case MULTIPLY: + r1 = clamp(r1*r2/255); + g1 = clamp(g1*g2/255); + b1 = clamp(b1*b2/255); + break; + case DISSOLVE: + if ((randomGenerator.nextInt() & 0xff) <= a1) { + r1 = r2; + g1 = g2; + b1 = b2; + } + break; + case AVERAGE: + r1 = (r1+r2)/2; + g1 = (g1+g2)/2; + b1 = (b1+b2)/2; + break; + case HUE: + case SATURATION: + case VALUE: + case COLOR: + Color.RGBtoHSB(r1, g1, b1, hsb1); + Color.RGBtoHSB(r2, g2, b2, hsb2); + switch (op) { + case HUE: + hsb2[0] = hsb1[0]; + break; + case SATURATION: + hsb2[1] = hsb1[1]; + break; + case VALUE: + hsb2[2] = hsb1[2]; + break; + case COLOR: + hsb2[0] = hsb1[0]; + hsb2[1] = hsb1[1]; + break; + } + rgb1 = Color.HSBtoRGB(hsb2[0], hsb2[1], hsb2[2]); + r1 = (rgb1 >> 16) & 0xff; + g1 = (rgb1 >> 8) & 0xff; + b1 = rgb1 & 0xff; + break; + case SCREEN: + r1 = 255 - ((255 - r1) * (255 - r2)) / 255; + g1 = 255 - ((255 - g1) * (255 - g2)) / 255; + b1 = 255 - ((255 - b1) * (255 - b2)) / 255; + break; + case OVERLAY: + int m, s; + s = 255 - ((255 - r1) * (255 - r2)) / 255; + m = r1 * r2 / 255; + r1 = (s * r1 + m * (255 - r1)) / 255; + s = 255 - ((255 - g1) * (255 - g2)) / 255; + m = g1 * g2 / 255; + g1 = (s * g1 + m * (255 - g1)) / 255; + s = 255 - ((255 - b1) * (255 - b2)) / 255; + m = b1 * b2 / 255; + b1 = (s * b1 + m * (255 - b1)) / 255; + break; + case CLEAR: + r1 = g1 = b1 = 0xff; + break; + case DST_IN: + r1 = clamp((r2*a1)/255); + g1 = clamp((g2*a1)/255); + b1 = clamp((b2*a1)/255); + a1 = clamp((a2*a1)/255); + return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; + case ALPHA: + a1 = a1*a2/255; + return (a1 << 24) | (r2 << 16) | (g2 << 8) | b2; + case ALPHA_TO_GRAY: + int na = 255-a1; + return (a1 << 24) | (na << 16) | (na << 8) | na; + } + if (extraAlpha != 0xff || a1 != 0xff) { + a1 = a1*extraAlpha/255; + int a3 = (255-a1)*a2/255; + r1 = clamp((r1*a1+r2*a3)/255); + g1 = clamp((g1*a1+g2*a3)/255); + b1 = clamp((b1*a1+b2*a3)/255); + a1 = clamp(a1+a3); + } + return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/QuantizeFilter.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/QuantizeFilter.java index c2e181eac..7153538fe 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/QuantizeFilter.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/QuantizeFilter.java @@ -29,150 +29,152 @@ import java.awt.Rectangle; */ public class QuantizeFilter extends WholeImageFilter { - /** - * Floyd-Steinberg dithering matrix. - */ - protected final static int[] matrix = { - 0, 0, 0, - 0, 0, 7, - 3, 5, 1, - }; - private int sum = 3+5+7+1; + /** + * Floyd-Steinberg dithering matrix. + */ + protected final static int[] matrix = { + 0, 0, 0, + 0, 0, 7, + 3, 5, 1, + }; + private int sum = 3+5+7+1; - private boolean dither; - private int numColors = 256; - private boolean serpentine = true; + private boolean dither; + private int numColors = 256; + private boolean serpentine = true; - /** - * Set the number of colors to quantize to. - * @param numColors the number of colors. The default is 256. - */ - public void setNumColors(int numColors) { - this.numColors = Math.min(Math.max(numColors, 8), 256); - } + /** + * Set the number of colors to quantize to. + * @param numColors the number of colors. The default is 256. + */ + public void setNumColors(int numColors) { + this.numColors = Math.min(Math.max(numColors, 8), 256); + } - /** - * Get the number of colors to quantize to. - * @return the number of colors. - */ - public int getNumColors() { - return numColors; - } + /** + * Get the number of colors to quantize to. + * @return the number of colors. + */ + public int getNumColors() { + return numColors; + } - /** - * Set whether to use dithering or not. If not, the image is posterized. - * @param dither true to use dithering - */ - public void setDither(boolean dither) { - this.dither = dither; - } + /** + * Set whether to use dithering or not. If not, the image is posterized. + * @param dither true to use dithering + */ + public void setDither(boolean dither) { + this.dither = dither; + } - /** - * Return the dithering setting. - * @return the current setting - */ - public boolean getDither() { - return dither; - } + /** + * Return the dithering setting. + * @return the current setting + */ + public boolean getDither() { + return dither; + } - /** - * Set whether to use a serpentine pattern for return or not. This can reduce 'avalanche' artifacts in the output. - * @param serpentine true to use serpentine pattern - */ - public void setSerpentine(boolean serpentine) { - this.serpentine = serpentine; - } + /** + * Set whether to use a serpentine pattern for return or not. This can reduce 'avalanche' artifacts in the output. + * @param serpentine true to use serpentine pattern + */ + public void setSerpentine(boolean serpentine) { + this.serpentine = serpentine; + } - /** - * Return the serpentine setting. - * @return the current setting - */ - public boolean getSerpentine() { - return serpentine; - } + /** + * Return the serpentine setting. + * @return the current setting + */ + public boolean getSerpentine() { + return serpentine; + } - public void quantize(int[] inPixels, int[] outPixels, int width, int height, int numColors, boolean dither, boolean serpentine) { - int count = width*height; - Quantizer quantizer = new OctTreeQuantizer(); - quantizer.setup(numColors); - quantizer.addPixels(inPixels, 0, count); - int[] table = quantizer.buildColorTable(); + public void quantize(int[] inPixels, int[] outPixels, int width, int height, int numColors, boolean dither, boolean serpentine) { + int count = width*height; + Quantizer quantizer = new OctTreeQuantizer(); + quantizer.setup(numColors); + quantizer.addPixels(inPixels, 0, count); + int[] table = quantizer.buildColorTable(); - if (!dither) { - for (int i = 0; i < count; i++) - outPixels[i] = table[quantizer.getIndexForColor(inPixels[i])]; - } else { - int index = 0; - for (int y = 0; y < height; y++) { - boolean reverse = serpentine && (y & 1) == 1; - int direction; - if (reverse) { - index = y*width+width-1; - direction = -1; - } else { - index = y*width; - direction = 1; - } - for (int x = 0; x < width; x++) { - int rgb1 = inPixels[index]; - int rgb2 = table[quantizer.getIndexForColor(rgb1)]; + if (!dither) { + for (int i = 0; i < count; i++) + outPixels[i] = table[quantizer.getIndexForColor(inPixels[i])]; + } else { + int index = 0; + for (int y = 0; y < height; y++) { + boolean reverse = serpentine && (y & 1) == 1; + int direction; + if (reverse) { + index = y*width+width-1; + direction = -1; + } else { + index = y*width; + direction = 1; + } + for (int x = 0; x < width; x++) { + int rgb1 = inPixels[index]; + int rgb2 = table[quantizer.getIndexForColor(rgb1)]; - outPixels[index] = rgb2; + outPixels[index] = rgb2; - int r1 = (rgb1 >> 16) & 0xff; - int g1 = (rgb1 >> 8) & 0xff; - int b1 = rgb1 & 0xff; + int r1 = (rgb1 >> 16) & 0xff; + int g1 = (rgb1 >> 8) & 0xff; + int b1 = rgb1 & 0xff; - int r2 = (rgb2 >> 16) & 0xff; - int g2 = (rgb2 >> 8) & 0xff; - int b2 = rgb2 & 0xff; + int r2 = (rgb2 >> 16) & 0xff; + int g2 = (rgb2 >> 8) & 0xff; + int b2 = rgb2 & 0xff; - int er = r1-r2; - int eg = g1-g2; - int eb = b1-b2; + int er = r1-r2; + int eg = g1-g2; + int eb = b1-b2; - for (int i = -1; i <= 1; i++) { - int iy = i+y; - if (0 <= iy && iy < height) { - for (int j = -1; j <= 1; j++) { - int jx = j+x; - if (0 <= jx && jx < width) { - int w; - if (reverse) - w = matrix[(i+1)*3-j+1]; - else - w = matrix[(i+1)*3+j+1]; - if (w != 0) { - int k = reverse ? index - j : index + j; - rgb1 = inPixels[k]; - r1 = (rgb1 >> 16) & 0xff; - g1 = (rgb1 >> 8) & 0xff; - b1 = rgb1 & 0xff; - r1 += er * w/sum; - g1 += eg * w/sum; - b1 += eb * w/sum; - inPixels[k] = (PixelUtils.clamp(r1) << 16) | (PixelUtils.clamp(g1) << 8) | PixelUtils.clamp(b1); - } - } - } - } - } - index += direction; - } - } - } - } + for (int i = -1; i <= 1; i++) { + int iy = i+y; + if (0 <= iy && iy < height) { + for (int j = -1; j <= 1; j++) { + int jx = j+x; + if (0 <= jx && jx < width) { + int w; + if (reverse) + w = matrix[(i+1)*3-j+1]; + else + w = matrix[(i+1)*3+j+1]; + if (w != 0) { + int k = reverse ? index - j : index + j; + rgb1 = inPixels[k]; + r1 = (rgb1 >> 16) & 0xff; + g1 = (rgb1 >> 8) & 0xff; + b1 = rgb1 & 0xff; + r1 += er * w/sum; + g1 += eg * w/sum; + b1 += eb * w/sum; + inPixels[k] = (PixelUtils.clamp(r1) << 16) | (PixelUtils.clamp(g1) << 8) | PixelUtils.clamp(b1); + } + } + } + } + } + index += direction; + } + } + } + } - protected int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace) { - int[] outPixels = new int[width*height]; + @Override + protected int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace) { + int[] outPixels = new int[width*height]; - quantize(inPixels, outPixels, width, height, numColors, dither, serpentine); + quantize(inPixels, outPixels, width, height, numColors, dither, serpentine); - return outPixels; - } + return outPixels; + } - public String toString() { - return "Colors/Quantize..."; - } + @Override + public String toString() { + return "Colors/Quantize..."; + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/Quantizer.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/Quantizer.java index d5eb36cc6..2aa6233d6 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/Quantizer.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/Quantizer.java @@ -22,32 +22,32 @@ package org.jivesoftware.smackx.jingleold.mediaimpl.sshare.api; * calling the buildColorTable method. */ public interface Quantizer { - /** - * Initialize the quantizer. This should be called before adding any pixels. - * @param numColors the number of colors we're quantizing to. - */ - public void setup(int numColors); + /** + * Initialize the quantizer. This should be called before adding any pixels. + * @param numColors the number of colors we're quantizing to. + */ + public void setup(int numColors); - /** - * Add pixels to the quantizer. - * @param pixels the array of ARGB pixels - * @param offset the offset into the array - * @param count the count of pixels - */ - public void addPixels(int[] pixels, int offset, int count); + /** + * Add pixels to the quantizer. + * @param pixels the array of ARGB pixels + * @param offset the offset into the array + * @param count the count of pixels + */ + public void addPixels(int[] pixels, int offset, int count); - /** - * Build a color table from the added pixels. - * @return an array of ARGB pixels representing a color table - */ - public int[] buildColorTable(); + /** + * Build a color table from the added pixels. + * @return an array of ARGB pixels representing a color table + */ + public int[] buildColorTable(); - /** - * Using the previously-built color table, return the index into that table for a pixel. - * This is guaranteed to return a valid index - returning the index of a color closer - * to that requested if necessary. - * @param rgb the pixel to find - * @return the pixel's index in the color table - */ - public int getIndexForColor(int rgb); + /** + * Using the previously-built color table, return the index into that table for a pixel. + * This is guaranteed to return a valid index - returning the index of a color closer + * to that requested if necessary. + * @param rgb the pixel to find + * @return the pixel's index in the color table + */ + public int getIndexForColor(int rgb); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/WholeImageFilter.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/WholeImageFilter.java index eb90e676a..2a435062d 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/WholeImageFilter.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/sshare/api/WholeImageFilter.java @@ -27,53 +27,54 @@ import java.awt.image.WritableRaster; */ public abstract class WholeImageFilter extends AbstractBufferedImageOp { - /** + /** * The output image bounds. */ protected Rectangle transformedSpace; - /** + /** * The input image bounds. */ - protected Rectangle originalSpace; + protected Rectangle originalSpace; - /** - * Construct a WholeImageFilter. - */ - public WholeImageFilter() { - } + /** + * Construct a WholeImageFilter. + */ + public WholeImageFilter() { + } + @Override public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); - int type = src.getType(); - WritableRaster srcRaster = src.getRaster(); + int type = src.getType(); + WritableRaster srcRaster = src.getRaster(); - originalSpace = new Rectangle(0, 0, width, height); - transformedSpace = new Rectangle(0, 0, width, height); - transformSpace(transformedSpace); + originalSpace = new Rectangle(0, 0, width, height); + transformedSpace = new Rectangle(0, 0, width, height); + transformSpace(transformedSpace); if (dst == null) { ColorModel dstCM = src.getColorModel(); - dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height), dstCM.isAlphaPremultiplied(), null); - } - WritableRaster dstRaster = dst.getRaster(); + dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height), dstCM.isAlphaPremultiplied(), null); + } + WritableRaster dstRaster = dst.getRaster(); - int[] inPixels = getRGB(src, 0, 0, width, height, null); - inPixels = filterPixels(width, height, inPixels, transformedSpace); - setRGB(dst, 0, 0, transformedSpace.width, transformedSpace.height, inPixels); + int[] inPixels = getRGB(src, 0, 0, width, height, null); + inPixels = filterPixels(width, height, inPixels, transformedSpace); + setRGB(dst, 0, 0, transformedSpace.width, transformedSpace.height, inPixels); return dst; } - /** + /** * Calculate output bounds for given input bounds. * @param rect input and output rectangle */ - protected void transformSpace(Rectangle rect) { - } + protected void transformSpace(Rectangle rect) { + } - /** + /** * Actually filter the pixels. * @param width the image width * @param height the image height @@ -81,6 +82,6 @@ public abstract class WholeImageFilter extends AbstractBufferedImageOp { * @param transformedSpace the output bounds * @return the output pixels */ - protected abstract int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace); + protected abstract int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaManager.java index 4fe57ff33..dfcf47066 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaManager.java @@ -49,6 +49,7 @@ public class TestMediaManager extends JingleMediaManager { * * @return The Payload List */ + @Override public List getPayloads() { return payloads; } @@ -65,6 +66,7 @@ public class TestMediaManager extends JingleMediaManager { * @param local local Candidate * @return JingleMediaSession JingleMediaSession */ + @Override public JingleMediaSession createMediaSession(PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, final JingleSession jingleSession) { TestMediaSession session = null; @@ -74,6 +76,7 @@ public class TestMediaManager extends JingleMediaManager { return session; } + @Override public PayloadType getPreferredPayloadType() { if (preferredPayloadType != null) return preferredPayloadType; @@ -84,6 +87,7 @@ public class TestMediaManager extends JingleMediaManager { this.preferredPayloadType = preferredPayloadType; } + @Override public String getName() { return MEDIA_NAME; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaSession.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaSession.java index 8e9cc30a9..5f12b71b4 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaSession.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/test/TestMediaSession.java @@ -45,6 +45,7 @@ public class TestMediaSession extends JingleMediaSession { /** * Initialize the screen share channels. */ + @Override public void initialize() { } @@ -52,6 +53,7 @@ public class TestMediaSession extends JingleMediaSession { /** * Starts transmission and for NAT Traversal reasons start receiving also. */ + @Override public void startTrasmit() { } @@ -62,6 +64,7 @@ public class TestMediaSession extends JingleMediaSession { * * @param active active state */ + @Override public void setTrasmit(boolean active) { } @@ -69,6 +72,7 @@ public class TestMediaSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void startReceive() { // Do nothing } @@ -76,6 +80,7 @@ public class TestMediaSession extends JingleMediaSession { /** * Stops transmission and for NAT Traversal reasons stop receiving also. */ + @Override public void stopTrasmit() { } @@ -83,6 +88,7 @@ public class TestMediaSession extends JingleMediaSession { /** * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf */ + @Override public void stopReceive() { } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicResolver.java index fc3fbf968..53cf0d765 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicResolver.java @@ -50,6 +50,7 @@ public class BasicResolver extends TransportResolver { * @throws NotConnectedException * @throws InterruptedException */ + @Override public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException { setResolveInit(); @@ -115,10 +116,12 @@ public class BasicResolver extends TransportResolver { } + @Override public void initialize() throws XMPPException { setInitialized(); } + @Override public void cancel() throws XMPPException { // Nothing to do here } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicTransportManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicTransportManager.java index cf4e7dcda..40435b57e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicTransportManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BasicTransportManager.java @@ -24,6 +24,7 @@ import org.jivesoftware.smackx.jingleold.JingleSession; */ public class BasicTransportManager extends JingleTransportManager{ + @Override protected TransportResolver createResolver(JingleSession session) { return new BasicResolver(); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedResolver.java index 8b38f9d0e..a6f2d8f69 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedResolver.java @@ -65,6 +65,7 @@ public class BridgedResolver extends TransportResolver { * @throws NotConnectedException * @throws InterruptedException */ + @Override public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException { setResolveInit(); @@ -102,6 +103,7 @@ public class BridgedResolver extends TransportResolver { setResolveEnd(); } + @Override public void initialize() throws SmackException, XMPPErrorException, InterruptedException { clearCandidates(); @@ -114,6 +116,7 @@ public class BridgedResolver extends TransportResolver { } + @Override public void cancel() throws XMPPException { // Nothing to do here } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedTransportManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedTransportManager.java index 8769f49c1..020563579 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedTransportManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/BridgedTransportManager.java @@ -46,6 +46,7 @@ public class BridgedTransportManager extends JingleTransportManager implements J * @param session correspondent Jingle Session * @return resolver */ + @Override protected TransportResolver createResolver(JingleSession session) { BridgedResolver bridgedResolver = new BridgedResolver(this.xmppConnection); return bridgedResolver; @@ -53,28 +54,35 @@ public class BridgedTransportManager extends JingleTransportManager implements J // Implement a Session Listener to relay candidates after establishment + @Override public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) throws NotConnectedException, InterruptedException { RTPBridge rtpBridge = RTPBridge.relaySession(lc.getConnection(), lc.getSessionId(), lc.getPassword(), rc, lc); } + @Override public void sessionDeclined(String reason, JingleSession jingleSession) { } + @Override public void sessionRedirected(String redirection, JingleSession jingleSession) { } + @Override public void sessionClosed(String reason, JingleSession jingleSession) { } + @Override public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) { } + @Override public void sessionMediaReceived(JingleSession jingleSession, String participant) { // Do Nothing } // Session Created + @Override public void sessionCreated(JingleSession jingleSession) { jingleSession.addListener(this); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedResolver.java index 9c6867fd5..e525e3138 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedResolver.java @@ -54,6 +54,7 @@ public class FixedResolver extends TransportResolver { * @throws NotConnectedException * @throws InterruptedException */ + @Override public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException { if (!isResolving()) { setResolveInit(); @@ -76,10 +77,12 @@ public class FixedResolver extends TransportResolver { * * @throws XMPPException */ + @Override public void initialize() throws XMPPException { setInitialized(); } + @Override public void cancel() throws XMPPException { // Nothing to do here } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedTransportManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedTransportManager.java index c7bb5c625..11381af64 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedTransportManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/FixedTransportManager.java @@ -34,29 +34,37 @@ public class FixedTransportManager extends JingleTransportManager implements Jin resolver = inResolver; } + @Override protected TransportResolver createResolver(JingleSession session) { return resolver; } + @Override public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) { } + @Override public void sessionDeclined(String reason, JingleSession jingleSession) { } + @Override public void sessionRedirected(String redirection, JingleSession jingleSession) { } + @Override public void sessionClosed(String reason, JingleSession jingleSession) { } + @Override public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) { } + @Override public void sessionMediaReceived(JingleSession jingleSession, String participant) { // Do Nothing } + @Override public void sessionCreated(JingleSession jingleSession) { jingleSession.addListener(this); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/HttpServer.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/HttpServer.java index a4207fb99..8bafc18cb 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/HttpServer.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/HttpServer.java @@ -27,14 +27,16 @@ import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; +import org.jivesoftware.smack.util.StringUtils; + /** * A very Simple HTTP Server. */ public class HttpServer { - private static final Logger LOGGER = Logger.getLogger(HttpServer.class.getName()); + private static final Logger LOGGER = Logger.getLogger(HttpServer.class.getName()); - public HttpServer(int port) { + public HttpServer(int port) { ServerSocket server_socket; try { @@ -73,7 +75,7 @@ public class HttpServer { HttpServer httpServer = new HttpServer(Integer.parseInt(args[0])); } - class HttpRequestHandler implements Runnable { + static class HttpRequestHandler implements Runnable { final static String CRLF = "\r\n"; Socket socket; @@ -85,9 +87,10 @@ public class HttpServer { this.socket = socket; this.input = socket.getInputStream(); this.output = socket.getOutputStream(); - this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); + this.br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StringUtils.UTF8)); } + @Override public void run() { try { processRequest(); @@ -115,19 +118,19 @@ public class HttpServer { String contentLengthLine; String statusLine = "HTTP/1.0 200 OK" + CRLF; contentLengthLine = "Content-Length: " - + (new Integer(entityBody.length())).toString() + CRLF; + + entityBody.length() + CRLF; contentTypeLine = "text/html"; - output.write(statusLine.getBytes()); + output.write(statusLine.getBytes(StringUtils.UTF8)); - output.write(serverLine.getBytes()); + output.write(serverLine.getBytes(StringUtils.UTF8)); - output.write(contentTypeLine.getBytes()); - output.write(contentLengthLine.getBytes()); + output.write(contentTypeLine.getBytes(StringUtils.UTF8)); + output.write(contentLengthLine.getBytes(StringUtils.UTF8)); - output.write(CRLF.getBytes()); + output.write(CRLF.getBytes(StringUtils.UTF8)); - output.write(entityBody.getBytes()); + output.write(entityBody.getBytes(StringUtils.UTF8)); } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICECandidate.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICECandidate.java index 20b37e068..58b65413c 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICECandidate.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICECandidate.java @@ -32,9 +32,9 @@ import java.util.logging.Logger; */ public class ICECandidate extends TransportCandidate implements Comparable { - private static final Logger LOGGER = Logger.getLogger(ICECandidate.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ICECandidate.class.getName()); - private String id; // An identification + private String id; // An identification private String username; @@ -219,6 +219,7 @@ public class ICECandidate extends TransportCandidate implements Comparable * ICE Candidate can check connectivity using UDP echo Test. */ + @Override public void check(final List localCandidates) { //TODO candidate is being checked trigger //candidatesChecking.add(cand); @@ -226,6 +227,7 @@ public class ICECandidate extends TransportCandidate implements Comparable arg.getPreference()) { - return 1; - } - return 0; - } + @Override + public int compareTo(ICECandidate arg) { + if (getPreference() < arg.getPreference()) { + return -1; + } else if (getPreference() > arg.getPreference()) { + return 1; + } + return 0; + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICEResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICEResolver.java index 7d001ca67..daefe386f 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICEResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICEResolver.java @@ -45,7 +45,7 @@ import de.javawi.jstun.util.UtilityException; */ public class ICEResolver extends TransportResolver { - private static final Logger LOGGER = Logger.getLogger(ICEResolver.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ICEResolver.class.getName()); XMPPConnection connection; Random random = new Random(); @@ -63,6 +63,7 @@ public class ICEResolver extends TransportResolver { this.setType(Type.ice); } + @Override public void initialize() throws XMPPException { if (!isResolving() && !isResolved()) { LOGGER.fine("Initialized"); @@ -73,13 +74,13 @@ public class ICEResolver extends TransportResolver { // of the STUN server are much, much faster. if (negociatorsMap.get(server) == null) { // CHECKSTYLE:OFF - ICENegociator iceNegociator = new ICENegociator(server, port, (short) 1); - negociatorsMap.put(server, iceNegociator); + ICENegociator iceNegociator = new ICENegociator(server, port, (short) 1); + negociatorsMap.put(server, iceNegociator); - // gather candidates - iceNegociator.gatherCandidateAddresses(); - // priorize candidates - iceNegociator.prioritizeCandidates(); + // gather candidates + iceNegociator.gatherCandidateAddresses(); + // priorize candidates + iceNegociator.prioritizeCandidates(); // CHECKSTYLE:ON } @@ -87,6 +88,7 @@ public class ICEResolver extends TransportResolver { this.setInitialized(); } + @Override public void cancel() throws XMPPException { } @@ -96,6 +98,7 @@ public class ICEResolver extends TransportResolver { * @throws SmackException * @throws InterruptedException */ + @Override public synchronized void resolve(JingleSession session) throws XMPPException, SmackException, InterruptedException { this.setResolveInit(); @@ -125,21 +128,21 @@ public class ICEResolver extends TransportResolver { // JBW/GW - 17JUL08: Figure out the zero-based NIC number for this candidate. short nicNum = 0; - try { - Enumeration nics = NetworkInterface.getNetworkInterfaces(); - short i = 0; - NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress()); - while(nics.hasMoreElements()) { - NetworkInterface checkNIC = nics.nextElement(); - if (checkNIC.equals(nic)) { - nicNum = i; - break; - } - i++; - } - } catch (SocketException e1) { - LOGGER.log(Level.WARNING, "exeption", e1); - } + try { + Enumeration nics = NetworkInterface.getNetworkInterfaces(); + short i = 0; + NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress()); + while(nics.hasMoreElements()) { + NetworkInterface checkNIC = nics.nextElement(); + if (checkNIC.equals(nic)) { + nicNum = i; + break; + } + i++; + } + } catch (SocketException e1) { + LOGGER.log(Level.WARNING, "exeption", e1); + } TransportCandidate transportCandidate = new ICECandidate(candidate.getAddress().getInetAddress().getHostAddress(), 1, nicNum, String.valueOf(Math.abs(random.nextLong())), candidate.getPort(), "1", candidate.getPriority(), iceType); transportCandidate.setLocalIp(candidate.getBase().getAddress().getInetAddress().getHostAddress()); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICETransportManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICETransportManager.java index a9825050f..ce9f72a83 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICETransportManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/ICETransportManager.java @@ -27,6 +27,7 @@ import org.jivesoftware.smackx.jingleold.JingleSession; import org.jivesoftware.smackx.jingleold.listeners.CreatedJingleSessionListener; import org.jivesoftware.smackx.jingleold.listeners.JingleSessionListener; import org.jivesoftware.smackx.jingleold.media.PayloadType; +import org.jivesoftware.smackx.jingleold.nat.ICECandidate.Type; public class ICETransportManager extends JingleTransportManager implements JingleSessionListener, CreatedJingleSessionListener { private static final Logger LOGGER = Logger.getLogger(ICETransportManager.class.getName()); @@ -43,6 +44,7 @@ public class ICETransportManager extends JingleTransportManager implements Jingl } } + @Override protected TransportResolver createResolver(JingleSession session) throws SmackException, InterruptedException { try { iceResolver.resolve(session); @@ -55,32 +57,39 @@ public class ICETransportManager extends JingleTransportManager implements Jingl // Implement a Session Listener to relay candidates after establishment + @Override public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) throws NotConnectedException, InterruptedException { if (lc instanceof ICECandidate) { - if (((ICECandidate) lc).getType().equals("relay")) { + if (((ICECandidate) lc).getType().equals(Type.relay)) { RTPBridge rtpBridge = RTPBridge.relaySession(lc.getConnection(), lc.getSessionId(), lc.getPassword(), rc, lc); } } } + @Override public void sessionDeclined(String reason, JingleSession jingleSession) { } + @Override public void sessionRedirected(String redirection, JingleSession jingleSession) { } + @Override public void sessionClosed(String reason, JingleSession jingleSession) { } + @Override public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) { } + @Override public void sessionMediaReceived(JingleSession jingleSession, String participant) { // Do Nothing } // Session Created + @Override public void sessionCreated(JingleSession jingleSession) { jingleSession.addListener(this); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/RTPBridge.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/RTPBridge.java index 92028b613..918bd0f2f 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/RTPBridge.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/RTPBridge.java @@ -52,9 +52,9 @@ import org.xmlpull.v1.XmlPullParserException; */ public class RTPBridge extends IQ { - private static final Logger LOGGER = Logger.getLogger(RTPBridge.class.getName()); + private static final Logger LOGGER = Logger.getLogger(RTPBridge.class.getName()); - private String sid; + private String sid; private String pass; private String ip; private String name; @@ -303,6 +303,7 @@ public class RTPBridge extends IQ { * * @return the Child Element XML of the Packet */ + @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder str) { str.attribute("sid", sid); str.rightAngleBracket(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUN.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUN.java index 51dee98ef..005c1a42a 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUN.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUN.java @@ -46,9 +46,9 @@ import org.xmlpull.v1.XmlPullParserException; */ public class STUN extends SimpleIQ { - private static final Logger LOGGER = Logger.getLogger(STUN.class.getName()); + private static final Logger LOGGER = Logger.getLogger(STUN.class.getName()); - private List servers = new ArrayList(); + private List servers = new ArrayList(); private String publicIp = null; diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNResolver.java index a55e3f43e..b72537212 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNResolver.java @@ -46,9 +46,9 @@ import de.javawi.jstun.test.DiscoveryTest; */ public class STUNResolver extends TransportResolver { - private static final Logger LOGGER = Logger.getLogger(STUNResolver.class.getName()); + private static final Logger LOGGER = Logger.getLogger(STUNResolver.class.getName()); - // The filename where the STUN servers are stored. + // The filename where the STUN servers are stored. public final static String STUNSERVERS_FILENAME = "META-INF/stun-config.xml"; // Current STUN server we are using @@ -87,6 +87,7 @@ public class STUNResolver extends TransportResolver { * * @see TransportResolver#isResolving() */ + @Override public boolean isResolving() { return super.isResolving() && resolverThread != null; } @@ -266,6 +267,7 @@ public class STUNResolver extends TransportResolver { * @throws NotConnectedException * @throws InterruptedException */ + @Override public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException { setResolveInit(); @@ -289,6 +291,7 @@ public class STUNResolver extends TransportResolver { * * @throws XMPPException */ + @Override public void initialize() throws XMPPException { LOGGER.fine("Initialized"); if (!isResolving()&&!isResolved()) { @@ -302,6 +305,7 @@ public class STUNResolver extends TransportResolver { clearCandidates(); resolverThread = new Thread(new Runnable() { + @Override public void run() { // Iterate through the list of interfaces, and ask // to the STUN server for our address. @@ -386,6 +390,7 @@ public class STUNResolver extends TransportResolver { * * @see TransportResolver#cancel() */ + @Override public synchronized void cancel() throws XMPPException { if (isResolving()) { resolverThread.interrupt(); @@ -398,6 +403,7 @@ public class STUNResolver extends TransportResolver { * * @see TransportResolver#clear() */ + @Override public synchronized void clear() throws XMPPException { this.defaultPort = 0; super.clear(); @@ -406,7 +412,7 @@ public class STUNResolver extends TransportResolver { /** * STUN service definition. */ - protected class STUNService { + protected static class STUNService { private String hostname; // The hostname of the service diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNTransportManager.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNTransportManager.java index d3cf9030c..ce15c201d 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNTransportManager.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/STUNTransportManager.java @@ -41,6 +41,7 @@ public class STUNTransportManager extends JingleTransportManager { } } + @Override protected TransportResolver createResolver(JingleSession session) { try { stunResolver.resolve(session); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeClient.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeClient.java index fa9c11502..881cbff70 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeClient.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeClient.java @@ -33,9 +33,9 @@ import java.util.logging.Logger; */ public class TcpUdpBridgeClient { - private static final Logger LOGGER = Logger.getLogger(TcpUdpBridgeClient.class.getName()); + private static final Logger LOGGER = Logger.getLogger(TcpUdpBridgeClient.class.getName()); - private String remoteTcpHost = null; + private String remoteTcpHost = null; private String remoteUdpHost = null; private int remoteTcpPort = -1; private int remoteUdpPort = -1; @@ -67,6 +67,7 @@ public class TcpUdpBridgeClient { final Thread process = new Thread(new Runnable() { + @Override public void run() { try { OutputStream out = localTcpSocket.getOutputStream(); @@ -97,6 +98,7 @@ public class TcpUdpBridgeClient { new Thread(new Runnable() { + @Override public void run() { try { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeServer.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeServer.java index 79e72febb..92270d56b 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeServer.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TcpUdpBridgeServer.java @@ -35,9 +35,9 @@ import java.util.logging.Logger; */ public class TcpUdpBridgeServer { - private static final Logger LOGGER = Logger.getLogger(TcpUdpBridgeServer.class.getName()); + private static final Logger LOGGER = Logger.getLogger(TcpUdpBridgeServer.class.getName()); - private String remoteTcpHost = null; + private String remoteTcpHost = null; private String remoteUdpHost = null; private int remoteTcpPort = -1; private int remoteUdpPort = -1; @@ -69,6 +69,7 @@ public class TcpUdpBridgeServer { final Thread process = new Thread(new Runnable() { + @Override public void run() { try { OutputStream out = localTcpSocket.getOutputStream(); @@ -98,6 +99,7 @@ public class TcpUdpBridgeServer { new Thread(new Runnable() { + @Override public void run() { try { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportCandidate.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportCandidate.java index 9f5d4a94c..00aacda32 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportCandidate.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportCandidate.java @@ -47,9 +47,9 @@ import org.jxmpp.jid.Jid; @SuppressWarnings("EqualsHashCode") public abstract class TransportCandidate { - private static final Logger LOGGER = Logger.getLogger(TransportCandidate.class.getName()); + private static final Logger LOGGER = Logger.getLogger(TransportCandidate.class.getName()); - private String name; + private String name; private String ip; // IP address @@ -301,6 +301,7 @@ public abstract class TransportCandidate { * * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -353,13 +354,14 @@ public abstract class TransportCandidate { //candidatesChecking.add(cand); Thread checkThread = new Thread(new Runnable() { + @Override public void run() { boolean isUsable; try { // CHECKSTYLE:OFF - InetAddress candAddress = InetAddress.getByName(getIp()); + InetAddress candAddress = InetAddress.getByName(getIp()); // CHECKSTYLE:ON isUsable = true;//candAddress.isReachable(TransportResolver.CHECK_TIMEOUT); } @@ -463,6 +465,7 @@ public abstract class TransportCandidate { this.value = value; } + @Override public String toString() { return value; } @@ -551,6 +554,7 @@ public abstract class TransportCandidate { this.value = value; } + @Override public String toString() { return value; } @@ -664,6 +668,7 @@ public abstract class TransportCandidate { } + @Override public void run() { try { LOGGER.fine("Listening for ECHO: " + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort()); @@ -756,9 +761,11 @@ public abstract class TransportCandidate { Thread thread = new Thread(new Runnable() { + @Override public void run() { DatagramListener listener = new DatagramListener() { + @Override public boolean datagramReceived(DatagramPacket datagramPacket) { try { @@ -771,8 +778,8 @@ public abstract class TransportCandidate { // CHECKSTYLE:OFF if (pass.equals(password) - && transportCandidate.getIp().indexOf(ip) != -1 - && transportCandidate.getPort() == Integer.parseInt(pt)) { + && transportCandidate.getIp().indexOf(ip) != -1 + && transportCandidate.getPort() == Integer.parseInt(pt)) { // CHECKSTYLE:ON LOGGER.fine("ECHO OK: " + candidate.getIp() + ":" + candidate.getPort() + " <-> " + transportCandidate.getIp() + ":" + transportCandidate.getPort()); TestResult testResult = new TestResult(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportNegotiator.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportNegotiator.java index 731e527b0..f5d66908a 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportNegotiator.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportNegotiator.java @@ -36,6 +36,7 @@ import org.jivesoftware.smackx.jingleold.JingleNegotiatorState; import org.jivesoftware.smackx.jingleold.JingleSession; import org.jivesoftware.smackx.jingleold.listeners.JingleListener; import org.jivesoftware.smackx.jingleold.listeners.JingleTransportListener; +import org.jivesoftware.smackx.jingleold.nat.ICECandidate.Type; import org.jivesoftware.smackx.jingleold.packet.Jingle; import org.jivesoftware.smackx.jingleold.packet.JingleContent; import org.jivesoftware.smackx.jingleold.packet.JingleTransport; @@ -52,9 +53,9 @@ import org.jivesoftware.smackx.jingleold.packet.JingleTransport.JingleTransportC */ public abstract class TransportNegotiator extends JingleNegotiator { - private static final Logger LOGGER = Logger.getLogger(TransportNegotiator.class.getName()); + private static final Logger LOGGER = Logger.getLogger(TransportNegotiator.class.getName()); - // The time we give to the candidates check before we accept or decline the + // The time we give to the candidates check before we accept or decline the // transport (in milliseconds) public final static int CANDIDATES_ACCEPT_PERIOD = 4000; @@ -158,6 +159,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { /** * Called from above to start the negotiator during a session-initiate. */ + @Override protected void doStart() { try { @@ -173,6 +175,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { /** * Called from above to session-terminate. */ + @Override public void close() { super.close(); @@ -246,6 +249,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { */ private void checkRemoteCandidate(final TransportCandidate offeredCandidate) { offeredCandidate.addListener(new TransportResolverListener.Checker() { + @Override public void candidateChecked(TransportCandidate cand, final boolean validCandidate) { if (validCandidate) { if (getNegotiatorState() == JingleNegotiatorState.PENDING) @@ -253,6 +257,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { } } + @Override public void candidateChecking(TransportCandidate cand) { } @@ -292,6 +297,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { if (resultThread == null && !getRemoteCandidates().isEmpty()) { resultThread = new Thread(new Runnable() { + @Override public void run() { // Sleep for some time, waiting for the candidates checks @@ -351,7 +357,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { for (TransportCandidate candidate : remoteCandidates) { if (candidate instanceof ICECandidate) { ICECandidate iceCandidate = (ICECandidate) candidate; - if (iceCandidate.getType().equals("relay")) { + if (iceCandidate.getType().equals(Type.relay)) { //TODO Check if the relay is reacheable addValidRemoteCandidate(iceCandidate); foundRemoteRelay = true; @@ -366,7 +372,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { for (TransportCandidate candidate : offeredCandidates) { if (candidate instanceof ICECandidate) { ICECandidate iceCandidate = (ICECandidate) candidate; - if (iceCandidate.getType().equals("relay")) { + if (iceCandidate.getType().equals(Type.relay)) { foundLocalRelay = true; } } @@ -565,13 +571,16 @@ public abstract class TransportNegotiator extends JingleNegotiator { if (resolverListener == null) { // Add a listener that sends the offer when the resolver finishes... resolverListener = new TransportResolverListener.Resolver() { + @Override public void candidateAdded(TransportCandidate cand) throws NotConnectedException, InterruptedException { sendTransportCandidateOffer(cand); } + @Override public void end() { } + @Override public void init() { } }; @@ -597,6 +606,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { * @throws SmackException * @throws InterruptedException */ + @Override public final List dispatchIncomingPacket(IQ iq, String id) throws XMPPException, SmackException, InterruptedException { List responses = new ArrayList(); IQ response = null; @@ -838,6 +848,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { /** * Get a TransportNegotiator instance. */ + @Override public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate bestRemote) { org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp(); jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp.Candidate(bestRemote)); @@ -850,6 +861,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { * * @return the bestRemoteCandidate */ + @Override public TransportCandidate getBestRemoteCandidate() { // Hopefully, we only have one validRemoteCandidate ArrayList cands = getValidRemoteCandidatesList(); @@ -865,6 +877,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { /** * Return true for fixed candidates. */ + @Override public boolean acceptableTransportCandidate(TransportCandidate tc, List localCandidates) { return tc instanceof TransportCandidate.Fixed; } @@ -892,6 +905,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { * * @param candidate */ + @Override public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate candidate) { org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice(); jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice.Candidate(candidate)); @@ -903,6 +917,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { * * @return the bestRemoteCandidate */ + @Override public TransportCandidate getBestRemoteCandidate() { ICECandidate result = null; @@ -911,18 +926,18 @@ public abstract class TransportNegotiator extends JingleNegotiator { int highest = -1; ICECandidate chose = null; for (TransportCandidate transportCandidate : cands) { - if (transportCandidate instanceof ICECandidate) { - ICECandidate icecandidate = (ICECandidate) transportCandidate; - if (icecandidate.getPreference() > highest) { - chose = icecandidate; - highest = icecandidate.getPreference(); - } + if (transportCandidate instanceof ICECandidate) { + ICECandidate icecandidate = (ICECandidate) transportCandidate; + if (icecandidate.getPreference() > highest) { + chose = icecandidate; + highest = icecandidate.getPreference(); + } } } result = chose; } - if (result != null && result.getType().equals("relay")) + if (result != null && result.getType().equals(Type.relay)) LOGGER.fine("Relay Type"); return result; @@ -931,6 +946,7 @@ public abstract class TransportNegotiator extends JingleNegotiator { /** * Return true for ICE candidates. */ + @Override public boolean acceptableTransportCandidate(TransportCandidate tc, List localCandidates) { return tc instanceof ICECandidate; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportResolver.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportResolver.java index 3ce8370e6..99fef19dd 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportResolver.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/TransportResolver.java @@ -40,9 +40,9 @@ import org.jivesoftware.smackx.jingleold.JingleSession; */ public abstract class TransportResolver { - private static final Logger LOGGER = Logger.getLogger(TransportResolver.class.getName()); + private static final Logger LOGGER = Logger.getLogger(TransportResolver.class.getName()); - public enum Type { + public enum Type { rawupd, ice } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/Jingle.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/Jingle.java index 7dfe93a3e..353f91ffa 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/Jingle.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/Jingle.java @@ -70,7 +70,7 @@ public class Jingle extends IQ { this(); if (contents != null) { - contents.addAll(contents); + this.contents.addAll(contents); } setContentInfo(mi); @@ -343,6 +343,7 @@ public class Jingle extends IQ { * * @return the XML string */ + @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) { if (getInitiator() != null) { buf.append(" initiator=\"").append(getInitiator()).append('"'); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContent.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContent.java index 9f0380139..875eae08e 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContent.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContent.java @@ -62,6 +62,7 @@ public class JingleContent implements ExtensionElement { * * @return the XML element name of the element. */ + @Override public String getElementName() { return NODENAME; } @@ -71,6 +72,7 @@ public class JingleContent implements ExtensionElement { * * @return The namespace */ + @Override public String getNamespace() { // There is no namespace for return ""; @@ -157,6 +159,7 @@ public class JingleContent implements ExtensionElement { * * @return a string with the XML representation */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentDescription.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentDescription.java index e9759404b..8d94447cd 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentDescription.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentDescription.java @@ -51,6 +51,7 @@ public abstract class JingleContentDescription implements ExtensionElement { * * @return the XML element name of the element. */ + @Override public String getElementName() { return NODENAME; } @@ -60,6 +61,7 @@ public abstract class JingleContentDescription implements ExtensionElement { * * @return The namespace */ + @Override public abstract String getNamespace(); /** @@ -144,6 +146,7 @@ public abstract class JingleContentDescription implements ExtensionElement { * * @return a string with the XML representation */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); @@ -183,6 +186,7 @@ public abstract class JingleContentDescription implements ExtensionElement { addJinglePayloadType(pt); } + @Override public String getNamespace() { return NAMESPACE; } @@ -279,16 +283,17 @@ public abstract class JingleContentDescription implements ExtensionElement { super(audio); } + @Override protected String getChildAttributes() { StringBuilder buf = new StringBuilder(); PayloadType pt = getPayloadType(); if (pt instanceof PayloadType.Audio) { - PayloadType.Audio pta = (PayloadType.Audio) pt; + PayloadType.Audio pta = (PayloadType.Audio) pt; - buf.append(" clockrate=\"").append(pta.getClockRate()).append("\" "); - } - return buf.toString(); - } - } - } + buf.append(" clockrate=\"").append(pta.getClockRate()).append("\" "); + } + return buf.toString(); + } + } + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentInfo.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentInfo.java index b37ee5831..179e945df 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentInfo.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleContentInfo.java @@ -59,6 +59,7 @@ public class JingleContentInfo implements ExtensionElement { /** * Get the element name. */ + @Override public String getElementName() { // Media info is supposed to be just a single-word command... return getMediaInfo().toString(); @@ -76,10 +77,12 @@ public class JingleContentInfo implements ExtensionElement { /** * Get the publilc namespace. */ + @Override public String getNamespace() { return namespace; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(getElementName()).append(" xmlns=\""); @@ -100,6 +103,7 @@ public class JingleContentInfo implements ExtensionElement { setNamespace(NAMESPACE); } + @Override public String getNamespace() { return NAMESPACE; } @@ -148,7 +152,7 @@ public class JingleContentInfo implements ExtensionElement { public static class Ringing extends Audio { public Ringing() { super(ContentInfo.Audio.RINGING); - } - } - } + } + } + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java index aedc1a7b3..d76935671 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java @@ -32,9 +32,9 @@ import org.jivesoftware.smackx.jingleold.media.PayloadType; */ public abstract class JingleDescription implements ExtensionElement { - private static final Logger LOGGER = Logger.getLogger(JingleDescription.class.getName()); + private static final Logger LOGGER = Logger.getLogger(JingleDescription.class.getName()); - // static + // static public static final String NODENAME = "description"; @@ -54,6 +54,7 @@ public abstract class JingleDescription implements ExtensionElement { * * @return the XML element name of the element. */ + @Override public String getElementName() { return NODENAME; } @@ -63,6 +64,7 @@ public abstract class JingleDescription implements ExtensionElement { * * @return The namespace */ + @Override public abstract String getNamespace(); /** @@ -151,6 +153,7 @@ public abstract class JingleDescription implements ExtensionElement { * * @return a string with the XML representation */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); @@ -190,6 +193,7 @@ public abstract class JingleDescription implements ExtensionElement { addPayloadType(pt); } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleError.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleError.java index e7b22110b..f169bda7b 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleError.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleError.java @@ -73,6 +73,7 @@ public class JingleError implements ExtensionElement { * * @return the error as XML. */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); if (message != null) { @@ -110,17 +111,20 @@ public class JingleError implements ExtensionElement { return null; } + @Override public String toString() { return getMessage(); } + @Override public String getElementName() { return message; } + @Override public String getNamespace() { - return NAMESPACE; - } + return NAMESPACE; + } public static class Provider extends ExtensionElementProvider { diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleTransport.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleTransport.java index c525d5194..d9ac2f0e2 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleTransport.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleTransport.java @@ -123,6 +123,7 @@ public class JingleTransport implements ExtensionElement { * * @return the XML element name of the element. */ + @Override public String getElementName() { return NODENAME; } @@ -141,6 +142,7 @@ public class JingleTransport implements ExtensionElement { * * @return The namespace */ + @Override public String getNamespace() { return namespace; } @@ -148,6 +150,7 @@ public class JingleTransport implements ExtensionElement { /** * Return the XML representation for this element. */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); @@ -278,6 +281,7 @@ public class JingleTransport implements ExtensionElement { * * @see org.jivesoftware.smackx.jingleold.packet.JingleTransport#addCandidate(org.jivesoftware.smackx.jingleold.packet.JingleTransport.JingleTransportCandidate) */ + @Override public void addCandidate(final JingleTransportCandidate candidate) { super.addCandidate(candidate); } @@ -288,6 +292,7 @@ public class JingleTransport implements ExtensionElement { * * @see org.jivesoftware.smackx.jingleold.packet.JingleTransport#getCandidates() */ + @Override public List getCandidatesList() { List copy = new ArrayList(); List superCandidatesList = super.getCandidatesList(); @@ -316,6 +321,7 @@ public class JingleTransport implements ExtensionElement { /** * Get the elements of this candidate. */ + @Override protected String getChildElements() { StringBuilder buf = new StringBuilder(); @@ -360,6 +366,7 @@ public class JingleTransport implements ExtensionElement { * * @see org.jivesoftware.smackx.jingleold.packet.JingleTransport#addCandidate(org.jivesoftware.smackx.jingleold.packet.JingleTransport.JingleTransportCandidate) */ + @Override public void addCandidate(final JingleTransportCandidate candidate) { candidates.clear(); super.addCandidate(candidate); @@ -371,6 +378,7 @@ public class JingleTransport implements ExtensionElement { * * @see org.jivesoftware.smackx.jingleold.packet.JingleTransport#getCandidates() */ + @Override public List getCandidatesList() { List copy = new ArrayList(); List superCandidatesList = super.getCandidatesList(); @@ -402,6 +410,7 @@ public class JingleTransport implements ExtensionElement { /** * Get the elements of this candidate. */ + @Override protected String getChildElements() { StringBuilder buf = new StringBuilder(); diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentDescriptionProvider.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentDescriptionProvider.java index 51b1b6d43..d95a47b19 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentDescriptionProvider.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentDescriptionProvider.java @@ -108,6 +108,7 @@ public abstract class JingleContentDescriptionProvider extends ExtensionElementP /** * Parse an audio payload type. */ + @Override public JinglePayloadType parsePayload(final XmlPullParser parser) { JinglePayloadType pte = super.parsePayload(parser); PayloadType.Audio pt = new PayloadType.Audio(pte.getPayloadType()); @@ -125,8 +126,9 @@ public abstract class JingleContentDescriptionProvider extends ExtensionElementP /** * Get a new instance of this object. */ + @Override protected JingleContentDescription getInstance() { return new JingleContentDescription.Audio(); - } - } + } + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentInfoProvider.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentInfoProvider.java index 72c9d8681..6c5bed356 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentInfoProvider.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleContentInfoProvider.java @@ -103,7 +103,7 @@ public class JingleContentInfoProvider { public static class Ringing extends Audio { public Ringing() { super(new JingleContentInfo.Audio.Ringing()); - } - } - } + } + } + } } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleDescriptionProvider.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleDescriptionProvider.java index 2adf66960..01b8f6c1a 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleDescriptionProvider.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleDescriptionProvider.java @@ -69,6 +69,7 @@ public abstract class JingleDescriptionProvider extends ExtensionElementProvider * @throws IOException * @throws XmlPullParserException */ + @Override public JingleDescription parse(XmlPullParser parser, int initialDepth) throws SmackException, XmlPullParserException, IOException { boolean done = false; JingleDescription desc = getInstance(); @@ -106,6 +107,7 @@ public abstract class JingleDescriptionProvider extends ExtensionElementProvider /** * Parse an audio payload type. */ + @Override public PayloadType parsePayload(final XmlPullParser parser) { PayloadType pte = super.parsePayload(parser); PayloadType.Audio pt = new PayloadType.Audio(pte); @@ -123,6 +125,7 @@ public abstract class JingleDescriptionProvider extends ExtensionElementProvider /** * Get a new instance of this object. */ + @Override protected JingleDescription getInstance() { return new JingleDescription.Audio(); } diff --git a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleTransportProvider.java b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleTransportProvider.java index fff7aebe4..0038910b0 100644 --- a/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleTransportProvider.java +++ b/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/provider/JingleTransportProvider.java @@ -99,6 +99,7 @@ public abstract class JingleTransportProvider extends ExtensionElementProvider userPresences = presenceMap.get(jid); + Jid j; + try { + j = JidCreate.from(jid); + } + catch (XmppStringprepException e) { + throw new IllegalStateException(e); + } + Map userPresences = presenceMap.get(j); if (userPresences != null) { Iterator presences = userPresences.values().iterator(); while (presences.hasNext()) { @@ -175,6 +183,7 @@ public class AgentRoster { * or "user@domain/resource"). * @return true if the XMPP address is an agent in the workgroup. */ + @SuppressWarnings("EqualsIncompatibleType") public boolean contains(Jid jid) { if (jid == null) { return false; @@ -282,7 +291,9 @@ public class AgentRoster { /** * Listens for all presence packets and processes them. */ + @SuppressWarnings("EqualsIncompatibleType") private class PresencePacketListener implements StanzaListener { + @Override public void processStanza(Stanza packet) { Presence presence = (Presence)packet; EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible(); @@ -359,6 +370,7 @@ public class AgentRoster { */ private class AgentStatusListener implements StanzaListener { + @Override public void processStanza(Stanza packet) { if (packet instanceof AgentStatusRequest) { AgentStatusRequest statusRequest = (AgentStatusRequest)packet; @@ -369,9 +381,14 @@ public class AgentRoster { // Removing the user from the roster, so remove any presence information // about them. - String key = XmppStringUtils.parseLocalpart(XmppStringUtils.parseLocalpart(agentJID) + "@" + - XmppStringUtils.parseDomain(agentJID)); - presenceMap.remove(key); + Jid agentJid; + try { + agentJid = JidCreate.from(agentJID); + } + catch (XmppStringprepException e) { + throw new IllegalStateException(e); + } + presenceMap.remove(agentJid.asBareJid()); // Fire event for roster listeners. fireEvent(EVENT_AGENT_REMOVED, agentJID); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java index 7572d2d46..297b39779 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java @@ -77,6 +77,7 @@ import org.jivesoftware.smackx.workgroup.settings.SearchSettings; import org.jivesoftware.smackx.xdata.Form; import org.jxmpp.jid.Jid; import org.jxmpp.jid.parts.Resourcepart; +import org.jxmpp.stringprep.XmppStringprepException; /** * This class embodies the agent's active presence within a given workgroup. The application @@ -147,6 +148,7 @@ public class AgentSession { new StanzaTypeFilter(Message.class)); packetListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { try { handlePacket(packet); @@ -609,6 +611,23 @@ public class AgentSession { * @return an instance of WorkgroupQueue for the argument queue name, or null if none exists */ public WorkgroupQueue getQueue(String queueName) { + Resourcepart queueNameResourcepart; + try { + queueNameResourcepart = Resourcepart.from(queueName); + } + catch (XmppStringprepException e) { + throw new IllegalArgumentException(e); + } + return getQueue(queueNameResourcepart); + } + + /** + * Get queue. + * + * @param queueName the name of the queue + * @return an instance of WorkgroupQueue for the argument queue name, or null if none exists + */ + public WorkgroupQueue getQueue(Resourcepart queueName) { return queues.get(queueName); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/InvitationRequest.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/InvitationRequest.java index d88c0feb7..6da5b6a63 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/InvitationRequest.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/InvitationRequest.java @@ -46,14 +46,17 @@ public class InvitationRequest extends OfferContent { return reason; } + @Override boolean isUserRequest() { return false; } + @Override boolean isInvitation() { return true; } + @Override boolean isTransfer() { return false; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/OfferConfirmation.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/OfferConfirmation.java index 191e6f53f..1d953ef6e 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/OfferConfirmation.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/OfferConfirmation.java @@ -98,7 +98,7 @@ public class OfferConfirmation extends SimpleIQ { /** * Stanza(/Packet) for notifying server of RoomName */ - private class NotifyServicePacket extends IQ { + private static class NotifyServicePacket extends IQ { String roomName; NotifyServicePacket(Jid workgroup, String roomName) { diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TransferRequest.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TransferRequest.java index 0f491d04c..15fda70f9 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TransferRequest.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TransferRequest.java @@ -46,14 +46,17 @@ public class TransferRequest extends OfferContent { return reason; } + @Override boolean isUserRequest() { return false; } + @Override boolean isInvitation() { return false; } + @Override boolean isTransfer() { return true; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/UserRequest.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/UserRequest.java index d5a098577..c7016a432 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/UserRequest.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/UserRequest.java @@ -30,14 +30,17 @@ public class UserRequest extends OfferContent { return instance; } + @Override boolean isUserRequest() { return true; } + @Override boolean isInvitation() { return false; } + @Override boolean isTransfer() { return false; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/WorkgroupQueue.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/WorkgroupQueue.java index f2c0e61d2..951cb8784 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/WorkgroupQueue.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/WorkgroupQueue.java @@ -221,6 +221,7 @@ public class WorkgroupQueue { this.value = value; } + @Override public String toString() { return value; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatus.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatus.java index 164d9de44..c1ee92d39 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatus.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatus.java @@ -80,14 +80,17 @@ public class AgentStatus implements ExtensionElement { return maxChats; } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MetaDataProvider.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MetaDataProvider.java index 516e6a4cf..e09c372bf 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MetaDataProvider.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MetaDataProvider.java @@ -39,6 +39,7 @@ public class MetaDataProvider extends ExtensionElementProvider { * @throws IOException * @throws XmlPullParserException */ + @Override public MetaData parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException { Map> metaData = MetaDataUtils.parseMetaData(parser); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/OfferRevokeProvider.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/OfferRevokeProvider.java index bdca48492..aca307ec0 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/OfferRevokeProvider.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/OfferRevokeProvider.java @@ -67,7 +67,7 @@ public class OfferRevokeProvider extends IQProvider { return new OfferRevokePacket(userJID, userID, reason, sessionID); } - public class OfferRevokePacket extends IQ { + public static class OfferRevokePacket extends IQ { public static final String ELEMENT = "offer-revoke"; public static final String NAMESPACE = "http://jabber.org/protocol/workgroup"; diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueDetails.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueDetails.java index 9b5595e53..2a415ec2e 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueDetails.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueDetails.java @@ -91,14 +91,17 @@ public final class QueueDetails implements ExtensionElement { } } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">"); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueOverview.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueOverview.java index 64aa88005..24460301c 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueOverview.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueOverview.java @@ -88,14 +88,17 @@ public class QueueOverview implements ExtensionElement { this.status = status; } + @Override public String getElementName () { return ELEMENT_NAME; } + @Override public String getNamespace () { return NAMESPACE; } + @Override public String toXML () { StringBuilder buf = new StringBuilder(); buf.append('<').append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">"); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueUpdate.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueUpdate.java index 4b1fe9645..caf16e45a 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueUpdate.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/QueueUpdate.java @@ -69,6 +69,7 @@ public class QueueUpdate implements ExtensionElement { return remainingTime; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append(""); @@ -82,10 +83,12 @@ public class QueueUpdate implements ExtensionElement { return buf.toString(); } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomInvitation.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomInvitation.java index d9fb98f4e..fe83f34f0 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomInvitation.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomInvitation.java @@ -80,10 +80,12 @@ public class RoomInvitation implements ExtensionElement { private RoomInvitation() { } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomTransfer.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomTransfer.java index b56b54a9a..dc4fc2430 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomTransfer.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/RoomTransfer.java @@ -80,10 +80,12 @@ public class RoomTransfer implements ExtensionElement { private RoomTransfer() { } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/SessionID.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/SessionID.java index e8cd700bb..5740a1d3a 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/SessionID.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/SessionID.java @@ -46,14 +46,17 @@ public class SessionID implements ExtensionElement { return this.sessionID; } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/UserID.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/UserID.java index ba2ecee0a..67c0ea947 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/UserID.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/UserID.java @@ -48,14 +48,17 @@ public class UserID implements ExtensionElement { return this.userID; } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/WorkgroupInformation.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/WorkgroupInformation.java index 9250d45e4..13c34a800 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/WorkgroupInformation.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/WorkgroupInformation.java @@ -50,14 +50,17 @@ public class WorkgroupInformation implements ExtensionElement { return workgroupJID; } + @Override public String getElementName() { return ELEMENT_NAME; } + @Override public String getNamespace() { return NAMESPACE; } + @Override public String toXML() { StringBuilder buf = new StringBuilder(); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/WorkgroupProperties.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/WorkgroupProperties.java index 9a94f6d8a..326225197 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/WorkgroupProperties.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/WorkgroupProperties.java @@ -103,7 +103,7 @@ public class WorkgroupProperties extends IQ { while (!done) { int eventType = parser.next(); if ((eventType == XmlPullParser.START_TAG) && ("authRequired".equals(parser.getName()))) { - props.setAuthRequired(new Boolean(parser.nextText()).booleanValue()); + props.setAuthRequired(Boolean.valueOf(parser.nextText()).booleanValue()); } else if ((eventType == XmlPullParser.START_TAG) && ("email".equals(parser.getName()))) { props.setEmail(parser.nextText()); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/user/Workgroup.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/user/Workgroup.java index 4b0e737e6..338715788 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/user/Workgroup.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/user/Workgroup.java @@ -58,7 +58,7 @@ import org.jivesoftware.smackx.workgroup.settings.WorkgroupProperties; import org.jivesoftware.smackx.xdata.Form; import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.packet.DataForm; -import org.jxmpp.jid.EntityFullJid; +import org.jxmpp.jid.EntityJid; import org.jxmpp.jid.DomainBareJid; import org.jxmpp.jid.Jid; @@ -108,20 +108,24 @@ public class Workgroup { // Register as a queue listener for internal usage by this instance. addQueueListener(new QueueListener() { + @Override public void joinedQueue() { inQueue = true; } + @Override public void departedQueue() { inQueue = false; queuePosition = -1; queueRemainingTime = -1; } + @Override public void queuePositionUpdated(int currentPosition) { queuePosition = currentPosition; } + @Override public void queueWaitTimeUpdated(int secondsRemaining) { queueRemainingTime = secondsRemaining; } @@ -133,7 +137,7 @@ public class Workgroup { MultiUserChatManager.getInstanceFor(connection).addInvitationListener( new org.jivesoftware.smackx.muc.InvitationListener() { @Override - public void invitationReceived(XMPPConnection conn, org.jivesoftware.smackx.muc.MultiUserChat room, EntityFullJid inviter, + public void invitationReceived(XMPPConnection conn, org.jivesoftware.smackx.muc.MultiUserChat room, EntityJid inviter, String reason, String password, Message message, MUCUser.Invite invitation) { inQueue = false; queuePosition = -1; @@ -145,6 +149,7 @@ public class Workgroup { StanzaFilter typeFilter = new StanzaTypeFilter(Message.class); connection.addAsyncStanzaListener(new StanzaListener() { + @Override public void processStanza(Stanza packet) { handlePacket(packet); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/ListenerEventDispatcher.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/ListenerEventDispatcher.java index 979423330..0c42e2a6e 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/ListenerEventDispatcher.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/ListenerEventDispatcher.java @@ -84,6 +84,7 @@ public class ListenerEventDispatcher implements Runnable { return this.hasFinishedDispatching; } + @Override public void run() { ListIterator li = null; @@ -104,7 +105,7 @@ public class ListenerEventDispatcher implements Runnable { } - protected class TripletContainer { + protected static class TripletContainer { protected Object listenerInstance; protected Method listenerMethod; diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/DefaultMessageEventRequestListener.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/DefaultMessageEventRequestListener.java index 7bd7c96ac..8f71e4be1 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/DefaultMessageEventRequestListener.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/DefaultMessageEventRequestListener.java @@ -31,6 +31,7 @@ import org.jxmpp.jid.Jid; */ public class DefaultMessageEventRequestListener implements MessageEventRequestListener { + @Override public void deliveredNotificationRequested(Jid from, String packetID, MessageEventManager messageEventManager) throws NotConnectedException, InterruptedException { @@ -38,16 +39,19 @@ public class DefaultMessageEventRequestListener implements MessageEventRequestLi messageEventManager.sendDeliveredNotification(from, packetID); } + @Override public void displayedNotificationRequested(Jid from, String packetID, MessageEventManager messageEventManager) { } + @Override public void composingNotificationRequested(Jid from, String packetID, MessageEventManager messageEventManager) { } + @Override public void offlineNotificationRequested(Jid from, String packetID, MessageEventManager messageEventManager) { diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java index 61cf22d2d..6e18bd5d2 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java @@ -77,6 +77,7 @@ public final class MessageEventManager extends Manager { super(connection); // Listens for all message event packets and fire the proper message event listeners. connection.addAsyncStanzaListener(new StanzaListener() { + @Override public void processStanza(Stanza packet) { Message message = (Message) packet; MessageEvent messageEvent = diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/packet/MessageEvent.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/packet/MessageEvent.java index 81dd8ca3a..bccc21a89 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/packet/MessageEvent.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/packet/MessageEvent.java @@ -78,6 +78,7 @@ public class MessageEvent implements ExtensionElement { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return ELEMENT; } @@ -88,6 +89,7 @@ public class MessageEvent implements ExtensionElement { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return NAMESPACE; } @@ -303,6 +305,7 @@ public class MessageEvent implements ExtensionElement { * * */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java index a84c8b2fa..fb2eda00a 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java @@ -51,9 +51,9 @@ public class RemoteRosterEntry { public RemoteRosterEntry(Jid user, String name, String [] groups) { this.user = user; this.name = name; - if (groups != null) { + if (groups != null) { groupNames.addAll(Arrays.asList(groups)); - } + } } /** diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java index 506e02c93..fbc6e068d 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java @@ -78,6 +78,7 @@ public class RosterExchangeManager { weakRefConnection = new WeakReference(connection); // Listens for all roster exchange packets and fire the roster exchange listeners. packetListener = new StanzaListener() { + @Override public void processStanza(Stanza packet) { Message message = (Message) packet; RosterExchange rosterExchange = diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/packet/RosterExchange.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/packet/RosterExchange.java index 3cec05ebd..8940a1dbe 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/packet/RosterExchange.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/packet/RosterExchange.java @@ -78,13 +78,13 @@ public class RosterExchange implements ExtensionElement { * @param rosterEntry a roster entry to add. */ public void addRosterEntry(RosterEntry rosterEntry) { - // Obtain a String[] from the roster entry groups name - List groupNamesList = new ArrayList(); - String[] groupNames; - for (RosterGroup group : rosterEntry.getGroups()) { - groupNamesList.add(group.getName()); - } - groupNames = groupNamesList.toArray(new String[groupNamesList.size()]); + // Obtain a String[] from the roster entry groups name + List groupNamesList = new ArrayList(); + String[] groupNames; + for (RosterGroup group : rosterEntry.getGroups()) { + groupNamesList.add(group.getName()); + } + groupNames = groupNamesList.toArray(new String[groupNamesList.size()]); // Create a new Entry based on the rosterEntry and add it to the packet RemoteRosterEntry remoteRosterEntry = new RemoteRosterEntry(rosterEntry.getJid(), @@ -110,6 +110,7 @@ public class RosterExchange implements ExtensionElement { * * @return the XML element name of the stanza(/packet) extension. */ + @Override public String getElementName() { return RosterExchangeManager.ELEMENT; } @@ -121,6 +122,7 @@ public class RosterExchange implements ExtensionElement { * * @return the XML namespace of the stanza(/packet) extension. */ + @Override public String getNamespace() { return RosterExchangeManager.NAMESPACE; } @@ -163,6 +165,7 @@ public class RosterExchange implements ExtensionElement { * * */ + @Override public String toXML() { StringBuilder buf = new StringBuilder(); buf.append('<').append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( diff --git a/smack-resolver-javax/src/main/java/org/jivesoftware/smack/util/dns/javax/JavaxResolver.java b/smack-resolver-javax/src/main/java/org/jivesoftware/smack/util/dns/javax/JavaxResolver.java index 7de7b911e..9ebec30a2 100644 --- a/smack-resolver-javax/src/main/java/org/jivesoftware/smack/util/dns/javax/JavaxResolver.java +++ b/smack-resolver-javax/src/main/java/org/jivesoftware/smack/util/dns/javax/JavaxResolver.java @@ -1,6 +1,6 @@ /** * - * Copyright 2013-2016 Florian Schmaus + * Copyright 2013-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,9 @@ import java.net.InetAddress; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; +import java.util.logging.Level; +import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; @@ -80,15 +82,26 @@ public class JavaxResolver extends DNSResolver implements SmackInitializer { @Override protected List lookupSRVRecords0(String name, List failedAddresses, DnssecMode dnssecMode) { - List res = new ArrayList(); + List res = null; + Attribute srvAttribute; try { Attributes dnsLookup = dirContext.getAttributes(name, new String[] { "SRV" }); - Attribute srvAttribute = dnsLookup.get("SRV"); + srvAttribute = dnsLookup.get("SRV"); if (srvAttribute == null) - return res; + return null; + } catch (NameNotFoundException e) { + LOGGER.log(Level.FINEST, "No DNS SRV RR found for " + name, e); + return null; + } catch (NamingException e) { + LOGGER.log(Level.WARNING, "Exception while resolving DNS SRV RR for " + name, e); + return null; + } + + try { @SuppressWarnings("unchecked") NamingEnumeration srvRecords = (NamingEnumeration) srvAttribute.getAll(); + res = new ArrayList<>(); while (srvRecords.hasMore()) { String srvRecordString = srvRecords.next(); String[] srvRecordEntries = srvRecordString.split(" "); @@ -107,7 +120,7 @@ public class JavaxResolver extends DNSResolver implements SmackInitializer { } } catch (NamingException e) { - throw new IllegalStateException(e); + LOGGER.log(Level.SEVERE, "Exception while resolving DNS SRV RR for" + name, e); } return res; diff --git a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLCramMD5Mechanism.java b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLCramMD5Mechanism.java index 25aded104..48a3fca1f 100644 --- a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLCramMD5Mechanism.java +++ b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLCramMD5Mechanism.java @@ -25,6 +25,7 @@ public class SASLCramMD5Mechanism extends SASLJavaXMechanism { public static final String NAME = CRAMMD5; + @Override public String getName() { return NAME; } diff --git a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Mechanism.java b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Mechanism.java index 39d7dc430..c574edddd 100644 --- a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Mechanism.java +++ b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Mechanism.java @@ -30,6 +30,7 @@ public class SASLDigestMD5Mechanism extends SASLJavaXMechanism { return true; } + @Override public String getName() { return NAME; } diff --git a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLPlainMechanism.java b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLPlainMechanism.java index 278d60f1d..4e8a878d0 100644 --- a/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLPlainMechanism.java +++ b/smack-sasl-javax/src/main/java/org/jivesoftware/smack/sasl/javax/SASLPlainMechanism.java @@ -25,6 +25,7 @@ public class SASLPlainMechanism extends SASLJavaXMechanism { public static final String NAME = PLAIN; + @Override public String getName() { return NAME; } diff --git a/smack-sasl-javax/src/test/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Test.java b/smack-sasl-javax/src/test/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Test.java index bb2aac7c5..988267e18 100644 --- a/smack-sasl-javax/src/test/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Test.java +++ b/smack-sasl-javax/src/test/java/org/jivesoftware/smack/sasl/javax/SASLDigestMD5Test.java @@ -1,6 +1,6 @@ /** * - * Copyright 2014 Florian Schmaus + * Copyright 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ */ package org.jivesoftware.smack.sasl.javax; +import java.io.UnsupportedEncodingException; + import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.sasl.DigestMd5SaslTest; @@ -29,12 +31,12 @@ public class SASLDigestMD5Test extends DigestMd5SaslTest { } @Test - public void testDigestMD5() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException { + public void testDigestMD5() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException, UnsupportedEncodingException { runTest(false); } @Test - public void testDigestMD5Authzid() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException { + public void testDigestMD5Authzid() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException, UnsupportedEncodingException { runTest(true); } } diff --git a/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Mechanism.java b/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Mechanism.java index 47d0513a0..723256838 100644 --- a/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Mechanism.java +++ b/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Mechanism.java @@ -16,6 +16,8 @@ */ package org.jivesoftware.smack.sasl.provided; +import java.io.UnsupportedEncodingException; + import javax.security.auth.callback.CallbackHandler; import org.jivesoftware.smack.SmackException; @@ -101,7 +103,14 @@ public class SASLDigestMD5Mechanism extends SASLMechanism { if (challenge.length == 0) { throw new SmackException("Initial challenge has zero length"); } - String[] challengeParts = (new String(challenge)).split(","); + String challengeString; + try { + challengeString = new String(challenge, StringUtils.UTF8); + } + catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + String[] challengeParts = challengeString.split(","); byte[] response = null; switch (state) { case INITIAL: diff --git a/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLProvidedSmackInitializer.java b/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLProvidedSmackInitializer.java index 849ccbc15..ad30919a5 100644 --- a/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLProvidedSmackInitializer.java +++ b/smack-sasl-provided/src/main/java/org/jivesoftware/smack/sasl/provided/SASLProvidedSmackInitializer.java @@ -23,12 +23,12 @@ import org.jivesoftware.smack.initializer.SmackInitializer; public class SASLProvidedSmackInitializer implements SmackInitializer { - @Override - public List initialize() { - SASLAuthentication.registerSASLMechanism(new SASLDigestMD5Mechanism()); - SASLAuthentication.registerSASLMechanism(new SASLExternalMechanism()); - SASLAuthentication.registerSASLMechanism(new SASLPlainMechanism()); - return null; - } + @Override + public List initialize() { + SASLAuthentication.registerSASLMechanism(new SASLDigestMD5Mechanism()); + SASLAuthentication.registerSASLMechanism(new SASLExternalMechanism()); + SASLAuthentication.registerSASLMechanism(new SASLPlainMechanism()); + return null; + } } diff --git a/smack-sasl-provided/src/test/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Test.java b/smack-sasl-provided/src/test/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Test.java index c68eb346c..6d1413272 100644 --- a/smack-sasl-provided/src/test/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Test.java +++ b/smack-sasl-provided/src/test/java/org/jivesoftware/smack/sasl/provided/SASLDigestMD5Test.java @@ -16,6 +16,8 @@ */ package org.jivesoftware.smack.sasl.provided; +import java.io.UnsupportedEncodingException; + import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.sasl.DigestMd5SaslTest; @@ -28,12 +30,14 @@ public class SASLDigestMD5Test extends DigestMd5SaslTest { } @Test - public void testDigestMD5() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException { + public void testDigestMD5() throws NotConnectedException, SmackException, InterruptedException, + XmppStringprepException, UnsupportedEncodingException { runTest(false); } @Test - public void testDigestMD5Authzid() throws NotConnectedException, SmackException, InterruptedException, XmppStringprepException { + public void testDigestMD5Authzid() throws NotConnectedException, SmackException, InterruptedException, + XmppStringprepException, UnsupportedEncodingException { runTest(true); } } diff --git a/smack-tcp/src/main/java/org/jivesoftware/smack/tcp/XMPPTCPConnection.java b/smack-tcp/src/main/java/org/jivesoftware/smack/tcp/XMPPTCPConnection.java index 92a2ba631..2b3665886 100644 --- a/smack-tcp/src/main/java/org/jivesoftware/smack/tcp/XMPPTCPConnection.java +++ b/smack-tcp/src/main/java/org/jivesoftware/smack/tcp/XMPPTCPConnection.java @@ -707,7 +707,7 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { try { Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class); String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library(); - ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes()); + ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8)); Provider p = (Provider)c.newInstance(config); Security.addProvider(p); ks = KeyStore.getInstance("PKCS11",p); @@ -991,6 +991,7 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { done = false; Async.go(new Runnable() { + @Override public void run() { parsePackets(); }