diff --git a/.gitignore b/.gitignore index 8eeb443be..989af3d92 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ # IntelliJ .idea *.iml +*.ipr +*.iws # Mac OS X .DS_Store diff --git a/.travis.yml b/.travis.yml index 41f447858..969285456 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,7 +10,7 @@ cache: - $HOME/.m2 before_install: - - export GRADLE_VERSION=2.12 + - export GRADLE_VERSION=3.5 - wget https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-all.zip - unzip -q gradle-${GRADLE_VERSION}-all.zip - export PATH="$(pwd)/gradle-${GRADLE_VERSION}/bin:$PATH" @@ -19,6 +19,6 @@ install: gradle assemble --stacktrace script: gradle check --stacktrace after_success: -- JAVAC_VERSION=$((javac -version) 2>&1) -# Only run jacocoRootReport in the Java7 build -- if [[ "$JAVAC_VERSION" = javac\ 1.7.* ]]; then gradle jacocoRootReport coveralls; fi + - JAVAC_VERSION=$((javac -version) 2>&1) + # Only run jacocoRootReport in the Java 8 build + - if [[ "$JAVAC_VERSION" = javac\ 1.8.* ]]; then gradle jacocoRootReport coveralls; fi diff --git a/build.gradle b/build.gradle index 92a62e572..9ca176231 100644 --- a/build.gradle +++ b/build.gradle @@ -8,9 +8,9 @@ buildscript { } dependencies { classpath 'org.kordamp:markdown-gradle-plugin:1.0.0' - classpath 'org.kordamp.gradle:clirr-gradle-plugin:0.2.0' + classpath 'org.kordamp.gradle:clirr-gradle-plugin:0.2.2' classpath "org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.3.1" - classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.9' + classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.10' } } apply plugin: 'org.kordamp.gradle.markdown' @@ -20,6 +20,7 @@ apply from: 'version.gradle' allprojects { apply plugin: 'java' apply plugin: 'eclipse' + apply plugin: 'idea' apply plugin: 'jacoco' apply plugin: 'net.ltgt.errorprone' @@ -266,6 +267,7 @@ subprojects { checkstyle { configFile = new File(rootConfigDir, 'checkstyle.xml') + toolVersion = '7.7' } task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' diff --git a/config/checkstyle.xml b/config/checkstyle.xml index ce2345c20..d5ce5464e 100644 --- a/config/checkstyle.xml +++ b/config/checkstyle.xml @@ -117,5 +117,75 @@ , INDEX_OP "/> + + + + + + + + diff --git a/documentation/extensions/index.md b/documentation/extensions/index.md index 325fcf30a..05ffa0b5c 100644 --- a/documentation/extensions/index.md +++ b/documentation/extensions/index.md @@ -87,6 +87,7 @@ Experimental Smack Extensions and currently supported XEPs of smack-experimental | [Internet of Things - Control](iot.md) | [XEP-0325](http://xmpp.org/extensions/xep-0325.html) | Describes how to control devices or actuators in an XMPP-based sensor netowrk. | | [HTTP over XMPP transport](hoxt.md) | [XEP-0332](http://xmpp.org/extensions/xep-0332.html) | Allows to transport HTTP communication over XMPP peer-to-peer networks. | | Chat Markers | [XEP-0333](http://xmpp.org/extensions/xep-0333.html) | A solution of marking the last received, displayed and acknowledged message in a chat. | +| Message Processing Hints | [XEP-0334](http://xmpp.org/extensions/xep-0334.html) | Hints to entities routing or receiving a message. | | JSON Containers | [XEP-0335](http://xmpp.org/extensions/xep-0335.html) | Encapsulation of JSON data within XMPP Stanzas. | | [Internet of Things - Discovery](iot.md) | [XEP-0347](http://xmpp.org/extensions/xep-0347.html) | Describes how Things can be installed and discovered by their owners. | | Client State Indication | [XEP-0352](http://xmpp.org/extensions/xep-0352.html) | A way for the client to indicate its active/inactive state. | 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 b91bb5a40..32edb865f 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 @@ -325,7 +325,7 @@ public class XMPPBOSHConnection extends AbstractXMPPConnection { writer = new Writer() { @Override public void write(char[] cbuf, int off, int len) { - /* ignore */} + /* ignore */ } @Override public void close() { 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 32b3ada5e..dc467b043 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/AbstractXMPPConnection.java @@ -41,6 +41,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; +import org.jivesoftware.smack.SmackConfiguration.UnknownIqRequestReplyMode; import org.jivesoftware.smack.SmackException.AlreadyConnectedException; import org.jivesoftware.smack.SmackException.AlreadyLoggedInException; import org.jivesoftware.smack.SmackException.NoResponseException; @@ -626,7 +627,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { hostAddresses = DNSUtil.resolveXMPPServiceDomain(config.getXMPPServiceDomain().toString(), failedAddresses, config.getDnssecMode()); } // Either the populated host addresses are not empty *or* there must be at least one failed address. - assert(!hostAddresses.isEmpty() || !failedAddresses.isEmpty()); + assert (!hostAddresses.isEmpty() || !failedAddresses.isEmpty()); return failedAddresses; } @@ -665,7 +666,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { @Override public void sendStanza(Stanza stanza) throws NotConnectedException, InterruptedException { Objects.requireNonNull(stanza, "Stanza must not be null"); - assert(stanza instanceof Message || stanza instanceof Presence || stanza instanceof IQ); + assert (stanza instanceof Message || stanza instanceof Presence || stanza instanceof IQ); throwNotConnectedExceptionIfAppropriate(); switch (fromMode) { @@ -894,7 +895,8 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { continue; } } - }}); + } + }); } @Override @@ -991,20 +993,31 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { replyTimeout = timeout; } - private static boolean replyToUnknownIqDefault = true; - /** * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured * default is 'true'. * * @param replyToUnkownIqDefault * @see #setReplyToUnknownIq(boolean) + * @deprecated Use {@link SmackConfiguration#setUnknownIqRequestReplyMode(org.jivesoftware.smack.SmackConfiguration.UnknownIqRequestReplyMode)} instead. */ + @Deprecated + // TODO Remove in Smack 4.3 public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) { - AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault; + SmackConfiguration.UnknownIqRequestReplyMode mode; + if (replyToUnkownIqDefault) { + mode = SmackConfiguration.UnknownIqRequestReplyMode.replyServiceUnavailable; + } else { + mode = SmackConfiguration.UnknownIqRequestReplyMode.doNotReply; + } + SmackConfiguration.setUnknownIqRequestReplyMode(mode); } - private boolean replyToUnkownIq = replyToUnknownIqDefault; + private SmackConfiguration.UnknownIqRequestReplyMode unknownIqRequestReplyMode = SmackConfiguration.getUnknownIqRequestReplyMode(); + + public void setUnknownIqRequestReplyMode(UnknownIqRequestReplyMode unknownIqRequestReplyMode) { + this.unknownIqRequestReplyMode = Objects.requireNonNull(unknownIqRequestReplyMode, "Mode must not be null"); + } /** * Set if Smack will automatically send @@ -1012,9 +1025,18 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { * registered {@link IQRequestHandler} is received. * * @param replyToUnknownIq + * @deprecated use {@link #setUnknownIqRequestReplyMode(UnknownIqRequestReplyMode)} instead. */ + @Deprecated + // TODO Remove in Smack 4.3 public void setReplyToUnknownIq(boolean replyToUnknownIq) { - this.replyToUnkownIq = replyToUnknownIq; + SmackConfiguration.UnknownIqRequestReplyMode mode; + if (replyToUnknownIq) { + mode = SmackConfiguration.UnknownIqRequestReplyMode.replyServiceUnavailable; + } else { + mode = SmackConfiguration.UnknownIqRequestReplyMode.doNotReply; + } + unknownIqRequestReplyMode = mode; } protected void parseAndProcessStanza(XmlPullParser parser) throws Exception { @@ -1048,7 +1070,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { * @throws InterruptedException */ protected void processStanza(final Stanza stanza) throws InterruptedException { - assert(stanza != null); + assert (stanza != null); lastStanzaReceived = System.currentTimeMillis(); // Deliver the incoming packet to listeners. executorService.executeBlocking(new Runnable() { @@ -1089,13 +1111,24 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'"); } if (iqRequestHandler == null) { - if (!replyToUnkownIq) { + XMPPError.Condition replyCondition; + switch (unknownIqRequestReplyMode) { + case doNotReply: return; + case replyFeatureNotImplemented: + replyCondition = XMPPError.Condition.feature_not_implemented; + break; + case replyServiceUnavailable: + replyCondition = XMPPError.Condition.service_unavailable; + break; + default: + throw new AssertionError(); } + // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an // IQ of type 'error' with condition 'service-unavailable'. ErrorIQ errorIQ = IQ.createErrorResponse(iq, XMPPError.getBuilder(( - XMPPError.Condition.service_unavailable))); + replyCondition))); try { sendStanza(errorIQ); } @@ -1170,7 +1203,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { } // Loop through all collectors and notify the appropriate ones. - for (StanzaCollector collector: collectors) { + for (StanzaCollector collector : collectors) { collector.processStanza(packet); } @@ -1192,7 +1225,7 @@ public abstract class AbstractXMPPConnection implements XMPPConnection { for (StanzaListener listener : listenersToNotify) { try { listener.processStanza(packet); - } catch(NotConnectedException e) { + } catch (NotConnectedException e) { LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e); break; } catch (Exception e) { 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 55f76798a..ff35a6968 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java @@ -162,7 +162,7 @@ public abstract class ConnectionConfiguration { enabledSaslMechanisms = builder.enabledSaslMechanisms; // If the enabledSaslmechanisms are set, then they must not be empty - assert(enabledSaslMechanisms != null ? !enabledSaslMechanisms.isEmpty() : true); + assert (enabledSaslMechanisms != null ? !enabledSaslMechanisms.isEmpty() : true); if (dnssecMode != DnssecMode.disabled && customSSLContext != null) { throw new IllegalStateException("You can not use a custom SSL context with DNSSEC enabled"); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java b/smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java index 2a0f76119..137e07110 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java @@ -132,13 +132,13 @@ public final class SASLAuthentication { } public static boolean blacklistSASLMechanism(String mechansim) { - synchronized(BLACKLISTED_MECHANISMS) { + synchronized (BLACKLISTED_MECHANISMS) { return BLACKLISTED_MECHANISMS.add(mechansim); } } public static boolean unBlacklistSASLMechanism(String mechanism) { - synchronized(BLACKLISTED_MECHANISMS) { + synchronized (BLACKLISTED_MECHANISMS) { return BLACKLISTED_MECHANISMS.remove(mechanism); } } @@ -209,7 +209,7 @@ public final class SASLAuthentication { } } - if (saslException != null){ + if (saslException != null) { if (saslException instanceof SmackException) { throw (SmackException) saslException; } else if (saslException instanceof SASLErrorException) { diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SmackConfiguration.java b/smack-core/src/main/java/org/jivesoftware/smack/SmackConfiguration.java index 2e6770c7a..245e8f0e9 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/SmackConfiguration.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/SmackConfiguration.java @@ -34,6 +34,7 @@ import org.jivesoftware.smack.debugger.SmackDebugger; import org.jivesoftware.smack.debugger.SmackDebuggerFactory; import org.jivesoftware.smack.parsing.ExceptionThrowingCallback; import org.jivesoftware.smack.parsing.ParsingExceptionCallback; +import org.jivesoftware.smack.util.Objects; /** * Represents the configuration of Smack. The configuration is used for: @@ -173,7 +174,7 @@ public final class SmackConfiguration { * @param mech the SASL mechanism to be added */ public static void addSaslMech(String mech) { - if(!defaultMechs.contains(mech)) { + if (!defaultMechs.contains(mech)) { defaultMechs.add(mech); } } @@ -184,7 +185,7 @@ public final class SmackConfiguration { * @param mechs the Collection of SASL mechanisms to be added */ public static void addSaslMechs(Collection mechs) { - for(String mech : mechs) { + for (String mech : mechs) { addSaslMech(mech); } } @@ -370,4 +371,20 @@ public final class SmackConfiguration { return defaultHostnameVerififer; } + enum UnknownIqRequestReplyMode { + doNotReply, + replyFeatureNotImplemented, + replyServiceUnavailable, + } + + // TODO Change to replyFeatureNotImplemented in Smack 4.3 + private static UnknownIqRequestReplyMode unknownIqRequestReplyMode = UnknownIqRequestReplyMode.replyServiceUnavailable; + + public static UnknownIqRequestReplyMode getUnknownIqRequestReplyMode() { + return unknownIqRequestReplyMode; + } + + public static void setUnknownIqRequestReplyMode(UnknownIqRequestReplyMode unknownIqRequestReplyMode) { + SmackConfiguration.unknownIqRequestReplyMode = Objects.requireNonNull(unknownIqRequestReplyMode, "Must set mode"); + } } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SmackFuture.java b/smack-core/src/main/java/org/jivesoftware/smack/SmackFuture.java new file mode 100644 index 000000000..36dbda2cb --- /dev/null +++ b/smack-core/src/main/java/org/jivesoftware/smack/SmackFuture.java @@ -0,0 +1,170 @@ +/** + * + * 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; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.packet.Stanza; + +public abstract class SmackFuture implements Future { + + private boolean cancelled; + + private V result; + + protected Exception exception; + + private SuccessCallback successCallback; + + private ExceptionCallback exceptionCallback; + + @Override + public synchronized final boolean cancel(boolean mayInterruptIfRunning) { + if (isDone()) { + return false; + } + + cancelled = true; + return true; + } + + @Override + public synchronized final boolean isCancelled() { + return cancelled; + } + + @Override + public synchronized final boolean isDone() { + return result != null; + } + + public void onSuccessOrError(SuccessCallback successCallback, ExceptionCallback exceptionCallback) { + this.successCallback = successCallback; + this.exceptionCallback = exceptionCallback; + + maybeInvokeCallbacks(); + } + + public void onSuccess(SuccessCallback successCallback) { + onSuccessOrError(successCallback, null); + } + + public void onError(ExceptionCallback exceptionCallback) { + onSuccessOrError(null, exceptionCallback); + } + + private final V getResultOrThrow() throws ExecutionException { + assert (result != null || exception != null); + if (result != null) { + return result; + } + + throw new ExecutionException(exception); + } + + @Override + public synchronized final V get() throws InterruptedException, ExecutionException { + while (result == null && exception == null) { + wait(); + } + + return getResultOrThrow(); + } + + @Override + public synchronized final V get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + final long deadline = System.currentTimeMillis() + unit.toMillis(timeout); + while (result != null && exception != null) { + final long waitTimeRemaining = deadline - System.currentTimeMillis(); + if (waitTimeRemaining > 0) { + wait(waitTimeRemaining); + } + } + + if (result == null || exception == null) { + throw new TimeoutException(); + } + + return getResultOrThrow(); + } + + protected final synchronized void maybeInvokeCallbacks() { + if (result != null && successCallback != null) { + successCallback.onSuccess(result); + } else if (exception != null && exceptionCallback != null) { + exceptionCallback.processException(exception); + } + } + + /** + * This method checks if the given exception is not fatal. If this method returns false, then + * the future will automatically set the given exception as failure reason and notify potential waiting threads. + * + * @param exception the exception to check. + * @return true if the exception is not fatal, false otherwise. + */ + protected abstract boolean isNonFatalException(Exception exception); + + protected abstract void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException; + + protected final void setResult(V result) { + assert (Thread.holdsLock(this)); + + this.result = result; + this.notifyAll(); + + maybeInvokeCallbacks(); + } + + public static abstract class InternalSmackFuture extends SmackFuture implements StanzaListener, ExceptionCallback { + + @Override + public synchronized final void processException(Exception exception) { + if (!isNonFatalException(exception)) { + this.exception = exception; + this.notifyAll(); + + maybeInvokeCallbacks(); + } + } + + /** + * Wrapper method for {@link #handleStanza(Stanza)}. Note that this method is synchronized. + */ + @Override + public synchronized final void processStanza(Stanza stanza) throws NotConnectedException, InterruptedException { + handleStanza(stanza); + } + } + + /** + * A simple version of InternalSmackFuture which implements {@link #isNonFatalException(Exception)} as always returning false method. + * + * @param + */ + public static abstract class SimpleInternalSmackFuture extends InternalSmackFuture { + @Override + protected boolean isNonFatalException(Exception exception) { + return false; + } + } +} 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 7bdb8e18a..d7ac9410a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java @@ -68,7 +68,7 @@ public final class SmackInitialization { } catch (IOException e) { LOGGER.log(Level.WARNING, "IOException closing stream", e); } - } catch(Exception e) { + } catch (Exception e) { LOGGER.log(Level.SEVERE, "Could not determine Smack version", e); smackVersion = "unkown"; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SuccessCallback.java b/smack-core/src/main/java/org/jivesoftware/smack/SuccessCallback.java new file mode 100644 index 000000000..49106a9f1 --- /dev/null +++ b/smack-core/src/main/java/org/jivesoftware/smack/SuccessCallback.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.smack; + +public interface SuccessCallback { + + public void onSuccess(T result); + +} diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SynchronizationPoint.java b/smack-core/src/main/java/org/jivesoftware/smack/SynchronizationPoint.java index bb1984a1f..8906fc65e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/SynchronizationPoint.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/SynchronizationPoint.java @@ -79,7 +79,7 @@ public class SynchronizationPoint { if (request instanceof Stanza) { connection.sendStanza((Stanza) request); } - else if (request instanceof Nonza){ + else if (request instanceof Nonza) { connection.sendNonza((Nonza) request); } else { throw new IllegalStateException("Unsupported element type"); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/XMPPConnection.java b/smack-core/src/main/java/org/jivesoftware/smack/XMPPConnection.java index b8b8582bf..b22d004aa 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/XMPPConnection.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/XMPPConnection.java @@ -413,6 +413,7 @@ public interface XMPPConnection { * @deprecated use {@link #getReplyTimeout()} instead. */ @Deprecated + // TODO Remove in Smack 4.3 public long getPacketReplyTimeout(); /** @@ -423,6 +424,7 @@ public interface XMPPConnection { * @deprecated use {@link #setReplyTimeout(long)} instead. */ @Deprecated + // TODO Remove in Smack 4.3 public void setPacketReplyTimeout(long timeout); /** diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractJidTypeFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractJidTypeFilter.java index e091d6786..502c2951e 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractJidTypeFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractJidTypeFilter.java @@ -39,7 +39,7 @@ public abstract class AbstractJidTypeFilter implements StanzaFilter { @Override public final boolean accept(Stanza stanza) { - final Jid jid = stanza.getFrom(); + final Jid jid = getJidToInspect(stanza); if (jid == null) { return false; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractListFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractListFilter.java index 708d7b52f..d06ddad47 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractListFilter.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/AbstractListFilter.java @@ -45,7 +45,7 @@ public abstract class AbstractListFilter implements StanzaFilter { */ protected AbstractListFilter(StanzaFilter... filters) { Objects.requireNonNull(filters, "Parameter must not be null."); - for(StanzaFilter filter : filters) { + for (StanzaFilter filter : filters) { Objects.requireNonNull(filter, "Parameter must not be null."); } this.filters = new ArrayList(Arrays.asList(filters)); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/filter/MessageWithThreadFilter.java b/smack-core/src/main/java/org/jivesoftware/smack/filter/MessageWithThreadFilter.java new file mode 100644 index 000000000..81a5bc8ea --- /dev/null +++ b/smack-core/src/main/java/org/jivesoftware/smack/filter/MessageWithThreadFilter.java @@ -0,0 +1,43 @@ +/** + * + * 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.Message; +import org.jivesoftware.smack.util.StringUtils; + +/** + * Filters message stanzas which have at least one body. + */ +public final class MessageWithThreadFilter extends FlexibleStanzaTypeFilter { + + public static final StanzaFilter INSTANCE = new MessageWithThreadFilter(); + + private MessageWithThreadFilter() { + super(Message.class); + } + + @Override + protected boolean acceptSpecific(Message message) { + return StringUtils.isNotEmpty(message.getThread()); + } + + @Override + public String toString() { + return getClass().getSimpleName(); + } +} diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractError.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractError.java index 26e3daf69..d04c41ad3 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractError.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractError.java @@ -67,7 +67,10 @@ public class AbstractError { String defaultLocale = Locale.getDefault().getLanguage(); String descriptiveText = getDescriptiveText(defaultLocale); if (descriptiveText == null) { - descriptiveText = getDescriptiveText(""); + descriptiveText = getDescriptiveText("en"); + if (descriptiveText == null) { + descriptiveText = getDescriptiveText(""); + } } return descriptiveText; } 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 d2f096de6..11bb224ef 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 @@ -488,7 +488,7 @@ public final class Message extends Stanza implements TypedCloneable { // Add the subject in other languages for (Subject subject : getSubjects()) { // Skip the default language - if(subject.equals(defaultSubject)) + if (subject.equals(defaultSubject)) continue; buf.append(subject.toXML()); } @@ -500,7 +500,7 @@ public final class Message extends Stanza implements TypedCloneable { // Add the bodies in other languages for (Body body : getBodies()) { // Skip the default language - if(body.equals(defaultBody)) + if (body.equals(defaultBody)) continue; buf.append(body.toXML()); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/StandardExtensionElement.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/StandardExtensionElement.java index a7d98a3e7..35d904f20 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/packet/StandardExtensionElement.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/StandardExtensionElement.java @@ -120,7 +120,7 @@ public final class StandardExtensionElement implements ExtensionElement { } public List getElements() { - if (elements == null){ + if (elements == null) { return Collections.emptyList(); } return elements.values(); diff --git a/smack-core/src/main/java/org/jivesoftware/smack/provider/Provider.java b/smack-core/src/main/java/org/jivesoftware/smack/provider/Provider.java index 7b4a659eb..b9d64e7aa 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/provider/Provider.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/provider/Provider.java @@ -23,7 +23,7 @@ import org.xmlpull.v1.XmlPullParser; public abstract class Provider { - public final E parse(XmlPullParser parser) throws Exception{ + public final E parse(XmlPullParser parser) throws Exception { // XPP3 calling convention assert: Parser should be at start tag ParserUtils.assertAtStartTag(parser); 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 bee798fb0..4fa884d39 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 @@ -135,7 +135,7 @@ public class ProviderFileLoader implements ProviderLoader { } while (eventType != XmlPullParser.END_DOCUMENT); } - catch (Exception e){ + catch (Exception e) { LOGGER.log(Level.SEVERE, "Unknown error occurred while parsing provider file", e); exceptions.add(e); } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/proxy/ProxyException.java b/smack-core/src/main/java/org/jivesoftware/smack/proxy/ProxyException.java index ccf0f9b25..551b06876 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/proxy/ProxyException.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/proxy/ProxyException.java @@ -31,7 +31,7 @@ public class ProxyException extends IOException { public ProxyException(ProxyInfo.ProxyType type, String ex) { - super("Proxy Exception " + type.toString() + " : "+ex); + super("Proxy Exception " + type.toString() + " : " + ex); } public ProxyException(ProxyInfo.ProxyType type) 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 65a54059a..b416319d0 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 @@ -50,12 +50,12 @@ public class Socks4ProxySocketConnection implements ProxySocketConnection { try { socket.connect(new InetSocketAddress(proxy_host, proxy_port), timeout); - in=socket.getInputStream(); - out=socket.getOutputStream(); + in = socket.getInputStream(); + out = socket.getOutputStream(); socket.setTcpNoDelay(true); - byte[] buf=new byte[1024]; - int index=0; + byte[] buf = new byte[1024]; + int index = 0; /* 1) CONNECT @@ -75,27 +75,27 @@ public class Socks4ProxySocketConnection implements ProxySocketConnection { of all zero bits. */ - index=0; - buf[index++]=4; - buf[index++]=1; + index = 0; + buf[index++] = 4; + buf[index++] = 1; - buf[index++]=(byte)(port>>>8); - buf[index++]=(byte)(port&0xff); + buf[index++] = (byte) (port >>> 8); + buf[index++] = (byte) (port & 0xff); InetAddress inetAddress = InetAddress.getByName(proxy_host); byte[] byteAddress = inetAddress.getAddress(); for (int i = 0; i < byteAddress.length; i++) { - buf[index++]=byteAddress[i]; + buf[index++] = byteAddress[i]; } - if(user!=null) + if (user != null) { byte[] userBytes = user.getBytes(StringUtils.UTF8); System.arraycopy(userBytes, 0, buf, index, user.length()); - index+=user.length(); + index += user.length(); } - buf[index++]=0; + buf[index++] = 0; out.write(buf, 0, index); /* @@ -125,49 +125,49 @@ public class Socks4ProxySocketConnection implements ProxySocketConnection { The remaining fields are ignored. */ - int len=6; - int s=0; - while(s>>8); - buf[index++]=(byte)(port&0xff); + index += len; + buf[index++] = (byte) (port >>> 8); + buf[index++] = (byte) (port & 0xff); out.write(buf, 0, index); @@ -263,20 +263,20 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { //in.read(buf, 0, 4); fill(in, buf, 4); - if(buf[1]!=0) + if (buf[1] != 0) { try { socket.close(); } - catch(Exception eee) + catch (Exception eee) { } throw new ProxyException(ProxyInfo.ProxyType.SOCKS5, - "server returns "+buf[1]); + "server returns " + buf[1]); } - switch(buf[3]&0xff) + switch (buf[3] & 0xff) { case 1: //in.read(buf, 0, 6); @@ -286,7 +286,7 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { //in.read(buf, 0, 1); fill(in, buf, 1); //in.read(buf, 0, buf[0]+2); - fill(in, buf, (buf[0]&0xff)+2); + fill(in, buf, (buf[0] & 0xff) + 2); break; case 4: //in.read(buf, 0, 18); @@ -295,17 +295,17 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { default: } } - catch(RuntimeException e) + catch (RuntimeException e) { throw e; } - catch(Exception e) + catch (Exception e) { try { socket.close(); } - catch(Exception eee) + catch (Exception eee) { } // TODO convert to IOException(e) when minimum Android API level is 9 or higher @@ -316,16 +316,16 @@ public class Socks5ProxySocketConnection implements ProxySocketConnection { private static void fill(InputStream in, byte[] buf, int len) throws IOException { - int s=0; - while(s { this.password = password; this.authorizationId = authzid; this.sslSession = sslSession; - assert(authorizationId == null || authzidSupported()); + assert (authorizationId == null || authzidSupported()); authenticateInternal(); authenticate(); } @@ -194,7 +194,7 @@ public abstract class SASLMechanism implements Comparable { this.serviceName = serviceName; this.authorizationId = authzid; this.sslSession = sslSession; - assert(authorizationId == null || authzidSupported()); + assert (authorizationId == null || authzidSupported()); authenticateInternal(cbh); authenticate(); } 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 4209083c1..8ce0e8b36 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 @@ -232,7 +232,7 @@ public abstract class ScramMechanism extends SASLMechanism { } String cbName = getChannelBindingName(); - assert(StringUtils.isNotEmpty(cbName)); + assert (StringUtils.isNotEmpty(cbName)); return cbName + ',' + authzidPortion + ","; } diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/EventManger.java b/smack-core/src/main/java/org/jivesoftware/smack/util/EventManger.java index 69ca3d6eb..c778fcdf3 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/EventManger.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/EventManger.java @@ -81,7 +81,7 @@ public class EventManger { return false; } reference.eventResult = eventResult; - synchronized(reference) { + synchronized (reference) { reference.notifyAll(); } return true; diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/LazyStringBuilder.java b/smack-core/src/main/java/org/jivesoftware/smack/util/LazyStringBuilder.java index 638ada32d..6baf74625 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/LazyStringBuilder.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/LazyStringBuilder.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. @@ -19,9 +19,13 @@ package org.jivesoftware.smack.util; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; public class LazyStringBuilder implements Appendable, CharSequence { + private static final Logger LOGGER = Logger.getLogger(LazyStringBuilder.class.getName()); + private final List list; private String cache; @@ -69,8 +73,15 @@ public class LazyStringBuilder implements Appendable, CharSequence { return cache.length(); } int length = 0; - for (CharSequence csq : list) { - length += csq.length(); + try { + for (CharSequence csq : list) { + length += csq.length(); + } + } + catch (NullPointerException npe) { + StringBuilder sb = safeToStringBuilder(); + LOGGER.log(Level.SEVERE, "The following LazyStringBuilder threw a NullPointerException: " + sb, npe); + throw npe; } return length; } @@ -107,6 +118,14 @@ public class LazyStringBuilder implements Appendable, CharSequence { return cache; } + public StringBuilder safeToStringBuilder() { + StringBuilder sb = new StringBuilder(); + for (CharSequence csq : list) { + sb.append(csq); + } + return sb; + } + /** * Get the List of CharSequences representation of this instance. The list is unmodifiable. If * the resulting String was already cached, a list with a single String entry will be returned. diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/MultiMap.java b/smack-core/src/main/java/org/jivesoftware/smack/util/MultiMap.java index 479b8c395..1a6401e05 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/MultiMap.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/MultiMap.java @@ -143,7 +143,7 @@ public class MultiMap { if (res == null) { return null; } - assert(!res.isEmpty()); + assert (!res.isEmpty()); return res.iterator().next(); } 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 4c9ce0699..498344bb8 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 @@ -214,7 +214,7 @@ public class PacketParserUtils { public static Message parseMessage(XmlPullParser parser) throws Exception { ParserUtils.assertAtStartTag(parser); - assert(parser.getName().equals(Message.ELEMENT)); + assert (parser.getName().equals(Message.ELEMENT)); final int initialDepth = parser.getDepth(); Message message = new Message(); @@ -247,7 +247,7 @@ public class PacketParserUtils { case XmlPullParser.START_TAG: String elementName = parser.getName(); String namespace = parser.getNamespace(); - switch(elementName) { + switch (elementName) { case "subject": String xmlLangSubject = getLanguageAttribute(parser); if (xmlLangSubject == null) { @@ -385,7 +385,7 @@ public class PacketParserUtils { */ public static CharSequence parseContent(XmlPullParser parser) throws XmlPullParserException, IOException { - assert(parser.getEventType() == XmlPullParser.START_TAG); + assert (parser.getEventType() == XmlPullParser.START_TAG); if (parser.isEmptyElementTag()) { return ""; } @@ -546,7 +546,7 @@ public class PacketParserUtils { case XmlPullParser.START_TAG: String elementName = parser.getName(); String namespace = parser.getNamespace(); - switch(elementName) { + switch (elementName) { case "status": presence.setStatus(parser.nextText()); break; @@ -620,7 +620,7 @@ public class PacketParserUtils { case XmlPullParser.START_TAG: String elementName = parser.getName(); String namespace = parser.getNamespace(); - switch(elementName) { + switch (elementName) { case "error": error = PacketParserUtils.parseError(parser); break; @@ -775,7 +775,7 @@ public class PacketParserUtils { descriptiveTexts = parseDescriptiveTexts(parser, descriptiveTexts); } else { - assert(condition == null); + assert (condition == null); condition = parser.getName(); } break; @@ -945,7 +945,7 @@ public class PacketParserUtils { } } } - assert(parser.getEventType() == XmlPullParser.END_TAG); + assert (parser.getEventType() == XmlPullParser.END_TAG); return new StartTls(required); } @@ -954,7 +954,7 @@ public class PacketParserUtils { final int initialDepth = parser.getDepth(); boolean optional = false; if (!parser.isEmptyElementTag()) { - outerloop: while(true) { + outerloop: while (true) { int event = parser.next(); switch (event) { case XmlPullParser.START_TAG: @@ -1022,7 +1022,7 @@ public class PacketParserUtils { } public static void addExtensionElement(Stanza packet, XmlPullParser parser, String elementName, - String namespace) throws Exception{ + String namespace) throws Exception { ExtensionElement packetExtension = parseExtensionElement(elementName, namespace, parser); packet.addExtension(packetExtension); } 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 9a5b68153..3badf6a02 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 @@ -43,7 +43,7 @@ public class ParserUtils { public static final String JID = "jid"; public static void assertAtStartTag(XmlPullParser parser) throws XmlPullParserException { - assert(parser.getEventType() == XmlPullParser.START_TAG); + assert (parser.getEventType() == XmlPullParser.START_TAG); } public static void assertAtStartTag(XmlPullParser parser, String name) throws XmlPullParserException { @@ -52,7 +52,7 @@ public class ParserUtils { } public static void assertAtEndTag(XmlPullParser parser) throws XmlPullParserException { - assert(parser.getEventType() == XmlPullParser.END_TAG); + assert (parser.getEventType() == XmlPullParser.END_TAG); } public static void forwardToEndTagOfDepth(XmlPullParser parser, int depth) diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/StringUtils.java b/smack-core/src/main/java/org/jivesoftware/smack/util/StringUtils.java index 94e528099..c2bb9210a 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/StringUtils.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/StringUtils.java @@ -121,7 +121,7 @@ public class StringUtils { return null; } final int len = input.length(); - final StringBuilder out = new StringBuilder((int)(len*1.3)); + final StringBuilder out = new StringBuilder((int) (len * 1.3)); CharSequence toAppend; char ch; int last = 0; @@ -153,7 +153,7 @@ public class StringUtils { break; case forAttribute: // No need to escape '>' for attributes. - switch(ch) { + switch (ch) { case '<': toAppend = LT_ENCODE; break; @@ -172,7 +172,7 @@ public class StringUtils { break; case forAttributeApos: // No need to escape '>' and '"' for attributes using '\'' as quote. - switch(ch) { + switch (ch) { case '<': toAppend = LT_ENCODE; break; @@ -188,7 +188,7 @@ public class StringUtils { break; case forText: // No need to escape '"', '\'', and '>' for text. - switch(ch) { + switch (ch) { case '<': toAppend = LT_ENCODE; break; @@ -307,8 +307,8 @@ public class StringUtils { final Random random = randGen.get(); // Create a char buffer to put random letters and numbers in. - char [] randBuffer = new char[length]; - for (int i=0; i future = new SimpleInternalSmackFuture() { + @Override + protected void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException { + setResult(true); + } + }; + + future.processStanza(null); + + assertTrue(future.get()); + } + + @Test(expected = TimeoutException.class) + public void simpleSmackFutureTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException { + InternalSmackFuture future = new SimpleInternalSmackFuture() { + @Override + protected void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException { + } + }; + + future.get(5, TimeUnit.SECONDS); + } +} 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 4120f4529..5bd654721 100644 --- a/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java +++ b/smack-core/src/test/java/org/jivesoftware/smack/StanzaCollectorTest.java @@ -31,7 +31,7 @@ public class StanzaCollectorTest { TestStanzaCollector collector = new TestStanzaCollector(null, new OKEverything(), 5); - for (int i=0; i<6; i++) + for (int i = 0; i < 6; i++) { Stanza testPacket = new TestPacket(i); collector.processStanza(testPacket); @@ -45,7 +45,7 @@ public class StanzaCollectorTest assertEquals("5", collector.pollResult().getStanzaId()); assertNull(collector.pollResult()); - for (int i=10; i<15; i++) + for (int i = 10; i < 15; i++) { Stanza testPacket = new TestPacket(i); collector.processStanza(testPacket); @@ -156,7 +156,7 @@ public class StanzaCollectorTest consumer2.start(); consumer3.start(); - for(int i=0; i responsePairs = new HashMap(); for (String part : responseParts) { - String[] keyValue = part.split("="); - assertTrue(keyValue.length == 2); + String[] keyValue = part.split("=", 2); String key = keyValue[0]; String value = keyValue[1].replace("\"", ""); responsePairs.put(key, value); @@ -59,7 +58,7 @@ public class DigestMd5SaslTest extends AbstractSaslTest { if (useAuthzid) { assertMapValue("authzid", "shazbat@xmpp.org", responsePairs); } else { - assert(!responsePairs.containsKey("authzid")); + assertTrue (!responsePairs.containsKey("authzid")); } assertMapValue("username", "florian", responsePairs); assertMapValue("realm", "xmpp.org", responsePairs); 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 b988a3e3a..1494f220a 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 @@ -664,7 +664,7 @@ public class PacketParserUtilsTest { * * @throws Exception */ - @Test(expected=XmlPullParserException.class) + @Test(expected = XmlPullParserException.class) public void invalidMessageBodyContainingTagTest() throws Exception { String control = XMLBuilder.create("message") .a("from", "romeo@montague.lit/orchard") @@ -701,7 +701,7 @@ public class PacketParserUtilsTest { try { PacketParserUtils.parseMessage(PacketParserUtils.getParserFor(invalidControl)); fail("Exception should be thrown"); - } catch(XmlPullParserException e) { + } catch (XmlPullParserException e) { assertTrue(e.getMessage().contains("end tag name ")); } @@ -710,7 +710,7 @@ public class PacketParserUtilsTest { try { PacketParserUtils.parseMessage(PacketParserUtils.getParserFor(invalidControl)); fail("Exception should be thrown"); - } catch(XmlPullParserException e) { + } catch (XmlPullParserException e) { assertTrue(e.getMessage().contains("end tag name ")); } @@ -719,7 +719,7 @@ public class PacketParserUtilsTest { try { PacketParserUtils.parseMessage(PacketParserUtils.getParserFor(invalidControl)); fail("Exception should be thrown"); - } catch(XmlPullParserException e) { + } catch (XmlPullParserException e) { assertTrue(e.getMessage().contains("end tag name ")); } 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 ada3d4d99..6bd5ed33b 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 @@ -70,7 +70,7 @@ public class SHA1Test { */ private boolean isValidHash(String result) { boolean valid = true; - for (int i=0; i INSTANCES = new WeakHashMap<>(); + + static { + XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { + @Override + public void connectionCreated(XMPPConnection connection) { + getInstanceFor(connection); + } + }); + } + + public static final String NAMESPACE_V0 = ExplicitMessageEncryptionElement.NAMESPACE; + + public static synchronized ExplicitMessageEncryptionManager getInstanceFor(XMPPConnection connection) { + ExplicitMessageEncryptionManager manager = INSTANCES.get(connection); + if (manager == null) { + manager = new ExplicitMessageEncryptionManager(connection); + INSTANCES.put(connection, manager); + } + return manager; + } + + private ExplicitMessageEncryptionManager(XMPPConnection connection) { + ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); + sdm.addFeature(NAMESPACE_V0); + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/ExplicitMessageEncryptionElement.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/ExplicitMessageEncryptionElement.java new file mode 100644 index 000000000..c98f22cd4 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/ExplicitMessageEncryptionElement.java @@ -0,0 +1,146 @@ +/** + * + * 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.eme.element; + +import java.util.HashMap; +import java.util.Map; + +import org.jivesoftware.smack.packet.ExtensionElement; +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smack.util.StringUtils; +import org.jivesoftware.smack.util.XmlStringBuilder; + +public class ExplicitMessageEncryptionElement implements ExtensionElement { + + private static final Map PROTOCOL_LUT = new HashMap<>(); + + public static final String ELEMENT = "encryption"; + + public static final String NAMESPACE = "urn:xmpp:eme:0"; + + public enum ExplicitMessageEncryptionProtocol { + + /** + * The encryption method specified in XEP-0373: OpenPGP for + * XMPP. + */ + openpgpV0("urn:xmpp:openpgp:0", "OpenPGP for XMPP (XEP-0373)"), + + otrV0("urn:xmpp:otr:0", "Off-the-Record Messaging (XEP-0364)"), + + legacyOpenPGP("jabber:x:encrypted", "Legacy OpenPGP for XMPP [DANGEROUS, DO NOT USE!]"), + ; + + private final String namespace; + private final String name; + + private ExplicitMessageEncryptionProtocol(String namespace, String name) { + this.namespace = namespace; + this.name = name; + PROTOCOL_LUT.put(namespace, this); + } + + public String getNamespace() { + return namespace; + } + + public String getName() { + return name; + } + + public static ExplicitMessageEncryptionProtocol from(String namespace) { + return PROTOCOL_LUT.get(namespace); + } + } + + private final String encryptionNamespace; + + private final String name; + + private boolean isUnknownProtocol; + + private ExplicitMessageEncryptionProtocol protocolCache; + + public ExplicitMessageEncryptionElement(ExplicitMessageEncryptionProtocol protocol) { + this(protocol.getNamespace(), protocol.getName()); + } + + public ExplicitMessageEncryptionElement(String encryptionNamespace) { + this(encryptionNamespace, null); + } + + public ExplicitMessageEncryptionElement(String encryptionNamespace, String name) { + this.encryptionNamespace = StringUtils.requireNotNullOrEmpty(encryptionNamespace, + "encryptionNamespace must not be null"); + this.name = name; + } + + public ExplicitMessageEncryptionProtocol getProtocol() { + if (protocolCache != null) { + return protocolCache; + } + + if (isUnknownProtocol) { + return null; + } + + ExplicitMessageEncryptionProtocol protocol = PROTOCOL_LUT.get(encryptionNamespace); + if (protocol == null) { + isUnknownProtocol = true; + return null; + } + + protocolCache = protocol; + return protocol; + } + + public String getEncryptionNamespace() { + return encryptionNamespace; + } + + /** + * Get the optional name of the encryption method. + * + * @return the name of the encryption method or null. + */ + public String getName() { + return name; + } + + @Override + public String getElementName() { + return ELEMENT; + } + + @Override + public String getNamespace() { + return NAMESPACE; + } + + @Override + public XmlStringBuilder toXML() { + XmlStringBuilder xml = new XmlStringBuilder(this); + xml.attribute("namespace", getEncryptionNamespace()); + xml.optAttribute("name", getName()); + xml.closeEmptyElement(); + return xml; + } + + public static ExplicitMessageEncryptionElement from(Message message) { + return message.getExtension(ELEMENT, NAMESPACE); + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/package-info.java new file mode 100644 index 000000000..9b4b286e7 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/element/package-info.java @@ -0,0 +1,20 @@ +/** + * + * 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. + */ +/** + * XMPP extension elements for XEP-0380: Explicit Message Encryption. + */ +package org.jivesoftware.smackx.eme.element; diff --git a/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/package-info.java similarity index 81% rename from package-info.java rename to smack-experimental/src/main/java/org/jivesoftware/smackx/eme/package-info.java index a9c7f141b..ae132d815 100644 --- a/package-info.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/package-info.java @@ -1,6 +1,6 @@ /** * - * Copyright 2015 Florian Schmaus + * 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. @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** - * TODO describe me + * Smack's API for XEP-0380: Explicit Message Encryption. */ -package org.jivesoftware.smackx.iqprivate; +package org.jivesoftware.smackx.eme; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProvider.java new file mode 100644 index 000000000..b466f4b70 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProvider.java @@ -0,0 +1,32 @@ +/** + * + * 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.eme.provider; + +import org.jivesoftware.smack.provider.ExtensionElementProvider; +import org.jivesoftware.smackx.eme.element.ExplicitMessageEncryptionElement; +import org.xmlpull.v1.XmlPullParser; + +public class ExplicitMessageEncryptionProvider extends ExtensionElementProvider { + + @Override + public ExplicitMessageEncryptionElement parse(XmlPullParser parser, int initialDepth) throws Exception { + String namespace = parser.getAttributeValue(null, "namespace"); + String name = parser.getAttributeValue(null, "name"); + return new ExplicitMessageEncryptionElement(namespace, name); + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/package-info.java new file mode 100644 index 000000000..611873f17 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/eme/provider/package-info.java @@ -0,0 +1,20 @@ +/** + * + * 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. + */ +/** + * Smack Provider for XEP-0380: Explicit Message Encryption. + */ +package org.jivesoftware.smackx.eme.provider; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/MessageProcessingHintsManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/MessageProcessingHintsManager.java new file mode 100644 index 000000000..4f0e20522 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/MessageProcessingHintsManager.java @@ -0,0 +1,71 @@ +/** + * + * 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.hints; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smackx.hints.element.MessageProcessingHintType; +import org.jivesoftware.smackx.hints.element.NoCopyHint; +import org.jivesoftware.smackx.hints.element.NoPermanentStoreHint; +import org.jivesoftware.smackx.hints.element.NoStoreHint; +import org.jivesoftware.smackx.hints.element.StoreHint; + +public class MessageProcessingHintsManager { + + public static Set getHintsFrom(Message message) { + Set hints = null; + + boolean noCopyHint = NoCopyHint.hasHint(message); + if (noCopyHint) { + hints = new HashSet<>(MessageProcessingHintType.values().length); + hints.add(MessageProcessingHintType.no_copy); + } + + boolean noPermanentStoreHint = NoPermanentStoreHint.hasHint(message); + if (noPermanentStoreHint) { + if (hints == null) { + hints = new HashSet<>(MessageProcessingHintType.values().length); + } + hints.add(MessageProcessingHintType.no_permanent_store); + } + + boolean noStoreHint = NoStoreHint.hasHint(message); + if (noStoreHint) { + if (hints == null) { + hints = new HashSet<>(MessageProcessingHintType.values().length); + } + hints.add(MessageProcessingHintType.no_store); + } + + boolean storeHint = StoreHint.hasHint(message); + if (storeHint) { + if (hints == null) { + hints = new HashSet<>(MessageProcessingHintType.values().length); + } + hints.add(MessageProcessingHintType.store); + } + + if (hints == null) { + return Collections.emptySet(); + } + + return hints; + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHint.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHint.java new file mode 100644 index 000000000..3ea9dc487 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHint.java @@ -0,0 +1,32 @@ +/** + * + * 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.hints.element; + +import org.jivesoftware.smack.packet.ExtensionElement; + +public abstract class MessageProcessingHint implements ExtensionElement { + + public static final String NAMESPACE = "urn:xmpp:hints"; + + @Override + public final String getNamespace() { + return NAMESPACE; + } + + public abstract MessageProcessingHintType getHintType(); + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHintType.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHintType.java new file mode 100644 index 000000000..a89bc56b5 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/MessageProcessingHintType.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.hints.element; + +public enum MessageProcessingHintType { + + no_permanent_store, + no_store, + no_copy, + store, + ; + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoCopyHint.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoCopyHint.java new file mode 100644 index 000000000..b726b2be2 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoCopyHint.java @@ -0,0 +1,61 @@ +/** + * + * 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.hints.element; + +import org.jivesoftware.smack.packet.Message; + +/** + * A "no copy" hint. Messages with this hint should not be copied to addresses other than the one to which it is addressed. + * + * @see XEP-0344 § 4.3 No copies + */ +public final class NoCopyHint extends MessageProcessingHint { + + public static final NoCopyHint INSTANCE = new NoCopyHint(); + + public static final String ELEMENT = "no-copy"; + + private NoCopyHint() { + } + + @Override + public String getElementName() { + return ELEMENT; + } + + @Override + public String toXML() { + return '<' + ELEMENT + " xmlns='" + NAMESPACE + "'/>"; + } + + @Override + public MessageProcessingHintType getHintType() { + return MessageProcessingHintType.no_copy; + } + + public static NoCopyHint from(Message message) { + return message.getExtension(ELEMENT, NAMESPACE); + } + + public static boolean hasHint(Message message) { + return from(message) != null; + } + + public static void set(Message message) { + message.addExtension(INSTANCE); + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoPermanentStoreHint.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoPermanentStoreHint.java new file mode 100644 index 000000000..d52ed693b --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoPermanentStoreHint.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.smackx.hints.element; + +import org.jivesoftware.smack.packet.Message; + +/** + * A "no permanent store" hint. Messages with this hint should not be stored in permanent stores or archives. + * + * @see XEP-0334 § 4.1 No permanent store + */ +public final class NoPermanentStoreHint extends MessageProcessingHint { + + public static final NoPermanentStoreHint INSTANCE = new NoPermanentStoreHint(); + + public static final String ELEMENT = "no-permanent-store"; + + private NoPermanentStoreHint() { + } + + @Override + public String getElementName() { + return ELEMENT; + } + + @Override + public String toXML() { + return '<' + ELEMENT + " xmlns='" + NAMESPACE + "'/>"; + } + + @Override + public MessageProcessingHintType getHintType() { + return MessageProcessingHintType.no_permanent_store; + } + + public static NoPermanentStoreHint from(Message message) { + return message.getExtension(ELEMENT, NAMESPACE); + } + + public static boolean hasHint(Message message) { + return from(message) != null; + } + + public static void set(Message message) { + if (StoreHint.hasHint(message)) { + // No need to set the no-permanent-store hint when a no-store hint is already set. + return; + } + setExplicitly(message); + } + + public static void setExplicitly(Message message) { + message.addExtension(INSTANCE); + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoStoreHint.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoStoreHint.java new file mode 100644 index 000000000..1651dde18 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/NoStoreHint.java @@ -0,0 +1,61 @@ +/** + * + * 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.hints.element; + +import org.jivesoftware.smack.packet.Message; + +/** + * A "no store" hint. Messages with this hint should not be stored in stores or archives. + * + * XEP-0334 § 4.2 No store + */ +public final class NoStoreHint extends MessageProcessingHint { + + public static final NoStoreHint INSTANCE = new NoStoreHint(); + + public static final String ELEMENT = "no-store"; + + private NoStoreHint() { + } + + @Override + public String getElementName() { + return ELEMENT; + } + + @Override + public String toXML() { + return '<' + ELEMENT + " xmlns='" + NAMESPACE + "'/>"; + } + + @Override + public MessageProcessingHintType getHintType() { + return MessageProcessingHintType.no_store; + } + + public static NoStoreHint from(Message message) { + return message.getExtension(ELEMENT, NAMESPACE); + } + + public static boolean hasHint(Message message) { + return from(message) != null; + } + + public static void set(Message message) { + message.addExtension(INSTANCE); + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/StoreHint.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/StoreHint.java new file mode 100644 index 000000000..fdbc826fa --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/StoreHint.java @@ -0,0 +1,61 @@ +/** + * + * 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.hints.element; + +import org.jivesoftware.smack.packet.Message; + +/** + * A "store" hint. Messages with this hint should be stored in permanent stores or archives. + * + * @see XEP-0334 § 4.4 Store + */ +public final class StoreHint extends MessageProcessingHint { + + public static final StoreHint INSTANCE = new StoreHint(); + + public static final String ELEMENT = "store"; + + private StoreHint() { + } + + @Override + public String getElementName() { + return ELEMENT; + } + + @Override + public String toXML() { + return '<' + ELEMENT + " xmlns='" + NAMESPACE + "'/>"; + } + + @Override + public MessageProcessingHintType getHintType() { + return MessageProcessingHintType.store; + } + + public static StoreHint from(Message message) { + return message.getExtension(ELEMENT, NAMESPACE); + } + + public static boolean hasHint(Message message) { + return from(message) != null; + } + + public static void set(Message message) { + message.addExtension(INSTANCE); + } +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/package-info.java new file mode 100644 index 000000000..f2a9eff0d --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/element/package-info.java @@ -0,0 +1,20 @@ +/** + * + * 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. + */ +/** + * XMPP extension elements for XEP-0334: Message Processing Hints. + */ +package org.jivesoftware.smackx.hints.element; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/package-info.java new file mode 100644 index 000000000..33d49eaae --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/package-info.java @@ -0,0 +1,20 @@ +/** + * + * 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. + */ +/** + * Smack's API for XEP-0334: Message Processing Hints. + */ +package org.jivesoftware.smackx.hints; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/MessageProcessingHintProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/MessageProcessingHintProvider.java new file mode 100644 index 000000000..0918bcd56 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/MessageProcessingHintProvider.java @@ -0,0 +1,31 @@ +/** + * + * 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.hints.provider; + +import org.jivesoftware.smack.provider.ExtensionElementProvider; +import org.jivesoftware.smackx.hints.element.MessageProcessingHint; +import org.xmlpull.v1.XmlPullParser; + +public abstract class MessageProcessingHintProvider extends ExtensionElementProvider { + + @Override + public H parse(XmlPullParser parser, int initialDepth) throws Exception { + return getHint(); + } + + protected abstract H getHint(); +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoCopyHintProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoCopyHintProvider.java new file mode 100644 index 000000000..1cabaaf20 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoCopyHintProvider.java @@ -0,0 +1,28 @@ +/** + * + * 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.hints.provider; + +import org.jivesoftware.smackx.hints.element.NoCopyHint; + +public class NoCopyHintProvider extends MessageProcessingHintProvider { + + @Override + protected NoCopyHint getHint() { + return NoCopyHint.INSTANCE; + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoPermanentStoreHintProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoPermanentStoreHintProvider.java new file mode 100644 index 000000000..8d81cede8 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoPermanentStoreHintProvider.java @@ -0,0 +1,28 @@ +/** + * + * 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.hints.provider; + +import org.jivesoftware.smackx.hints.element.NoPermanentStoreHint; + +public class NoPermanentStoreHintProvider extends MessageProcessingHintProvider { + + @Override + protected NoPermanentStoreHint getHint() { + return NoPermanentStoreHint.INSTANCE; + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoStoreHintProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoStoreHintProvider.java new file mode 100644 index 000000000..343f9b1bb --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/NoStoreHintProvider.java @@ -0,0 +1,28 @@ +/** + * + * 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.hints.provider; + +import org.jivesoftware.smackx.hints.element.NoStoreHint; + +public class NoStoreHintProvider extends MessageProcessingHintProvider { + + @Override + protected NoStoreHint getHint() { + return NoStoreHint.INSTANCE; + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/StoreHintProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/StoreHintProvider.java new file mode 100644 index 000000000..cd7889c59 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/StoreHintProvider.java @@ -0,0 +1,28 @@ +/** + * + * 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.hints.provider; + +import org.jivesoftware.smackx.hints.element.StoreHint; + +public class StoreHintProvider extends MessageProcessingHintProvider { + + @Override + protected StoreHint getHint() { + return StoreHint.INSTANCE; + } + +} diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/package-info.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/package-info.java new file mode 100644 index 000000000..c508930b1 --- /dev/null +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/hints/provider/package-info.java @@ -0,0 +1,20 @@ +/** + * + * 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. + */ +/** + * Smack Provider for XEP-0334: Message Processing Hints. + */ +package org.jivesoftware.smackx.hints.provider; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java index ddf67f054..bbc5cb51c 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java @@ -121,7 +121,7 @@ public final class HttpFileUploadManager extends Manager { } private static UploadService uploadServiceFrom(DiscoverInfo discoverInfo) { - assert(containsHttpFileUploadNamespace(discoverInfo)); + assert (containsHttpFileUploadNamespace(discoverInfo)); UploadService.Version version; if (discoverInfo.containsFeature(NAMESPACE)) { diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/provider/FileTooLargeErrorProvider.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/provider/FileTooLargeErrorProvider.java index 77ea7fda4..d8114c0d3 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/provider/FileTooLargeErrorProvider.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/provider/FileTooLargeErrorProvider.java @@ -34,13 +34,13 @@ public class FileTooLargeErrorProvider extends ExtensionElementProvider { switch (event) { case XmlPullParser.START_TAG: String name = parser.getName(); - switch(name) { + switch (name) { case "put": putUrl = new URL(parser.nextText()); break; diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/element/IoTIsFriendResponse.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/element/IoTIsFriendResponse.java index 6892b7030..042b69055 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/element/IoTIsFriendResponse.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/provisioning/element/IoTIsFriendResponse.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. @@ -21,7 +21,7 @@ import org.jxmpp.jid.BareJid; public class IoTIsFriendResponse extends IQ { - public static final String ELEMENT = "isFriend"; + public static final String ELEMENT = "isFriendResponse"; public static final String NAMESPACE = Constants.IOT_PROVISIONING_NAMESPACE; private final BareJid jid; @@ -46,6 +46,7 @@ public class IoTIsFriendResponse extends IQ { protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { xml.attribute("jid", jid); xml.attribute("result", result); + xml.setEmptyElement(); return xml; } diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/element/EnablePushNotificationsIQ.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/element/EnablePushNotificationsIQ.java index ea403ca3a..1fea8d518 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/element/EnablePushNotificationsIQ.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/element/EnablePushNotificationsIQ.java @@ -96,7 +96,7 @@ public class EnablePushNotificationsIQ extends IQ { xml.rightAngleBracket(); if (publishOptions != null) { - DataForm dataForm = new DataForm(DataForm.Type.form); + DataForm dataForm = new DataForm(DataForm.Type.submit); FormField formTypeField = new FormField("FORM_TYPE"); formTypeField.addValue(PubSub.NAMESPACE + "#publish-options"); diff --git a/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.providers b/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.providers index 20ed6cd25..21a8281f0 100644 --- a/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.providers +++ b/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.providers @@ -233,6 +233,28 @@ org.jivesoftware.smackx.chat_markers.provider.AcknowledgedProvider + + + no-copy + urn:xmpp:hints + org.jivesoftware.smackx.hints.provider.NoCopyHintProvider + + + no-permanent-store + urn:xmpp:hints + org.jivesoftware.smackx.hints.provider.NoPermanentStoreHintProvider + + + no-store + urn:xmpp:hints + org.jivesoftware.smackx.hints.provider.NoStoreHintProvider + + + store + urn:xmpp:hints + org.jivesoftware.smackx.hints.provider.StoreHintProvider + +g slot @@ -255,4 +277,11 @@ org.jivesoftware.smackx.httpfileupload.provider.FileTooLargeErrorProvider + + + encryption + urn:xmpp:eme:0 + org.jivesoftware.smackx.eme.provider.ExplicitMessageEncryptionProvider + + diff --git a/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.xml b/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.xml index 05b819a27..ab592717a 100644 --- a/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.xml +++ b/smack-experimental/src/main/resources/org.jivesoftware.smack.experimental/experimental.xml @@ -5,5 +5,6 @@ org.jivesoftware.smackx.iot.discovery.IoTDiscoveryManager org.jivesoftware.smackx.iot.provisioning.IoTProvisioningManager org.jivesoftware.smackx.httpfileupload.HttpFileUploadManager + org.jivesoftware.smackx.eme.ExplicitMessageEncryptionManager diff --git a/smack-experimental/src/test/java/org/jivesoftware/smackx/carbons/CarbonTest.java b/smack-experimental/src/test/java/org/jivesoftware/smackx/carbons/CarbonTest.java index c1ea5397b..20e479f95 100644 --- a/smack-experimental/src/test/java/org/jivesoftware/smackx/carbons/CarbonTest.java +++ b/smack-experimental/src/test/java/org/jivesoftware/smackx/carbons/CarbonTest.java @@ -94,7 +94,7 @@ public class CarbonTest extends ExperimentalInitializerTest { assertEquals("received", parser.getName()); } - @Test(expected=Exception.class) + @Test(expected = Exception.class) public void carbonEmptyTest() throws Exception { XmlPullParser parser; String control; diff --git a/smack-experimental/src/test/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProviderTest.java b/smack-experimental/src/test/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProviderTest.java new file mode 100644 index 000000000..248b9e39a --- /dev/null +++ b/smack-experimental/src/test/java/org/jivesoftware/smackx/eme/provider/ExplicitMessageEncryptionProviderTest.java @@ -0,0 +1,47 @@ +/** + * + * 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.eme.provider; + +import static org.junit.Assert.assertEquals; + +import org.jivesoftware.smack.test.util.TestUtils; +import org.jivesoftware.smackx.eme.element.ExplicitMessageEncryptionElement; +import org.jivesoftware.smackx.eme.element.ExplicitMessageEncryptionElement.ExplicitMessageEncryptionProtocol; +import org.junit.Test; + +public class ExplicitMessageEncryptionProviderTest { + + private static final String OX_EME_ELEMENT = ""; + + private static final String UNKNOWN_NAMESPACE = "urn:xmpp:foobar:0"; + private static final String UNKNOWN_NAME = "Foo Bar"; + private static final String UNKNOWN_EME_ELEMENT = ""; + + @Test + public void testParseOxEmeElement() throws Exception { + ExplicitMessageEncryptionElement eme = TestUtils.parseExtensionElement(OX_EME_ELEMENT); + assertEquals(ExplicitMessageEncryptionProtocol.openpgpV0, eme.getProtocol()); + } + + @Test + public void testParseUnknownEmeElement() throws Exception { + ExplicitMessageEncryptionElement eme = TestUtils.parseExtensionElement(UNKNOWN_EME_ELEMENT); + assertEquals(UNKNOWN_NAMESPACE, eme.getEncryptionNamespace()); + assertEquals(UNKNOWN_NAME, eme.getName()); + } +} diff --git a/smack-experimental/src/test/java/org/jivesoftware/smackx/muclight/MUCLightDestroyTest.java b/smack-experimental/src/test/java/org/jivesoftware/smackx/muclight/MUCLightDestroyTest.java index 455b650c1..ae73e3d5b 100644 --- a/smack-experimental/src/test/java/org/jivesoftware/smackx/muclight/MUCLightDestroyTest.java +++ b/smack-experimental/src/test/java/org/jivesoftware/smackx/muclight/MUCLightDestroyTest.java @@ -27,7 +27,7 @@ public class MUCLightDestroyTest { + "" + ""; @Test - public void checkDestroyMUCLightStanza() throws Exception{ + public void checkDestroyMUCLightStanza() throws Exception { MUCLightDestroyIQ mucLightDestroyIQ = new MUCLightDestroyIQ(JidCreate.from("coven@muclight.shakespeare.lit")); mucLightDestroyIQ.setStanzaId("destroy1"); Assert.assertEquals(mucLightDestroyIQ.toXML().toString(), stanza); diff --git a/smack-experimental/src/test/java/org/jivesoftware/smackx/push_notifications/EnablePushNotificationsIQTest.java b/smack-experimental/src/test/java/org/jivesoftware/smackx/push_notifications/EnablePushNotificationsIQTest.java index 644c62f83..c42e5bf12 100644 --- a/smack-experimental/src/test/java/org/jivesoftware/smackx/push_notifications/EnablePushNotificationsIQTest.java +++ b/smack-experimental/src/test/java/org/jivesoftware/smackx/push_notifications/EnablePushNotificationsIQTest.java @@ -31,7 +31,7 @@ public class EnablePushNotificationsIQTest { String exampleEnableIQWithPublishOptions = "" + "" - + "" + + "" + "http://jabber.org/protocol/pubsub#publish-options" + "eruio234vzxc2kla-91" + "" + "" + ""; diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java index 199906089..6bf423655 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java @@ -84,7 +84,7 @@ public class ServiceAdministrationManager extends Manager { passwordVerifyField.addValue(password); command.next(answerForm); - assert(command.isCompleted()); + assert (command.isCompleted()); } public RemoteCommand deleteUser() { @@ -112,6 +112,6 @@ public class ServiceAdministrationManager extends Manager { accountJids.addValues(JidUtil.toStringList(jidsToDelete)); command.next(answerForm); - assert(command.isCompleted()); + assert (command.isCompleted()); } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/packet/AMPExtension.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/packet/AMPExtension.java index 492c3b7ed..f6feabb59 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/packet/AMPExtension.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/packet/AMPExtension.java @@ -228,7 +228,7 @@ public class AMPExtension implements ExtensionElement { String getName(); String getValue(); - static final String ATTRIBUTE_NAME="condition"; + static final String ATTRIBUTE_NAME = "condition"; } /** @@ -265,7 +265,7 @@ public class AMPExtension implements ExtensionElement { */ notify; - public static final String ATTRIBUTE_NAME="action"; + public static final String ATTRIBUTE_NAME = "action"; } /** diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBData.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBData.java index 544a2d7a6..2d7deaca4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBData.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBData.java @@ -82,7 +82,7 @@ public class BoBData { private void setContentBinaryIfRequired() { if (contentBinary == null) { - assert(StringUtils.isNotEmpty(contentString)); + assert (StringUtils.isNotEmpty(contentString)); contentBinary = Base64.decode(contentString); } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java index 4a162f49a..dfbe62491 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java @@ -118,9 +118,9 @@ public final class BookmarkManager { BookmarkedConference bookmark = new BookmarkedConference(name, jid, isAutoJoin, nickname, password); List conferences = bookmarks.getBookmarkedConferences(); - if(conferences.contains(bookmark)) { + if (conferences.contains(bookmark)) { BookmarkedConference oldConference = conferences.get(conferences.indexOf(bookmark)); - if(oldConference.isShared()) { + if (oldConference.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmark"); } oldConference.setAutoJoin(isAutoJoin); @@ -149,10 +149,10 @@ public final class BookmarkManager { public void removeBookmarkedConference(EntityBareJid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); Iterator it = bookmarks.getBookmarkedConferences().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { BookmarkedConference conference = it.next(); - if(conference.getJid().equals(jid)) { - if(conference.isShared()) { + if (conference.getJid().equals(jid)) { + if (conference.isShared()) { throw new IllegalArgumentException("Conference is shared and can't be removed"); } it.remove(); @@ -192,9 +192,9 @@ public final class BookmarkManager { retrieveBookmarks(); BookmarkedURL bookmark = new BookmarkedURL(URL, name, isRSS); List urls = bookmarks.getBookmarkedURLS(); - if(urls.contains(bookmark)) { + if (urls.contains(bookmark)) { BookmarkedURL oldURL = urls.get(urls.indexOf(bookmark)); - if(oldURL.isShared()) { + if (oldURL.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmarks"); } oldURL.setName(name); @@ -219,10 +219,10 @@ public final class BookmarkManager { public void removeBookmarkedURL(String bookmarkURL) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); Iterator it = bookmarks.getBookmarkedURLS().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { BookmarkedURL bookmark = it.next(); - if(bookmark.getURL().equalsIgnoreCase(bookmarkURL)) { - if(bookmark.isShared()) { + if (bookmark.getURL().equalsIgnoreCase(bookmarkURL)) { + if (bookmark.isShared()) { throw new IllegalArgumentException("Cannot delete a shared bookmark."); } it.remove(); @@ -249,8 +249,8 @@ public final class BookmarkManager { } private Bookmarks retrieveBookmarks() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - synchronized(bookmarkLock) { - if(bookmarks == null) { + synchronized (bookmarkLock) { + if (bookmarks == null) { bookmarks = (Bookmarks) privateDataManager.getPrivateData("storage", "storage:bookmarks"); } 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 fa1a4f1d8..9037f01aa 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 @@ -115,10 +115,10 @@ public class BookmarkedConference implements SharedBookmark { @Override public boolean equals(Object obj) { - if(obj == null || !(obj instanceof BookmarkedConference)) { + if (obj == null || !(obj instanceof BookmarkedConference)) { return false; } - BookmarkedConference conference = (BookmarkedConference)obj; + BookmarkedConference conference = (BookmarkedConference) obj; return conference.getJid().equals(jid); } 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 55f30bfa0..a0e438bb5 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 @@ -86,10 +86,10 @@ public class BookmarkedURL implements SharedBookmark { @Override public boolean equals(Object obj) { - if(!(obj instanceof BookmarkedURL)) { + if (!(obj instanceof BookmarkedURL)) { return false; } - BookmarkedURL url = (BookmarkedURL)obj; + BookmarkedURL url = (BookmarkedURL) obj; return url.getURL().equalsIgnoreCase(URL); } 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 d196f23c4..c91db023b 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 @@ -177,7 +177,7 @@ public class Bookmarks implements PrivateData { buf.halfOpenElement(ELEMENT).xmlnsAttribute(NAMESPACE).rightAngleBracket(); for (BookmarkedURL urlStorage : getBookmarkedURLS()) { - if(urlStorage.isShared()) { + if (urlStorage.isShared()) { continue; } buf.halfOpenElement("url").attribute("name", urlStorage.getName()).attribute("url", urlStorage.getURL()); @@ -187,7 +187,7 @@ public class Bookmarks implements PrivateData { // Add Conference additions for (BookmarkedConference conference : getBookmarkedConferences()) { - if(conference.isShared()) { + if (conference.isShared()) { continue; } buf.halfOpenElement("conference"); @@ -260,7 +260,7 @@ public class Bookmarks implements PrivateData { boolean done = false; while (!done) { int eventType = parser.next(); - if(eventType == XmlPullParser.START_TAG + if (eventType == XmlPullParser.START_TAG && "shared_bookmark".equals(parser.getName())) { urlStore.setShared(true); } @@ -291,7 +291,7 @@ public class Bookmarks implements PrivateData { else if (eventType == XmlPullParser.START_TAG && "password".equals(parser.getName())) { conf.setPassword(parser.nextText()); } - else if(eventType == XmlPullParser.START_TAG + else if (eventType == XmlPullParser.START_TAG && "shared_bookmark".equals(parser.getName())) { conf.setShared(true); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/DataListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/DataListener.java index 21c1f0d00..6a4bcadc5 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/DataListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/ibb/DataListener.java @@ -64,7 +64,7 @@ class DataListener extends AbstractIqRequestHandler { ibbSession.processIQPacket(data); } } - catch (NotConnectedException|InterruptedException e) { + catch (NotConnectedException | InterruptedException e) { return null; } return null; 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 04f4d6ac4..e4eeb8f63 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 @@ -415,7 +415,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream */ @Override public Socks5BytestreamSession establishSession(Jid targetJID, String sessionID) - throws IOException, InterruptedException, NoResponseException, SmackException, XMPPException{ + throws IOException, InterruptedException, NoResponseException, SmackException, XMPPException { XMPPConnection connection = connection(); XMPPErrorException discoveryException = null; // check if target supports SOCKS5 Bytestream @@ -556,7 +556,7 @@ public final class Socks5BytestreamManager extends Manager implements Bytestream try { proxyInfo = serviceDiscoveryManager.discoverInfo(item.getEntityID()); } - catch (NoResponseException|XMPPErrorException e) { + catch (NoResponseException | XMPPErrorException e) { // blacklist errornous server proxyBlacklist.add(item.getEntityID()); continue; 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 4a1006877..6f1b4bc3b 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 @@ -280,7 +280,7 @@ public final class Socks5Proxy { * @return true if the address was removed. */ public boolean removeLocalAddress(String address) { - synchronized(localAddresses) { + synchronized (localAddresses) { return localAddresses.remove(address); } } @@ -311,7 +311,7 @@ public final class Socks5Proxy { if (addresses == null) { throw new IllegalArgumentException("list must not be null"); } - synchronized(localAddresses) { + synchronized (localAddresses) { localAddresses.clear(); localAddresses.addAll(addresses); } 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 4b87c8ecf..70d333954 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 @@ -224,7 +224,7 @@ public class Bytestream extends IQ { @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { - switch(getType()) { + switch (getType()) { case set: xml.optAttribute("sid", getSessionID()); xml.optAttribute("mode", getMode()); 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 afcdfce6a..319fc94e4 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 @@ -717,7 +717,7 @@ public final class EntityCapsManager extends Manager { throw new AssertionError(e); } byte[] digest; - synchronized(md) { + synchronized (md) { digest = md.digest(bytes); } String version = Base64.encodeToString(digest); 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 0552fd9b1..e013362ce 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 @@ -105,10 +105,10 @@ public final class ChatStateManager extends Manager { * @throws InterruptedException */ public void setCurrentState(ChatState newState, org.jivesoftware.smack.chat.Chat chat) throws NotConnectedException, InterruptedException { - if(chat == null || newState == null) { + if (chat == null || newState == null) { throw new IllegalArgumentException("Arguments cannot be null."); } - if(!updateChatState(chat, newState)) { + if (!updateChatState(chat, newState)) { return; } Message message = new Message(); 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 89667770c..70a8286d9 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 @@ -140,7 +140,7 @@ public final class ServiceDiscoveryManager extends Manager { response.addItems(nodeInformationProvider.getNodeItems()); // Add packet extensions response.addExtensions(nodeInformationProvider.getNodePacketExtensions()); - } else if(discoverItems.getNode() != null) { + } else if (discoverItems.getNode() != null) { // Return error since client doesn't contain // the specified node response.setType(IQ.Type.error); @@ -761,7 +761,7 @@ public final class ServiceDiscoveryManager extends Manager { try { // Get the disco items and send the disco packet to each server item items = discoverItems(serviceName); - } catch(XMPPErrorException e) { + } catch (XMPPErrorException e) { LOGGER.log(Level.WARNING, "Could not discover items about service", e); return serviceDiscoInfo; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/provider/DiscoverInfoProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/provider/DiscoverInfoProvider.java index 9baaa3742..2a08d8cfc 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/provider/DiscoverInfoProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/provider/DiscoverInfoProvider.java @@ -74,7 +74,7 @@ public class DiscoverInfoProvider extends IQProvider { if (parser.getName().equals("feature")) { // Create a new feature and add it to the discovered info. boolean notADuplicateFeature = discoverInfo.addFeature(variable); - assert(notADuplicateFeature); + assert (notADuplicateFeature); } if (parser.getName().equals("query")) { done = true; 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 fe2639060..125b2671a 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 @@ -73,7 +73,7 @@ public class FaultTolerantNegotiator extends StreamNegotiator { private StreamNegotiator determineNegotiator(Stanza streamInitiation) { if (streamInitiation instanceof Bytestream) { return primaryNegotiator; - } else if (streamInitiation instanceof Open){ + } else if (streamInitiation instanceof Open) { return secondaryNegotiator; } else { throw new IllegalStateException("Unknown stream initation type"); 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 13220ffaf..a23f750ef 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 @@ -308,7 +308,7 @@ public abstract class FileTransfer { * Return the length of bytes written out to the stream. * @return the amount in bytes written out. */ - public long getAmountWritten(){ + public long getAmountWritten() { return amountWritten; } 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 ce2d0ae91..29422b5cb 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 @@ -162,7 +162,7 @@ public class OutgoingFileTransfer extends FileTransfer { final long fileSize, final String description, final NegotiationProgress progress) { - if(progress == null) { + if (progress == null) { throw new IllegalArgumentException("Callback progress cannot be null."); } checkTransferThread(); @@ -295,7 +295,7 @@ public class OutgoingFileTransfer extends FileTransfer { * @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){ + public synchronized void sendStream(final InputStream in, final String fileName, final long fileSize, final String description) { checkTransferThread(); setFileInfo(fileName, fileSize); @@ -409,7 +409,7 @@ public class OutgoingFileTransfer extends FileTransfer { @Override protected boolean updateStatus(Status oldStatus, Status newStatus) { boolean isUpdated = super.updateStatus(oldStatus, newStatus); - if(callback != null && isUpdated) { + if (callback != null && isUpdated) { callback.statusUpdated(oldStatus, newStatus); } return isUpdated; @@ -419,7 +419,7 @@ public class OutgoingFileTransfer extends FileTransfer { protected void setStatus(Status status) { Status oldStatus = getStatus(); super.setStatus(status); - if(callback != null) { + if (callback != null) { callback.statusUpdated(oldStatus, status); } } @@ -427,7 +427,7 @@ public class OutgoingFileTransfer extends FileTransfer { @Override protected void setException(Exception exception) { super.setException(exception); - if(callback != null) { + if (callback != null) { callback.errorEstablishingStream(exception); } } 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 1bc1de725..fb1c89c51 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 @@ -41,7 +41,9 @@ import org.jivesoftware.smack.chat.ChatMessageListener; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.FromMatchesFilter; import org.jivesoftware.smack.filter.MessageTypeFilter; +import org.jivesoftware.smack.filter.MessageWithBodiesFilter; import org.jivesoftware.smack.filter.MessageWithSubjectFilter; +import org.jivesoftware.smack.filter.MessageWithThreadFilter; import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smack.filter.OrFilter; import org.jivesoftware.smack.filter.PresenceTypeFilter; @@ -170,10 +172,6 @@ public class MultiUserChat { public void processStanza(Stanza packet) { Message msg = (Message) packet; EntityFullJid from = msg.getFrom().asEntityFullJidIfPossible(); - if (from == null) { - LOGGER.warning("Message subject not changed by a full JID: " + msg.getFrom()); - return; - } // Update the room subject subject = msg.getSubject(); // Fire event for subject updated listeners @@ -322,8 +320,17 @@ public class MultiUserChat { connection.addSyncStanzaListener(messageListener, fromRoomGroupchatFilter); connection.addSyncStanzaListener(presenceListener, new AndFilter(fromRoomFilter, StanzaTypeFilter.PRESENCE)); - connection.addSyncStanzaListener(subjectListener, new AndFilter(fromRoomFilter, - MessageWithSubjectFilter.INSTANCE, new NotFilter(MessageTypeFilter.ERROR))); + // @formatter:off + connection.addSyncStanzaListener(subjectListener, + new AndFilter(fromRoomFilter, + MessageWithSubjectFilter.INSTANCE, + new NotFilter(MessageTypeFilter.ERROR), + // According to XEP-0045 § 8.1 "A message with a and a or a and a is a + // legitimate message, but it SHALL NOT be interpreted as a subject change." + new NotFilter(MessageWithBodiesFilter.INSTANCE), + new NotFilter(MessageWithThreadFilter.INSTANCE)) + ); + // @formatter:on connection.addSyncStanzaListener(declinesListener, DECLINE_FILTER); connection.addPacketInterceptor(presenceInterceptor, new AndFilter(ToMatchesFilter.create(room), StanzaTypeFilter.PRESENCE)); 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 044a027e2..ec4c8ce15 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 @@ -112,10 +112,10 @@ public class Occupant { @Override public boolean equals(Object obj) { - if(!(obj instanceof Occupant)) { + if (!(obj instanceof Occupant)) { return false; } - Occupant occupant = (Occupant)obj; + Occupant occupant = (Occupant) obj; return jid.equals(occupant.jid); } @@ -124,7 +124,7 @@ public class Occupant { int result; result = affiliation.hashCode(); result = 17 * result + role.hashCode(); - result = 17 * result + jid.hashCode(); + result = 17 * result + (jid != null ? jid.hashCode() : 0); result = 17 * result + (nick != null ? nick.hashCode() : 0); return result; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/SubjectUpdatedListener.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/SubjectUpdatedListener.java index ee5f0e337..91bae3f1a 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/SubjectUpdatedListener.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/SubjectUpdatedListener.java @@ -30,7 +30,7 @@ public interface SubjectUpdatedListener { * Called when a MUC room has changed its subject. * * @param subject the new room's subject. - * @param from the user that changed the room's subject (e.g. room@conference.jabber.org/nick). + * @param from the user that changed the room's subject or null if the room itself changed the subject. */ public abstract void subjectUpdated(String subject, EntityFullJid from); 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 ac476a7d2..ac6b72bcc 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 @@ -247,7 +247,7 @@ public class MUCUser implements ExtensionElement { * @author Gaston Dombiak */ public static class Invite implements NamedElement { - public static final String ELEMENT ="invite"; + public static final String ELEMENT = "invite"; private final String reason; 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 2fc42be80..2b3ee1b6e 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 @@ -95,9 +95,9 @@ public final class PEPManager extends Manager { public void processStanza(Stanza stanza) { Message message = (Message) stanza; EventElement event = EventElement.from(stanza); - assert(event != null); + assert (event != null); EntityBareJid from = message.getFrom().asEntityBareJidIfPossible(); - assert(from != null); + assert (from != null); for (PEPListener listener : pepListeners) { listener.eventReceived(from, event, message); } 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 39b77e81d..fe329b9f7 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 @@ -31,16 +31,20 @@ import org.jivesoftware.smack.AbstractConnectionClosedListener; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.SmackException.NotLoggedInException; +import org.jivesoftware.smack.SmackFuture; +import org.jivesoftware.smack.SmackFuture.InternalSmackFuture; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.ConnectionCreationListener; import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.XMPPConnectionRegistry; -import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException.XMPPErrorException; import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ.Type; +import org.jivesoftware.smack.packet.XMPPError; +import org.jivesoftware.smack.packet.Stanza; import org.jivesoftware.smack.util.SmackExecutorThreadFactory; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.ping.packet.Ping; @@ -142,6 +146,71 @@ public final class PingManager extends Manager { maybeSchedulePingServerTask(); } + private boolean isValidErrorPong(Jid destinationJid, XMPPErrorException xmppErrorException) { + // If it is an error error response and the destination was our own service, then this must mean that the + // service responded, i.e. is up and pingable. + if (destinationJid.equals(connection().getServiceName())) { + return true; + } + + final XMPPError xmppError = xmppErrorException.getXMPPError(); + + // We may received an error response from an intermediate service returning an error like + // 'remote-server-not-found' or 'remote-server-timeout' to us (which would fake the 'from' address, + // see RFC 6120 § 8.3.1 2.). Or the recipient could became unavailable. + + // Sticking with the current rules of RFC 6120/6121, it is undecidable at this point whether we received an + // error response from the pinged entity or not. This is because a service-unavailable error condition is + // *required* (as per the RFCs) to be send back in both relevant cases: + // 1. When the receiving entity is unaware of the IQ request type. RFC 6120 § 8.4.: + // "If an intended recipient receives an IQ stanza of type "get" or + // "set" containing a child element qualified by a namespace it does + // not understand, then the entity MUST return an IQ stanza of type + // "error" with an error condition of . + // 2. When the receiving resource is not available. RFC 6121 § 8.5.3.2.3. + + // Some clients don't obey the first rule and instead send back a feature-not-implement condition with type 'cancel', + // which allows us to consider this response as valid "error response" pong. + XMPPError.Type type = xmppError.getType(); + XMPPError.Condition condition = xmppError.getCondition(); + return type == XMPPError.Type.CANCEL && condition == XMPPError.Condition.feature_not_implemented; + } + + public SmackFuture pingAsync(Jid jid) { + return pingAsync(jid, connection().getReplyTimeout()); + } + + public SmackFuture pingAsync(final Jid jid, long pongTimeout) { + final InternalSmackFuture future = new InternalSmackFuture() { + @Override + public void handleStanza(Stanza packet) throws NotConnectedException, InterruptedException { + setResult(true); + } + @Override + public boolean isNonFatalException(Exception exception) { + if (exception instanceof XMPPErrorException) { + XMPPErrorException xmppErrorException = (XMPPErrorException) exception; + if (isValidErrorPong(jid, xmppErrorException)) { + setResult(true); + return true; + } + } + return false; + } + }; + + Ping ping = new Ping(jid); + try { + XMPPConnection connection = getAuthenticatedConnectionOrThrow(); + connection.sendIqWithResponseCallback(ping, future, future, pongTimeout); + } + catch (NotLoggedInException | NotConnectedException | InterruptedException e) { + future.processException(e); + } + + return future; + } + /** * Pings the given jid. This method will return false if an error occurs. The exception * to this, is a server ping, which will always return true if the server is reachable, @@ -168,8 +237,8 @@ public final class PingManager extends Manager { try { connection.createStanzaCollectorAndSend(ping).nextResultOrThrow(pingTimeout); } - catch (XMPPException exc) { - return jid.equals(connection.getXMPPServiceDomain()); + catch (XMPPErrorException e) { + return isValidErrorPong(jid, e); } return true; } 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 afe170d51..b5a1e7e18 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 @@ -575,7 +575,7 @@ public final class PrivacyListManager extends Manager { * @throws NotConnectedException * @throws InterruptedException */ - public boolean isSupported() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException{ + public boolean isSupported() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return ServiceDiscoveryManager.getInstanceFor(connection()).serverSupportsFeature(NAMESPACE); } } 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 11b056a28..754d8e103 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 @@ -46,11 +46,11 @@ public class Privacy extends IQ { 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; + 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; + 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 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 da2ba07da..5e299244a 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 @@ -139,7 +139,7 @@ public class Affiliation implements ExtensionElement */ public boolean isAffiliationModification() { if (jid != null && affiliation != null) { - assert(node == null && namespace == PubSubNamespace.OWNER); + assert (node == null && namespace == PubSubNamespace.OWNER); return true; } return false; 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 97c4d086c..ef070cabb 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 @@ -55,6 +55,6 @@ public class ConfigurationEvent extends NodeExtension implements EmbeddedPacketE if (getConfiguration() == null) return Collections.emptyList(); else - return Arrays.asList(((ExtensionElement)getConfiguration().getDataFormToSend())); + return Arrays.asList(((ExtensionElement) getConfiguration().getDataFormToSend())); } } 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 2d03cc896..500c13704 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 @@ -61,7 +61,7 @@ public class EventElement implements EmbeddedPacketExtension @Override public List getExtensions() { - return Arrays.asList(new ExtensionElement[]{getEvent()}); + return Arrays.asList(new ExtensionElement[] {getEvent()}); } public NodeExtension getEvent() 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 6b53fd408..3d7153e09 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 @@ -134,7 +134,7 @@ public class ItemsExtension extends NodeExtension implements EmbeddedPacketExten @SuppressWarnings("unchecked") public List getExtensions() { - return (List)getItems(); + return (List) getItems(); } /** 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 2c7982416..926aa2e98 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 @@ -303,7 +303,7 @@ public class LeafNode extends Node public void publish(T item) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Collection items = new ArrayList(1); - items.add((item == null ? (T)new Item() : item)); + items.add((item == null ? (T) new Item() : item)); publish(items); } 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 dae02e80c..720e1433c 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 @@ -573,7 +573,7 @@ abstract public class Node private static List getSubscriptionIds(Stanza packet) { - HeadersExtension headers = (HeadersExtension)packet.getExtension("headers", "http://jabber.org/protocol/shim"); + HeadersExtension headers = (HeadersExtension) packet.getExtension("headers", "http://jabber.org/protocol/shim"); List values = null; if (headers != null) @@ -608,10 +608,8 @@ abstract public class Node @SuppressWarnings({ "rawtypes", "unchecked" }) public void processStanza(Stanza packet) { -// CHECKSTYLE:OFF - EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); -// CHECKSTYLE:ON - ItemsExtension itemsElem = (ItemsExtension)event.getEvent(); + EventElement event = (EventElement) packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); + ItemsExtension itemsElem = (ItemsExtension) event.getEvent(); ItemPublishEvent eventItems = new ItemPublishEvent(itemsElem.getNode(), itemsElem.getItems(), getSubscriptionIds(packet), DelayInformationManager.getDelayTimestamp(packet)); listener.handlePublishedItems(eventItems); } @@ -681,8 +679,8 @@ abstract public class Node @Override public void processStanza(Stanza packet) { - EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); - ConfigurationEvent config = (ConfigurationEvent)event.getEvent(); + EventElement event = (EventElement) packet.getExtension("event", PubSubNamespace.EVENT.getXmlns()); + ConfigurationEvent config = (ConfigurationEvent) event.getEvent(); listener.handleNodeConfiguration(config); } @@ -735,7 +733,7 @@ abstract public class Node if (embedEvent instanceof EmbeddedPacketExtension) { - List secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions(); + List secondLevelList = ((EmbeddedPacketExtension) embedEvent).getExtensions(); // XEP-0060 allows no elements on second level for notifications. See schema or // for example § 4.3: 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 ef0ac70f5..c8feeac6b 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 @@ -73,7 +73,7 @@ public enum PubSubElementType public static PubSubElementType valueOfFromElemName(String elemName, String namespace) { int index = namespace.lastIndexOf('#'); - String fragment = (index == -1 ? null : namespace.substring(index+1)); + String fragment = (index == -1 ? null : namespace.substring(index + 1)); if (fragment != null) { diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubException.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubException.java new file mode 100644 index 000000000..eb885981a --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubException.java @@ -0,0 +1,53 @@ +/** + * + * 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.pubsub; + +import org.jivesoftware.smack.SmackException; +import org.jxmpp.jid.BareJid; + +public abstract class PubSubException extends SmackException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public static class NotALeafNodeException extends PubSubException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private final String nodeId; + private final BareJid pubSubService; + + NotALeafNodeException(String nodeId, BareJid pubSubService) { + this.nodeId = nodeId; + this.pubSubService = pubSubService; + } + + public String getNodeId() { + return nodeId; + } + + public BareJid getPubSubService() { + return pubSubService; + } + + } +} 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 f89c29cc2..0ba6ffd70 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 @@ -16,8 +16,6 @@ */ package org.jivesoftware.smackx.pubsub; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -42,6 +40,7 @@ import org.jivesoftware.smack.packet.ExtensionElement; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverItems; +import org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException; import org.jivesoftware.smackx.pubsub.packet.PubSub; import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace; import org.jivesoftware.smackx.pubsub.util.NodeUtils; @@ -64,6 +63,8 @@ import org.jxmpp.stringprep.XmppStringprepException; */ public final class PubSubManager extends Manager { + public static final String AUTO_CREATE_FEATURE = "http://jabber.org/protocol/pubsub#auto-create"; + private static final Logger LOGGER = Logger.getLogger(PubSubManager.class.getName()); private static final Map> INSTANCES = new WeakHashMap<>(); @@ -267,10 +268,11 @@ public final class PubSubManager extends Manager { * @throws NotConnectedException * @throws InterruptedException * @throws XMPPErrorException + * @throws NotALeafNodeException in case the node already exists as collection node. * @since 4.2.1 */ public LeafNode getOrCreateLeafNode(final String id) - throws NoResponseException, NotConnectedException, InterruptedException, XMPPErrorException { + throws NoResponseException, NotConnectedException, InterruptedException, XMPPErrorException, NotALeafNodeException { try { return getNode(id); } @@ -287,42 +289,115 @@ public final class PubSubManager extends Manager { throw e2; } } + if (e1.getXMPPError().getCondition() == Condition.service_unavailable) { + // This could be caused by Prosody bug #805 (see https://prosody.im/issues/issue/805). Prosody does not + // answer to disco#info requests on the node ID, which makes it undecidable if a node is a leaf or + // collection node. + LOGGER.warning("The PubSub service " + pubSubService + + " threw an DiscoInfoNodeAssertionError, trying workaround for Prosody bug #805 (https://prosody.im/issues/issue/805)"); + return getOrCreateLeafNodeProsodyWorkaround(id); + } throw e1; } - catch (PubSubAssertionError.DiscoInfoNodeAssertionError e) { - // This could be caused by Prosody bug #805 (see https://prosody.im/issues/issue/805). Prosody does not - // answer to disco#info requests on the node ID, which makes it undecidable if a node is a leaf or - // collection node. - LOGGER.warning("The PubSub service " + pubSubService - + " threw an DiscoInfoNodeAssertionError, trying workaround for Prosody bug #805 (https://prosody.im/issues/issue/805)"); - return getOrCreateLeafNodeProsodyWorkaround(id); - } + } + + /** + * Try to get a leaf node with the given node ID. + * + * @param id the node ID. + * @return the requested leaf node. + * @throws NotALeafNodeException in case the node exists but is a collection node. + * @throws NoResponseException + * @throws NotConnectedException + * @throws InterruptedException + * @throws XMPPErrorException + * @since 4.2.1 + */ + public LeafNode getLeafNode(String id) throws NotALeafNodeException, NoResponseException, NotConnectedException, + InterruptedException, XMPPErrorException { + Node node; + try { + node = getNode(id); + } + catch (XMPPErrorException e) { + if (e.getXMPPError().getCondition() == Condition.service_unavailable) { + // This could be caused by Prosody bug #805 (see https://prosody.im/issues/issue/805). Prosody does not + // answer to disco#info requests on the node ID, which makes it undecidable if a node is a leaf or + // collection node. + return getLeafNodeProsodyWorkaround(id); + } + throw e; + } + + if (node instanceof LeafNode) { + return (LeafNode) node; + } + + throw new PubSubException.NotALeafNodeException(id, pubSubService); + } + + private LeafNode getLeafNodeProsodyWorkaround(final String id) throws NoResponseException, NotConnectedException, + InterruptedException, NotALeafNodeException, XMPPErrorException { + LeafNode leafNode = new LeafNode(this, id); + try { + // Try to ensure that this is not a collection node by asking for one item form the node. + leafNode.getItems(1); + } catch (XMPPErrorException e) { + Condition condition = e.getXMPPError().getCondition(); + if (condition == Condition.feature_not_implemented) { + // XEP-0060 § 6.5.9.5: Item retrieval not supported, e.g. because node is a collection node + throw new PubSubException.NotALeafNodeException(id, pubSubService); + } + + throw e; + } + + nodeMap.put(id, leafNode); + + return leafNode; } private LeafNode getOrCreateLeafNodeProsodyWorkaround(final String id) - throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { + throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException, NotALeafNodeException { try { return createNode(id); } catch (XMPPErrorException e1) { if (e1.getXMPPError().getCondition() == Condition.conflict) { - Constructor constructor = LeafNode.class.getDeclaredConstructors()[0]; - constructor.setAccessible(true); - LeafNode res; - try { - res = (LeafNode) constructor.newInstance(this, id); - } - catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e2) { - throw new AssertionError(e2); - } - // TODO: How to verify that this is actually a leafe node and not a conflict with a collection node? - return res; + return getLeafNodeProsodyWorkaround(id); } throw e1; } } + /** + * Try to publish an item and, if the node with the given ID does not exists, auto-create the node. + *

+ * Not every PubSub service supports automatic node creation. You can discover if this service supports it by using + * {@link #supportsAutomaticNodeCreation()}. + *

+ * + * @param id The unique id of the node. + * @param item The item to publish. + * @return the LeafNode on which the item was published. + * @throws NoResponseException + * @throws XMPPErrorException + * @throws NotConnectedException + * @throws InterruptedException + * @since 4.2.1 + */ + public LeafNode tryToPublishAndPossibleAutoCreate(String id, I item) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + LeafNode leafNode = new LeafNode(this, id); + leafNode.publish(item); + + // If LeafNode.publish() did not throw then we have successfully published an item and possible auto-created + // (XEP-0163 § 3., XEP-0060 § 7.1.4) the node. So we can put the node into the nodeMap. + nodeMap.put(id, leafNode); + + return leafNode; + } + /** * Get all the nodes that currently exist as a child of the specified * collection node. If the service does not support collection nodes @@ -440,6 +515,23 @@ public final class PubSubManager extends Manager { return mgr.discoverInfo(pubSubService); } + /** + * Check if the PubSub service supports automatic node creation. + * + * @return true if the PubSub service supports automatic node creation. + * @throws NoResponseException + * @throws XMPPErrorException + * @throws NotConnectedException + * @throws InterruptedException + * @since 4.2.1 + * @see XEP-0060 § 7.1.4 Automatic Node Creation + */ + public boolean supportsAutomaticNodeCreation() + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection()); + return sdm.supportsFeature(pubSubService, AUTO_CREATE_FEATURE); + } + /** * Check if it is possible to create PubSub nodes on this service. It could be possible that the * PubSub service allows only certain XMPP entities (clients) to create nodes and publish items 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 da8822447..1dbeb336c 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 @@ -61,7 +61,7 @@ public enum PubSubNamespace if (index != -1) { - String suffix = ns.substring(ns.lastIndexOf('#')+1); + String suffix = ns.substring(ns.lastIndexOf('#') + 1); return valueOf(suffix.toUpperCase(Locale.US)); } else 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 f1ba37f67..3e0ff9750 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 @@ -35,7 +35,7 @@ import org.jivesoftware.smackx.pubsub.AffiliationsExtension; @Override protected AffiliationsExtension createReturnExtension(String currentElement, String currentNamespace, Map attributeMap, List content) { - return new AffiliationsExtension((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 bd3da7331..2f5c26423 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 @@ -39,6 +39,6 @@ public class ConfigEventProvider extends EmbeddedExtensionProvider @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)); + 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 2766d9334..2c7a622c2 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 @@ -37,6 +37,6 @@ public class FormNodeProvider extends EmbeddedExtensionProvider @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())); + 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/SubscriptionsProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/provider/SubscriptionsProvider.java index d642df63b..60bec5c5d 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 @@ -36,7 +36,7 @@ public class SubscriptionsProvider extends EmbeddedExtensionProvider attributeMap, List content) { - return new SubscriptionsExtension(attributeMap.get("node"), (List)content); + return new SubscriptionsExtension(attributeMap.get("node"), (List) content); } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/search/ReportedData.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/search/ReportedData.java index 73a12c610..cfdbbaae0 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/search/ReportedData.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/search/ReportedData.java @@ -86,7 +86,7 @@ public class ReportedData { } - public ReportedData(){ + public ReportedData() { // Allow for model creation of ReportedData. } @@ -94,7 +94,7 @@ public class ReportedData { * Adds a new Row. * @param row the new row to add. */ - public void addRow(Row row){ + public void addRow(Row row) { rows.add(row); } @@ -102,7 +102,7 @@ public class ReportedData { * Adds a new Column. * @param column the column to add. */ - public void addColumn(Column column){ + public void addColumn(Column column) { columns.add(column); } @@ -206,7 +206,7 @@ public class ReportedData { * @return the values of the field whose variable matches the requested variable. */ public List getValues(String variable) { - for(Field field : getFields()) { + for (Field field : getFields()) { if (variable.equalsIgnoreCase(field.getVariable())) { return field.getValues(); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java index fa59f53d2..130e0a4b4 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java @@ -172,16 +172,16 @@ public class UserSearch extends SimpleIQ { FormField field = new FormField(name); // Handle hard coded values. - if(name.equals("first")){ + if (name.equals("first")) { field.setLabel("First Name"); } - else if(name.equals("last")){ + else if (name.equals("last")) { field.setLabel("Last Name"); } - else if(name.equals("email")){ + else if (name.equals("email")) { field.setLabel("Email Address"); } - else if(name.equals("nick")){ + else if (name.equals("nick")) { field.setLabel("Nickname"); } 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 f19b458f3..33cb87d8c 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 @@ -87,7 +87,7 @@ public class StreamInitiationProvider extends IQProvider { done = true; } else if (elementName.equals("file")) { long fileSize = 0; - if(size != null && size.trim().length() !=0){ + if (size != null && size.trim().length() != 0) { try { fileSize = Long.parseLong(size); } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java index fc67214a8..577905dcc 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java @@ -205,7 +205,7 @@ public class Form { } private static void validateThatFieldIsText(FormField field) { - switch(field.getType()) { + switch (field.getType()) { case text_multi: case text_private: case text_single: @@ -444,7 +444,7 @@ public class Form { if (isSubmitType()) { // Create a new DataForm that contains only the answered fields DataForm dataFormToSend = new DataForm(getType()); - for(FormField field : getFields()) { + for (FormField field : getFields()) { if (!field.getValues().isEmpty()) { dataFormToSend.addField(field); } 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 65976c575..c68ccbaa8 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 @@ -163,7 +163,7 @@ public class Socks5ByteStreamManagerTest { catch (FeatureNotSupportedException e) { assertTrue(e.getFeature().equals("SOCKS5 Bytestream")); assertTrue(e.getJid().equals(targetJID)); - } catch(Exception e) { + } catch (Exception e) { fail(e.getMessage()); } 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 b2d3da710..5b00cf86b 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 @@ -148,7 +148,7 @@ public class Socks5ProxyTest { proxy.addLocalAddress("same"); int sameCount = 0; - for(String localAddress : proxy.getLocalAddresses()) { + for (String localAddress : proxy.getLocalAddresses()) { if ("same".equals(localAddress)) { sameCount++; } 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 d3b60e2a3..208efeeef 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 @@ -176,7 +176,7 @@ public final class Socks5TestProxy { */ @SuppressWarnings("WaitNotInLoop") public Socket getSocket(String digest) { - synchronized(this) { + synchronized (this) { if (!startupComplete) { try { wait(5000); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/forward/ForwardedTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/forward/ForwardedTest.java index 3a1a6feed..4ce4601ef 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/forward/ForwardedTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/forward/ForwardedTest.java @@ -93,7 +93,7 @@ public class ForwardedTest { assertEquals("forwarded", parser.getName()); } - @Test(expected=Exception.class) + @Test(expected = Exception.class) public void forwardedEmptyTest() throws Exception { XmlPullParser parser; String control; diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/packet/GeoLocationTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/packet/GeoLocationTest.java index cec9fd1e1..c61477d8c 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/packet/GeoLocationTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/packet/GeoLocationTest.java @@ -75,32 +75,32 @@ public class GeoLocationTest extends InitExtensions { // @formatter:off final String geoLocationMessageString = "" - +"" - +"23" - +"1000" - +"Delhi" - +"10" - +"Small Building" - +"India" - +"IN" - +"My Description" - +"90" - +"top" - +"25.098345" - +"awesome" - +"77.992034" - +"110085" - +"North" - +"small" - +"250.0" - +"Wall Street" - +"Unit Testing GeoLocation" - +"2004-02-19" - +"+5:30" - +"http://xmpp.org" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "23" + + "1000" + + "Delhi" + + "10" + + "Small Building" + + "India" + + "IN" + + "My Description" + + "90" + + "top" + + "25.098345" + + "awesome" + + "77.992034" + + "110085" + + "North" + + "small" + + "250.0" + + "Wall Street" + + "Unit Testing GeoLocation" + + "2004-02-19" + + "+5:30" + + "http://xmpp.org" + + "" + + "
"; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationMessageString); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/provider/GeoLocationProviderTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/provider/GeoLocationProviderTest.java index be15d1a86..ec89d58f4 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/provider/GeoLocationProviderTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/geoloc/provider/GeoLocationProviderTest.java @@ -35,32 +35,32 @@ public class GeoLocationProviderTest extends InitExtensions { public void testGeoLocationProviderWithNoDatumSet() throws Exception { // @formatter:off final String geoLocationString = "" - +"" - +"23" - +"1000" - +"Delhi" - +"10" - +"Small Building" - +"India" - +"IN" - +"My Description" - +"90" - +"top" - +"25.098345" - +"awesome" - +"77.992034" - +"110085" - +"North" - +"small" - +"250.0" - +"Wall Street" - +"Unit Testing GeoLocation" - +"2004-02-19" - +"+5:30" - +"http://xmpp.org" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "23" + + "1000" + + "Delhi" + + "10" + + "Small Building" + + "India" + + "IN" + + "My Description" + + "90" + + "top" + + "25.098345" + + "awesome" + + "77.992034" + + "110085" + + "North" + + "small" + + "250.0" + + "Wall Street" + + "Unit Testing GeoLocation" + + "2004-02-19" + + "+5:30" + + "http://xmpp.org" + + "" + + "
"; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString); @@ -101,33 +101,33 @@ public class GeoLocationProviderTest extends InitExtensions { // @formatter:off final String geoLocationString = "" - +"" - +"23" - +"1000" - +"Delhi" - +"10" - +"Small Building" - +"India" - +"IN" - +"Test Datum" - +"My Description" - +"90" - +"top" - +"25.098345" - +"awesome" - +"77.992034" - +"110085" - +"North" - +"small" - +"250.0" - +"Wall Street" - +"Unit Testing GeoLocation" - +"2004-02-19" - +"+5:30" - +"http://xmpp.org" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "23" + + "1000" + + "Delhi" + + "10" + + "Small Building" + + "India" + + "IN" + + "Test Datum" + + "My Description" + + "90" + + "top" + + "25.098345" + + "awesome" + + "77.992034" + + "110085" + + "North" + + "small" + + "250.0" + + "Wall Street" + + "Unit Testing GeoLocation" + + "2004-02-19" + + "+5:30" + + "http://xmpp.org" + + "" + + ""; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString); @@ -168,11 +168,11 @@ public class GeoLocationProviderTest extends InitExtensions { // @formatter:off final String geoLocationString = "" - +"" - +"90" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "90" + + "" + + ""; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString); @@ -188,11 +188,11 @@ public class GeoLocationProviderTest extends InitExtensions { // @formatter:off final String geoLocationString = "" - +"" - +"90" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "90" + + "" + + ""; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString); @@ -208,12 +208,12 @@ public class GeoLocationProviderTest extends InitExtensions { // @formatter:off final String geoLocationString = "" - +"" - +"90" - +"100" - +"" - +""; + + " to='bassanio@merchantofvenice.lit'>" + + "" + + "90" + + "100" + + "" + + ""; // @formatter:on Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString); 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 1197aaa7b..7e7053177 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 @@ -26,7 +26,9 @@ import org.jivesoftware.smack.ThreadedDummyConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException.XMPPErrorException; import org.jivesoftware.smack.packet.XMPPError; +import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.packet.XMPPError.Condition; +import org.jivesoftware.smackx.InitExtensions; import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverInfo.Identity; import org.jivesoftware.smackx.pubsub.packet.PubSub; @@ -39,7 +41,7 @@ import org.junit.Test; * @author Robin Collier * */ -public class ConfigureFormTest +public class ConfigureFormTest extends InitExtensions { @Test public void checkChildrenAssocPolicy() @@ -55,6 +57,8 @@ public class ConfigureFormTest ThreadedDummyConnection con = ThreadedDummyConnection.newInstance(); PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); DiscoverInfo info = new DiscoverInfo(); + info.setType(Type.result); + info.setFrom(PubSubManagerTest.DUMMY_PUBSUB_SERVICE); Identity ident = new Identity("pubsub", null, "leaf"); info.addIdentity(ident); con.addIQReply(info); @@ -62,6 +66,8 @@ public class ConfigureFormTest Node node = mgr.getNode("princely_musings"); PubSub errorIq = new PubSub(); + errorIq.setType(Type.error); + errorIq.setFrom(PubSubManagerTest.DUMMY_PUBSUB_SERVICE); XMPPError.Builder error = XMPPError.getBuilder(Condition.forbidden); errorIq.setError(error); con.addIQReply(errorIq); @@ -76,7 +82,7 @@ public class ConfigureFormTest } } - @Test (expected=SmackException.class) + @Test(expected = SmackException.class) public void getConfigFormWithTimeout() throws XMPPException, SmackException, InterruptedException { ThreadedDummyConnection con = new ThreadedDummyConnection(); 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 2ef6cb4b0..0ebad1059 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 @@ -111,11 +111,11 @@ public class ItemValidationTest extends InitExtensions { assertEquals(EventElementType.items, event.getEventType()); assertEquals(1, event.getExtensions().size()); assertTrue(event.getExtensions().get(0) instanceof ItemsExtension); - assertEquals(1, ((ItemsExtension)event.getExtensions().get(0)).items.size()); + assertEquals(1, ((ItemsExtension) event.getExtensions().get(0)).items.size()); - ExtensionElement itemExt = ((ItemsExtension)event.getExtensions().get(0)).items.get(0); + ExtensionElement itemExt = ((ItemsExtension) event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof Item); - assertEquals("testid1", ((Item)itemExt).getId()); + assertEquals("testid1", ((Item) itemExt).getId()); } @Test @@ -137,10 +137,10 @@ public class ItemValidationTest extends InitExtensions { Stanza message = PacketParserUtils.parseMessage(parser); ExtensionElement eventExt = message.getExtension(PubSubNamespace.EVENT.getXmlns()); EventElement event = (EventElement) eventExt; - ExtensionElement itemExt = ((ItemsExtension)event.getExtensions().get(0)).items.get(0); + ExtensionElement itemExt = ((ItemsExtension) event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof PayloadItem); - PayloadItem item = (PayloadItem)itemExt; + PayloadItem item = (PayloadItem) itemExt; assertEquals("testid1", item.getId()); assertTrue(item.getPayload() instanceof SimplePayload); @@ -184,10 +184,10 @@ public class ItemValidationTest extends InitExtensions { Stanza message = PacketParserUtils.parseMessage(parser); ExtensionElement eventExt = message.getExtension(PubSubNamespace.EVENT.getXmlns()); EventElement event = (EventElement) eventExt; - ExtensionElement itemExt = ((ItemsExtension)event.getExtensions().get(0)).items.get(0); + ExtensionElement itemExt = ((ItemsExtension) event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof PayloadItem); - PayloadItem item = (PayloadItem)itemExt; + PayloadItem item = (PayloadItem) itemExt; assertEquals("testid1", item.getId()); assertTrue(item.getPayload() instanceof SimplePayload); @@ -222,15 +222,15 @@ public class ItemValidationTest extends InitExtensions { assertEquals(EventElementType.items, event.getEventType()); assertEquals(1, event.getExtensions().size()); assertTrue(event.getExtensions().get(0) instanceof ItemsExtension); - assertEquals(1, ((ItemsExtension)event.getExtensions().get(0)).items.size()); + assertEquals(1, ((ItemsExtension) event.getExtensions().get(0)).items.size()); - ExtensionElement itemExt = ((ItemsExtension)event.getExtensions().get(0)).items.get(0); + ExtensionElement itemExt = ((ItemsExtension) event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof PayloadItem); - PayloadItem item = (PayloadItem)itemExt; + PayloadItem item = (PayloadItem) itemExt; assertEquals("testid1", item.getId()); assertTrue(item.getPayload() instanceof SimplePayload); - assertXMLEqual(itemContent, ((SimplePayload)item.getPayload()).toXML().toString()); + assertXMLEqual(itemContent, ((SimplePayload) item.getPayload()).toXML().toString()); } } 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 a2f128125..3ff85f27b 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 @@ -60,7 +60,7 @@ public class DeliveryReceiptTest extends InitExtensions { parser = PacketParserUtils.getParserFor(control); Message p = PacketParserUtils.parseMessage(parser); - DeliveryReceiptRequest drr = (DeliveryReceiptRequest)p.getExtension( + DeliveryReceiptRequest drr = (DeliveryReceiptRequest) p.getExtension( DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE); assertNotNull(drr); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayoutTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayoutTest.java index 36959b1ec..0ace2ea16 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayoutTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdatalayout/packet/DataLayoutTest.java @@ -124,7 +124,7 @@ public class DataLayoutTest { assertEquals("Label - & \u00E9 \u00E1 ", layout.getLabel()); section = (Section) layout.getPageLayout().get(1); assertEquals("section Label - & \u00E9 \u00E1 ", section.getLabel()); - Text text = (Text)layout.getPageLayout().get(2); + Text text = (Text) layout.getPageLayout().get(2); assertEquals("PageText - & \u00E9 \u00E1 ", text.getText()); section = (Section) layout.getPageLayout().get(3); assertEquals("Number of Persons by
Nationality and Status", section.getLabel()); @@ -155,7 +155,7 @@ public class DataLayoutTest { assertEquals("Label - & \u00E9 \u00E1 ", layout.getLabel()); Section section = (Section) layout.getPageLayout().get(1); assertEquals("section Label - & \u00E9 \u00E1 ", section.getLabel()); - Text text = (Text)layout.getPageLayout().get(2); + Text text = (Text) layout.getPageLayout().get(2); assertEquals("PageText - & \u00E9 \u00E1 ", text.getText()); section = (Section) layout.getPageLayout().get(3); assertEquals("Number of Persons by
Nationality and Status", section.getLabel()); 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 c29dc8dbc..a50bc2c3e 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 @@ -122,7 +122,7 @@ public class DataValidationTest { assertEquals(TEST_OUTPUT_RANGE2, output); } - @Test(expected=NumberFormatException.class) + @Test(expected = NumberFormatException.class) public void testRangeFailure() throws IOException, XmlPullParserException { XmlPullParser parser = getParser(TEST_OUTPUT_FAIL); DataValidationProvider.parse(parser); diff --git a/smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java b/smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java index 5a9b6c97e..942370229 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java @@ -126,7 +126,7 @@ public class Chat { * @param listener a stanza(/packet) listener. */ public void addMessageListener(ChatMessageListener listener) { - if(listener == null) { + if (listener == null) { return; } // TODO these references should be weak. @@ -202,7 +202,7 @@ public class Chat { @Override public boolean equals(Object obj) { return obj instanceof Chat - && threadID.equals(((Chat)obj).getThreadID()) - && participant.equals(((Chat)obj).getParticipant()); + && threadID.equals(((Chat) obj).getThreadID()) + && participant.equals(((Chat) obj).getParticipant()); } } 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 897c06423..95757c9e7 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 @@ -164,7 +164,7 @@ public final class ChatManager extends Manager{ chat = getThreadChat(message.getThread()); } - if(chat == null) { + if (chat == null) { chat = createChat(message); } // The chat could not be created, abort here @@ -248,7 +248,7 @@ public final class ChatManager extends Manager{ thread = nextID(); } Chat chat = threadChats.get(thread); - if(chat != null) { + if (chat != null) { throw new IllegalArgumentException("ThreadID is already used"); } chat = createChat(userJID, thread, true); @@ -262,7 +262,7 @@ public final class ChatManager extends Manager{ jidChats.put(userJID, chat); baseJidChats.put(userJID.asEntityBareJid(), chat); - for(ChatManagerListener listener : chatManagerListeners) { + for (ChatManagerListener listener : chatManagerListeners) { listener.chatCreated(chat, createdLocally); } @@ -293,11 +293,11 @@ public final class ChatManager extends Manager{ EntityJid userJID = from.asEntityJidIfPossible(); if (userJID == null) { - LOGGER.warning("Message from JID without localpart: '" +message.toXML() + "'"); + LOGGER.warning("Message from JID without localpart: '" + message.toXML() + "'"); return null; } String threadID = message.getThread(); - if(threadID == null) { + if (threadID == null) { threadID = nextID(); } @@ -372,9 +372,9 @@ public final class ChatManager extends Manager{ } void sendMessage(Chat chat, Message message) throws NotConnectedException, InterruptedException { - for(Map.Entry interceptor : interceptors.entrySet()) { + for (Map.Entry interceptor : interceptors.entrySet()) { StanzaFilter filter = interceptor.getValue(); - if(filter != null && filter.accept(message)) { + if (filter != null && filter.accept(message)) { interceptor.getKey().processMessage(message); } } 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 286c968b7..0f9e18fe6 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 @@ -419,7 +419,7 @@ public final class Roster extends Manager { * @throws NotConnectedException * @throws InterruptedException */ - public void reload() throws NotLoggedInException, NotConnectedException, InterruptedException{ + public void reload() throws NotLoggedInException, NotConnectedException, InterruptedException { final XMPPConnection connection = getAuthenticatedConnectionOrThrow(); RosterPacket packet = new RosterPacket(); @@ -1307,7 +1307,7 @@ public final class Roster extends Manager { // Remove user from the remaining groups. List oldGroupNames = new ArrayList(); - for (RosterGroup group: getGroups()) { + for (RosterGroup group : getGroups()) { oldGroupNames.add(group.getName()); } oldGroupNames.removeAll(newGroupNames); @@ -1329,7 +1329,7 @@ public final class Roster extends Manager { move(user, presenceMap, nonRosterPresenceMap); deletedEntries.add(user); - for (Entry e: groups.entrySet()) { + for (Entry e : groups.entrySet()) { RosterGroup group = e.getValue(); group.removeEntryLocal(entry); if (group.getEntryCount() == 0) { 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 edac93801..42df082c5 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 @@ -123,7 +123,7 @@ public final class RosterEntry extends Manager { * @param subscriptionPending TODO */ void updateItem(RosterPacket.Item item) { - assert(item != null); + assert (item != null); this.item = item; } @@ -145,7 +145,7 @@ public final class RosterEntry extends Manager { List results = new ArrayList(); // Loop through all roster groups and find the ones that contain this // entry. This algorithm should be fine - for (RosterGroup group: roster.getGroups()) { + for (RosterGroup group : roster.getGroups()) { if (group.contains(this)) { results.add(group); } @@ -256,7 +256,7 @@ public final class RosterEntry extends Manager { return true; } if (object != null && object instanceof RosterEntry) { - return getJid().equals(((RosterEntry)object).getJid()); + return getJid().equals(((RosterEntry) object).getJid()); } else { return false; @@ -283,14 +283,46 @@ public final class RosterEntry extends Manager { return other.item.equals(this.item); } + /** + * Convert the RosterEntry to a Roster stanza <item/> element. + * + * @param entry the roster entry. + * @return the roster item. + */ static RosterPacket.Item toRosterItem(RosterEntry entry) { - return toRosterItem(entry, entry.getName()); + return toRosterItem(entry, entry.getName(), false); } - private static RosterPacket.Item toRosterItem(RosterEntry entry, String name) { + /** + * Convert the RosterEntry to a Roster stanza <item/> element. + * + * @param entry the roster entry + * @param name the name of the roster item. + * @return the roster item. + */ + static RosterPacket.Item toRosterItem(RosterEntry entry, String name) { + return toRosterItem(entry, name, false); + } + + static RosterPacket.Item toRosterItem(RosterEntry entry, boolean includeAskAttribute) { + return toRosterItem(entry, entry.getName(), includeAskAttribute); + } + + /** + * Convert a roster entry with the given name to a roster item. As per RFC 6121 § 2.1.2.2., clients MUST NOT include + * the 'ask' attribute, thus set {@code includeAskAttribute} to {@code false}. + * + * @param entry the roster entry. + * @param name the name of the roster item. + * @param includeAskAttribute whether or not to include the 'ask' attribute. + * @return the roster item. + */ + private static RosterPacket.Item toRosterItem(RosterEntry entry, String name, boolean includeAskAttribute) { RosterPacket.Item item = new RosterPacket.Item(entry.getJid(), name); item.setItemType(entry.getType()); - item.setSubscriptionPending(entry.isSubscriptionPending()); + if (includeAskAttribute) { + item.setSubscriptionPending(entry.isSubscriptionPending()); + } item.setApproved(entry.isApproved()); // Set the correct group names for the item. for (RosterGroup group : entry.getGroups()) { diff --git a/smack-im/src/main/java/org/jivesoftware/smack/roster/provider/RosterPacketProvider.java b/smack-im/src/main/java/org/jivesoftware/smack/roster/provider/RosterPacketProvider.java index bec356350..ded1acb1a 100644 --- a/smack-im/src/main/java/org/jivesoftware/smack/roster/provider/RosterPacketProvider.java +++ b/smack-im/src/main/java/org/jivesoftware/smack/roster/provider/RosterPacketProvider.java @@ -41,7 +41,7 @@ public class RosterPacketProvider extends IQProvider { outerloop: while (true) { int eventType = parser.next(); - switch(eventType) { + switch (eventType) { case XmlPullParser.START_TAG: String startTag = parser.getName(); switch (startTag) { @@ -53,7 +53,7 @@ public class RosterPacketProvider extends IQProvider { break; case XmlPullParser.END_TAG: String endTag = parser.getName(); - switch(endTag) { + switch (endTag) { case IQ.QUERY_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; @@ -84,7 +84,7 @@ public class RosterPacketProvider extends IQProvider { boolean approved = ParserUtils.getBooleanAttribute(parser, "approved", false); item.setApproved(approved); - outerloop: while(true) { + outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: @@ -106,7 +106,7 @@ public class RosterPacketProvider extends IQProvider { } } ParserUtils.assertAtEndTag(parser); - assert(item != null); + assert (item != null); return item; } } 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 fe3e87c8b..10cf35e21 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 @@ -227,10 +227,10 @@ public class RosterTest extends InitSmackIm { contactName, item.getName()); assertTrue("The updated contact doesn't belong to the requested groups (" - + contactGroups[0] +")!", + + contactGroups[0] + ")!", item.getGroupNames().contains(contactGroups[0])); assertTrue("The updated contact doesn't belong to the requested groups (" - + contactGroups[1] +")!", + + contactGroups[1] + ")!", item.getGroupNames().contains(contactGroups[1])); assertSame("The provided group number doesn't match the requested!", contactGroups.length, @@ -257,10 +257,10 @@ public class RosterTest extends InitSmackIm { contactName, addedEntry.getName()); assertTrue("The updated contact doesn't belong to the requested groups (" - + contactGroups[0] +")!", + + contactGroups[0] + ")!", roster.getGroup(contactGroups[0]).contains(addedEntry)); assertTrue("The updated contact doesn't belong to the requested groups (" - + contactGroups[1] +")!", + + contactGroups[1] + ")!", roster.getGroup(contactGroups[1]).contains(addedEntry)); assertSame("The updated contact should be member of two groups!", contactGroups.length, @@ -399,7 +399,7 @@ public class RosterTest extends InitSmackIm { * * @see SMACK-294 */ - @Test(timeout=5000) + @Test(timeout = 5000) public void testAddEmptyGroupEntry() throws Throwable { // Constants for the new contact final BareJid contactJID = JidCreate.entityBareFrom("nurse@example.com"); @@ -516,9 +516,9 @@ public class RosterTest extends InitSmackIm { * @param roster the roster (or buddy list) which should be initialized. */ public static void removeAllRosterEntries(DummyConnection connection, Roster roster) { - for(RosterEntry entry : roster.getEntries()) { + for (RosterEntry entry : roster.getEntries()) { // prepare the roster push packet - final RosterPacket rosterPush= new RosterPacket(); + final RosterPacket rosterPush = new RosterPacket(); rosterPush.setType(Type.set); rosterPush.setTo(connection.getUser()); diff --git a/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterVersioningTest.java b/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterVersioningTest.java index e3e15b96e..1cd34f7e6 100644 --- a/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterVersioningTest.java +++ b/smack-im/src/test/java/org/jivesoftware/smack/roster/RosterVersioningTest.java @@ -142,7 +142,7 @@ public class RosterVersioningTest { // but a shortcut in the test implementation. Stanza sentPacket = connection.getSentPacket(); if (sentPacket instanceof RosterPacket) { - RosterPacket sentRP = (RosterPacket)sentPacket; + RosterPacket sentRP = (RosterPacket) sentPacket; RosterPacket answer = new RosterPacket(); answer.setStanzaId(sentRP.getStanzaId()); answer.setType(Type.result); @@ -254,7 +254,7 @@ public class RosterVersioningTest { // but a shortcut in the test implementation. Stanza sentPacket = connection.getSentPacket(); if (sentPacket instanceof RosterPacket) { - final IQ emptyIQ = IQ.createResultIQ((RosterPacket)sentPacket); + final IQ emptyIQ = IQ.createResultIQ((RosterPacket) sentPacket); connection.processStanza(emptyIQ); } else { assertTrue("Expected to get a RosterPacket ", false); 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 176d42463..81911aebe 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 @@ -70,7 +70,7 @@ public class SubscriptionPreApprovalTest extends InitSmackIm { connection = null; } - @Test(expected=FeatureNotSupportedException.class) + @Test(expected = FeatureNotSupportedException.class) public void testPreApprovalNotSupported() throws Throwable { final Jid contactJID = JidCreate.from("preapproval@example.com"); roster.preApprove(contactJID.asBareJid()); diff --git a/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/SmackIntegrationTestFramework.java b/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/SmackIntegrationTestFramework.java index c23c5a56e..9e9feec00 100644 --- a/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/SmackIntegrationTestFramework.java +++ b/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/SmackIntegrationTestFramework.java @@ -537,7 +537,7 @@ public class SmackIntegrationTestFramework { throw new IllegalStateException(); } if (StringUtils.isNullOrEmpty(accountUsername)) { - accountUsername = USERNAME_PREFIX + '-' + middlefix + '-' +testRunResult.testRunId; + accountUsername = USERNAME_PREFIX + '-' + middlefix + '-' + testRunResult.testRunId; } if (StringUtils.isNullOrEmpty(accountPassword)) { accountPassword = StringUtils.insecureRandomString(16); diff --git a/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/util/ResultSyncPoint.java b/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/util/ResultSyncPoint.java index 71c907781..37b143934 100644 --- a/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/util/ResultSyncPoint.java +++ b/smack-integration-test/src/main/java/org/igniterealtime/smack/inttest/util/ResultSyncPoint.java @@ -26,7 +26,7 @@ public class ResultSyncPoint { private E exception; public R waitForResult(long timeout) throws E, InterruptedException, TimeoutException { - synchronized(this) { + synchronized (this) { if (result != null) { return result; } @@ -51,14 +51,14 @@ public class ResultSyncPoint { public void signal(R result) { - synchronized(this) { + synchronized (this) { this.result = Objects.requireNonNull(result); notifyAll(); } } public void signal(E exception) { - synchronized(this) { + synchronized (this) { this.exception = Objects.requireNonNull(exception); notifyAll(); } diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadIntegrationTest.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadIntegrationTest.java index c846aad07..779a6d0c0 100644 --- a/smack-integration-test/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadIntegrationTest.java +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadIntegrationTest.java @@ -39,7 +39,7 @@ import org.jivesoftware.smack.XMPPException.XMPPErrorException; public class HttpFileUploadIntegrationTest extends AbstractSmackIntegrationTest { - private static final int FILE_SIZE = 1024*128; + private static final int FILE_SIZE = 1024 * 128; private final HttpFileUploadManager hfumOne; diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/ping/PingIntegrationTest.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/ping/PingIntegrationTest.java index 5bcb22bc9..4347d7382 100644 --- a/smack-integration-test/src/main/java/org/jivesoftware/smackx/ping/PingIntegrationTest.java +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/ping/PingIntegrationTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2015 Florian Schmaus + * Copyright 2015-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. @@ -18,10 +18,23 @@ package org.jivesoftware.smackx.ping; import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest; import org.igniterealtime.smack.inttest.SmackIntegrationTest; import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment; import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.XMPPConnection; +import org.jxmpp.jid.Jid; public class PingIntegrationTest extends AbstractSmackIntegrationTest { @@ -35,4 +48,52 @@ public class PingIntegrationTest extends AbstractSmackIntegrationTest { assertTrue(pingManager.pingMyServer()); } + private static final class Pinger implements Runnable { + private final List toPing; + private final Collection> pongFutures; + + private final PingManager pingManager; + + private Pinger(XMPPConnection connection, Collection> pongFutures, Jid... toPing) { + this(connection, pongFutures, Arrays.asList(toPing)); + } + + private Pinger(XMPPConnection connection, Collection> pongFutures, List toPing) { + this.toPing = toPing; + this.pongFutures = pongFutures; + + this.pingManager = PingManager.getInstanceFor(connection); + } + + @Override + public void run() { + List> futures = new ArrayList<>(); + for (Jid jid : toPing) { + Future future = pingManager.pingAsync(jid); + futures.add(future); + } + pongFutures.addAll(futures); + } + } + + @SmackIntegrationTest + public void pingAsync() throws InterruptedException, ExecutionException { + List> pongFutures = Collections.synchronizedList(new ArrayList>()); + Runnable[] pinger = new Runnable[3]; + pinger[0] = new Pinger(conOne, pongFutures, conTwo.getUser(), conThree.getUser()); + pinger[1] = new Pinger(conTwo, pongFutures, conOne.getUser(), conThree.getUser()); + pinger[2] = new Pinger(conThree, pongFutures, conOne.getUser(), conTwo.getUser()); + + ExecutorService executorService = Executors.newFixedThreadPool(pinger.length); + for (Runnable runnable : pinger) { + executorService.execute(runnable); + } + + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + + for (Future pongFuture : pongFutures) { + assertTrue(pongFuture.get()); + } + } } 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 5abf686f0..a40bf17a0 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 @@ -102,7 +102,7 @@ public class FormTest extends AbstractSmackIntegrationTest { chat.sendMessage(msg); // Get the message with the form to fill out - Message msg2 = (Message)collector2.nextResult(); + Message msg2 = (Message) collector2.nextResult(); assertNotNull("Messge not found", msg2); // Retrieve the form to fill out Form formToRespond = Form.getFormFrom(msg2); diff --git a/smack-integration-test/src/test/java/org/igniterealtime/smack/inttest/util/ResultSyncPointTest.java b/smack-integration-test/src/test/java/org/igniterealtime/smack/inttest/util/ResultSyncPointTest.java index 27d52e25b..e64e26f89 100644 --- a/smack-integration-test/src/test/java/org/igniterealtime/smack/inttest/util/ResultSyncPointTest.java +++ b/smack-integration-test/src/test/java/org/igniterealtime/smack/inttest/util/ResultSyncPointTest.java @@ -44,7 +44,7 @@ public class ResultSyncPointTest { assertEquals(result, receivedResult); } - @Test(expected=TestException.class) + @Test(expected = TestException.class) public void exceptionTestResultSyncPoint() throws InterruptedException, TimeoutException, Exception { final CyclicBarrier barrier = new CyclicBarrier(2); final ResultSyncPoint rsp = new ResultSyncPoint<>(); 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 dd2932986..488354f00 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 @@ -213,7 +213,7 @@ public class AudioChannel { // Wait for it to configure boolean result = waitForState(processor, Processor.Configured); - if (!result){ + if (!result) { return "Couldn't configure processor"; } @@ -221,7 +221,7 @@ public class AudioChannel { TrackControl[] tracks = processor.getTrackControls(); // Do we have atleast one track? - if (tracks == null || tracks.length < 1){ + if (tracks == null || tracks.length < 1) { return "Couldn't find tracks in processor"; } 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 262b32936..7848c792e 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 @@ -54,7 +54,7 @@ public class AudioMediaSession extends JingleMediaSession { */ public AudioMediaSession(final PayloadType payloadType, final TransportCandidate remote, final TransportCandidate local, String locator, JingleSession jingleSession) { - super(payloadType, remote, local, locator==null?"dsound://":locator,jingleSession); + super(payloadType, remote, local, locator == null ? "dsound://" : locator,jingleSession); initialize(); } 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 4cc76268e..aab8eb3bb 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 @@ -79,18 +79,18 @@ public class AudioMediaSession extends JingleMediaSession implements MediaSessio /** * The master key. Hardcoded for now. */ - byte[] masterKey = new byte[]{(byte) 0xE1, (byte) 0xF9, 0x7A, 0x0D, 0x3E, 0x01, (byte) 0x8B, (byte) 0xE0, (byte) 0xD6, 0x4F, (byte) 0xA3, 0x2C, 0x06, (byte) 0xDE, 0x41, 0x39}; + byte[] masterKey = new byte[] {(byte) 0xE1, (byte) 0xF9, 0x7A, 0x0D, 0x3E, 0x01, (byte) 0x8B, (byte) 0xE0, (byte) 0xD6, 0x4F, (byte) 0xA3, 0x2C, 0x06, (byte) 0xDE, 0x41, 0x39}; /** * The master salt. Hardcoded for now. */ - byte[] masterSalt = new byte[]{0x0E, (byte) 0xC6, 0x75, (byte) 0xAD, 0x49, (byte) 0x8A, (byte) 0xFE, (byte) 0xEB, (byte) 0xB6, (byte) 0x96, 0x0B, 0x3A, (byte) 0xAB, (byte) 0xE6}; + byte[] masterSalt = new byte[] {0x0E, (byte) 0xC6, 0x75, (byte) 0xAD, 0x49, (byte) 0x8A, (byte) 0xFE, (byte) 0xEB, (byte) 0xB6, (byte) 0x96, 0x0B, 0x3A, (byte) 0xAB, (byte) 0xE6}; DatagramSocket[] localPorts = MediaSession.getLocalPorts(InetAddress.getByName(localhost), localPort); MediaSession session = MediaSession.createInstance(remoteHost, remotePort, localPorts, quality, secure, masterKey, masterSalt); session.setListener(eventHandler); - session.setSourceDescription(new SourceDescription[]{new SourceDescription(SourceDescription.SOURCE_DESC_NAME, "Superman", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_EMAIL, "cdcie.tester@je.jfcom.mil", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_LOC, InetAddress.getByName(localhost) + " Port " + session.getLocalDataPort(), 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_TOOL, "JFCOM CDCIE Audio Chat", 1, false)}); + session.setSourceDescription(new SourceDescription[] {new SourceDescription(SourceDescription.SOURCE_DESC_NAME, "Superman", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_EMAIL, "cdcie.tester@je.jfcom.mil", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_LOC, InetAddress.getByName(localhost) + " Port " + session.getLocalDataPort(), 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_TOOL, "JFCOM CDCIE Audio Chat", 1, false)}); return session; } 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 9edb92662..581e4c6eb 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 @@ -69,7 +69,7 @@ public abstract class AbstractBufferedImageOp implements BufferedImageOp, Clonea 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 (int[]) image.getRaster().getDataElements(x, y, width, height, pixels); return image.getRGB(x, y, width, height, pixels, 0, width); } 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 2f1a8564e..5e93dad8d 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 @@ -167,8 +167,8 @@ public class ImageReceiver extends Canvas { this.decoder = decoder; } - public void stop(){ - this.on=false; + public void stop() { + this.on = false; socket.close(); } } 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 922700a79..48271a50a 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 @@ -61,10 +61,10 @@ public class OctTreeQuantizer implements Quantizer { 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)); + 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); + leaf[i].list(s, level + 2); } } @@ -77,8 +77,8 @@ public class OctTreeQuantizer implements Quantizer { public OctTreeQuantizer() { setup(256); - colorList = new ArrayList<>(MAX_LEVEL+1); - for (int i = 0; i < MAX_LEVEL+1; i++) + colorList = new ArrayList<>(MAX_LEVEL + 1); + for (int i = 0; i < MAX_LEVEL + 1; i++) colorList.add(i, new Vector()); root = new OctTreeNode(); } @@ -102,7 +102,7 @@ public class OctTreeQuantizer implements Quantizer { @Override public void addPixels(int[] pixels, int offset, int count) { for (int i = 0; i < count; i++) { - insertColor(pixels[i+offset]); + insertColor(pixels[i + offset]); if (colors > reduceColors) reduceTree(reduceColors); } @@ -203,7 +203,7 @@ public class OctTreeQuantizer implements Quantizer { } private void reduceTree(int numColors) { - for (int level = MAX_LEVEL-1; level >= 0; level--) { + 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++) { @@ -222,7 +222,7 @@ public class OctTreeQuantizer implements Quantizer { node.children--; colors--; nodes--; - colorList.get(level+1).removeElement(child); + colorList.get(level + 1).removeElement(child); } } node.isLeaf = true; @@ -273,9 +273,9 @@ public class OctTreeQuantizer implements Quantizer { if (node.isLeaf) { int count = node.count; table[index] = 0xff000000 | - ((node.totalRed/count) << 16) | - ((node.totalGreen/count) << 8) | - node.totalBlue/count; + ((node.totalRed / count) << 16) | + ((node.totalGreen / count) << 8) | + node.totalBlue / count; node.index = index++; } else { for (int i = 0; i < 8; i++) { 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 525997ef0..bc616ab3f 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 @@ -62,14 +62,14 @@ public class PixelUtils { } public static int interpolate(int v1, int v2, float f) { - return clamp((int)(v1+f*(v2-v1))); + 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; + return (r + g + b) / 3; } public static boolean nearColors(int rgb1, int rgb2, int tolerance) { @@ -79,7 +79,7 @@ public class PixelUtils { 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; + 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 @@ -120,24 +120,24 @@ public class PixelUtils { b1 = Math.max(b1, b2); break; case ADD: - r1 = clamp(r1+r2); - g1 = clamp(g1+g2); - b1 = clamp(b1+b2); + 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); + 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)); + 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); + r1 = clamp(r1 * r2 / 255); + g1 = clamp(g1 * g2 / 255); + b1 = clamp(b1 * b2 / 255); break; case DISSOLVE: if ((randomGenerator.nextInt() & 0xff) <= a1) { @@ -147,9 +147,9 @@ public class PixelUtils { } break; case AVERAGE: - r1 = (r1+r2)/2; - g1 = (g1+g2)/2; - b1 = (b1+b2)/2; + r1 = (r1 + r2) / 2; + g1 = (g1 + g2) / 2; + b1 = (b1 + b2) / 2; break; case HUE: case SATURATION: @@ -198,25 +198,25 @@ public class PixelUtils { 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); + 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; + a1 = a1 * a2 / 255; return (a1 << 24) | (r2 << 16) | (g2 << 8) | b2; case ALPHA_TO_GRAY: - int na = 255-a1; + 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); + 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 7153538fe..55b6803c5 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 @@ -37,7 +37,7 @@ public class QuantizeFilter extends WholeImageFilter { 0, 0, 7, 3, 5, 1, }; - private int sum = 3+5+7+1; + private int sum = 3 + 5 + 7 + 1; private boolean dither; private int numColors = 256; @@ -92,7 +92,7 @@ public class QuantizeFilter extends WholeImageFilter { } public void quantize(int[] inPixels, int[] outPixels, int width, int height, int numColors, boolean dither, boolean serpentine) { - int count = width*height; + int count = width * height; Quantizer quantizer = new OctTreeQuantizer(); quantizer.setup(numColors); quantizer.addPixels(inPixels, 0, count); @@ -107,10 +107,10 @@ public class QuantizeFilter extends WholeImageFilter { boolean reverse = serpentine && (y & 1) == 1; int direction; if (reverse) { - index = y*width+width-1; + index = y * width + width - 1; direction = -1; } else { - index = y*width; + index = y * width; direction = 1; } for (int x = 0; x < width; x++) { @@ -127,30 +127,30 @@ public class QuantizeFilter extends WholeImageFilter { 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; + int iy = i + y; if (0 <= iy && iy < height) { for (int j = -1; j <= 1; j++) { - int jx = j+x; + int jx = j + x; if (0 <= jx && jx < width) { int w; if (reverse) - w = matrix[(i+1)*3-j+1]; + w = matrix[(i + 1) * 3 - j + 1]; else - w = matrix[(i+1)*3+j+1]; + 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; + 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); } } @@ -165,7 +165,7 @@ public class QuantizeFilter extends WholeImageFilter { @Override protected int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace) { - int[] outPixels = new int[width*height]; + int[] outPixels = new int[width * height]; quantize(inPixels, outPixels, width, height, numColors, dither, serpentine); 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 58b65413c..e097cf659 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 @@ -245,7 +245,7 @@ public class ICECandidate extends TransportCandidate implements Comparable nics = NetworkInterface.getNetworkInterfaces(); short i = 0; NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress()); - while(nics.hasMoreElements()) { + while (nics.hasMoreElements()) { NetworkInterface checkNIC = nics.nextElement(); if (checkNIC.equals(nic)) { nicNum = i; 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 918bd0f2f..6df40c534 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 @@ -518,7 +518,7 @@ public class RTPBridge extends IQ { // Cancel the collector. collector.cancel(); - if(response == null) return null; + if (response == null) return null; if (response.getIp() == null || response.getIp().equals("")) return null; @@ -529,7 +529,7 @@ public class RTPBridge extends IQ { catch (SocketException e) { LOGGER.log(Level.WARNING, "exception", e); } - while (ifaces!=null&&ifaces.hasMoreElements()) { + while (ifaces != null && ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration iaddresses = iface.getInetAddresses(); 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 b72537212..887f99cce 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 @@ -294,7 +294,7 @@ public class STUNResolver extends TransportResolver { @Override public void initialize() throws XMPPException { LOGGER.fine("Initialized"); - if (!isResolving()&&!isResolved()) { + if (!isResolving() && !isResolved()) { // Get the best STUN server available if (currentServer.isNull()) { loadSTUNServers(); 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 881cbff70..483461d46 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 @@ -80,7 +80,7 @@ public class TcpUdpBridgeClient { localUdpSocket.receive(p); if (p.getLength() == 0) continue; - LOGGER.fine("UDP Client Received and Sending to TCP Server:"+new String(p.getData(),0,p.getLength(),"UTF-8")); + LOGGER.fine("UDP Client Received and Sending to TCP Server:" + new String(p.getData(), 0, p.getLength(), "UTF-8")); out.write(p.getData(), 0, p.getLength()); out.flush(); @@ -112,7 +112,7 @@ public class TcpUdpBridgeClient { int s = in.read(b); //if (s == -1) continue; - LOGGER.fine("TCP Client:" +new String(b,0,s,"UTF-8")); + LOGGER.fine("TCP Client:" + new String(b, 0, s, "UTF-8")); DatagramPacket udpPacket = new DatagramPacket(b, s); 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 8d94447cd..88a8a1cbb 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 @@ -123,7 +123,7 @@ public abstract class JingleContentDescription implements ExtensionElement { JinglePayloadType jpt = jinglePtsIter.next(); if (jpt instanceof JinglePayloadType.Audio) { JinglePayloadType.Audio jpta = (JinglePayloadType.Audio) jpt; - result.add((PayloadType.Audio)jpta.getPayloadType()); + result.add((PayloadType.Audio) jpta.getPayloadType()); } } 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 d9ac2f0e2..997f013e4 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 @@ -325,7 +325,7 @@ public class JingleTransport implements ExtensionElement { protected String getChildElements() { StringBuilder buf = new StringBuilder(); - if (transportCandidate != null) {// && transportCandidate instanceof ICECandidate) { + if (transportCandidate != null) { // && transportCandidate instanceof ICECandidate) { ICECandidate tci = (ICECandidate) transportCandidate; // We convert the transportElement candidate to XML here... diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentRoster.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentRoster.java index d1c5d5698..e3e8505e7 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentRoster.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentRoster.java @@ -225,7 +225,7 @@ public class AgentRoster { while (it.hasNext()) { p = userPresences.get(it.next()); - if (presence == null){ + if (presence == null) { presence = p; } else { @@ -276,13 +276,13 @@ public class AgentRoster { for (int i = 0; i < listeners.length; i++) { switch (eventType) { case EVENT_AGENT_ADDED: - listeners[i].agentAdded((String)eventObject); + listeners[i].agentAdded((String) eventObject); break; case EVENT_AGENT_REMOVED: - listeners[i].agentRemoved((String)eventObject); + listeners[i].agentRemoved((String) eventObject); break; case EVENT_PRESENCE_CHANGED: - listeners[i].presenceChanged((Presence)eventObject); + listeners[i].presenceChanged((Presence) eventObject); break; } } @@ -295,7 +295,7 @@ public class AgentRoster { private class PresencePacketListener implements StanzaListener { @Override public void processStanza(Stanza packet) { - Presence presence = (Presence)packet; + Presence presence = (Presence) packet; EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible(); if (from == null) { // TODO Check if we need to ignore these presences or this is a server bug? @@ -308,7 +308,7 @@ public class AgentRoster { // for a particular user a map with the presence packets saved for each resource. if (presence.getType() == Presence.Type.available) { // Ignore the presence packet unless it has an agent status extension. - AgentStatus agentStatus = (AgentStatus)presence.getExtension( + AgentStatus agentStatus = (AgentStatus) presence.getExtension( AgentStatus.ELEMENT_NAME, AgentStatus.NAMESPACE); if (agentStatus == null) { return; @@ -373,7 +373,7 @@ public class AgentRoster { @Override public void processStanza(Stanza packet) { if (packet instanceof AgentStatusRequest) { - AgentStatusRequest statusRequest = (AgentStatusRequest)packet; + AgentStatusRequest statusRequest = (AgentStatusRequest) packet; for (Iterator i = statusRequest.getAgents().iterator(); i.hasNext();) { AgentStatusRequest.Item item = i.next(); String agentJID = item.getJID(); 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 297b39779..258368625 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 @@ -340,7 +340,7 @@ public class AgentSession { StanzaCollector collector = this.connection.createStanzaCollectorAndSend(new AndFilter( new StanzaTypeFilter(Presence.class), FromMatchesFilter.create(workgroupJID)), presence); - presence = (Presence)collector.nextResultOrThrow(); + presence = (Presence) collector.nextResultOrThrow(); // We can safely update this iv since we didn't get any error this.online = online; @@ -757,7 +757,7 @@ public class AgentSession { private void handlePacket(Stanza packet) { if (packet instanceof Presence) { - Presence presence = (Presence)packet; + Presence presence = (Presence) packet; // The workgroup can send us a number of different presence packets. We // check for different packet extensions to see what type of presence @@ -772,7 +772,7 @@ public class AgentSession { } // QueueOverview packet extensions contain basic information about a queue. - QueueOverview queueOverview = (QueueOverview)presence.getExtension(QueueOverview.ELEMENT_NAME, QueueOverview.NAMESPACE); + QueueOverview queueOverview = (QueueOverview) presence.getExtension(QueueOverview.ELEMENT_NAME, QueueOverview.NAMESPACE); if (queueOverview != null) { if (queueOverview.getStatus() == null) { queue.setStatus(WorkgroupQueue.Status.CLOSED); @@ -791,7 +791,7 @@ public class AgentSession { // QueueDetails packet extensions contain information about the users in // a queue. - QueueDetails queueDetails = (QueueDetails)packet.getExtension(QueueDetails.ELEMENT_NAME, QueueDetails.NAMESPACE); + QueueDetails queueDetails = (QueueDetails) packet.getExtension(QueueDetails.ELEMENT_NAME, QueueDetails.NAMESPACE); if (queueDetails != null) { queue.setUsers(queueDetails.getUsers()); // Fire event. @@ -812,23 +812,23 @@ public class AgentSession { } } else if (packet instanceof Message) { - Message message = (Message)packet; + Message message = (Message) packet; // Check if a room invitation was sent and if the sender is the workgroup - MUCUser mucUser = (MUCUser)message.getExtension("x", + MUCUser mucUser = (MUCUser) message.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null; if (invite != null && workgroupJID.equals(invite.getFrom())) { String sessionID = null; Map> metaData = null; - SessionID sessionIDExt = (SessionID)message.getExtension(SessionID.ELEMENT_NAME, + SessionID sessionIDExt = (SessionID) message.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE); if (sessionIDExt != null) { sessionID = sessionIDExt.getSessionID(); } - MetaData metaDataExt = (MetaData)message.getExtension(MetaData.ELEMENT_NAME, + MetaData metaDataExt = (MetaData) message.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE); if (metaDataExt != null) { metaData = metaDataExt.getMetaData(); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/AgentChatSession.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/AgentChatSession.java index 752ccf806..285122a0c 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/AgentChatSession.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/AgentChatSession.java @@ -79,11 +79,11 @@ public class AgentChatSession { this.sessionID = sessionID; } - public void setQuestion(String question){ + public void setQuestion(String question) { this.question = question; } - public String getQuestion(){ + public String getQuestion() { return question; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/ChatMetadata.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/ChatMetadata.java index 57a177d1b..09e16b5c3 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/ChatMetadata.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/history/ChatMetadata.java @@ -58,11 +58,11 @@ public class ChatMetadata extends IQ { private Map> map = new HashMap>(); - public void setMetadata(Map> metadata){ + public void setMetadata(Map> metadata) { this.map = metadata; } - public Map> getMetadata(){ + public Map> getMetadata() { return map; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatusRequest.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatusRequest.java index 447d5a98b..8855d0086 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatusRequest.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentStatusRequest.java @@ -73,11 +73,11 @@ public class AgentStatusRequest extends IQ { protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) { buf.rightAngleBracket(); synchronized (agents) { - for (Iterator i=agents.iterator(); i.hasNext(); ) { + for (Iterator i = agents.iterator(); i.hasNext(); ) { Item item = i.next(); buf.append(""); if (item.getName() != null) { - buf.append(""); + buf.append(""); buf.append(item.getName()); buf.append(""); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentWorkgroups.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentWorkgroups.java index 434b9200b..760f91ffb 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentWorkgroups.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/AgentWorkgroups.java @@ -88,7 +88,7 @@ public class AgentWorkgroups extends IQ { protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) { buf.attribute("jid", agentJID).rightAngleBracket(); - for (Iterator it=workgroups.iterator(); it.hasNext();) { + for (Iterator it = workgroups.iterator(); it.hasNext();) { String workgroupJID = it.next(); buf.append(""); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MonitorPacket.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MonitorPacket.java index 3fe42a597..c84419462 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MonitorPacket.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/MonitorPacket.java @@ -64,7 +64,7 @@ public class MonitorPacket extends IQ { buf.rightAngleBracket(); if (sessionID != null) { - buf.append(""); + buf.append(""); } return buf; 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 2a415ec2e..584d5edaf 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 @@ -107,7 +107,7 @@ public final class QueueDetails implements ExtensionElement { buf.append('<').append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">"); synchronized (users) { - for (Iterator i=users.iterator(); i.hasNext(); ) { + for (Iterator i = users.iterator(); i.hasNext(); ) { QueueUser user = i.next(); int position = user.getQueuePosition(); int timeRemaining = user.getEstimatedRemainingTime(); @@ -183,7 +183,7 @@ public final class QueueDetails implements ExtensionElement { throw new SmackException(e); } } - else if(parser.getName().equals("waitTime")) { + else if (parser.getName().equals("waitTime")) { Date wait; try { wait = dateFormat.parse(parser.nextText()); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/Transcript.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/Transcript.java index 75e5a7680..8488354b9 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/Transcript.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/Transcript.java @@ -83,7 +83,7 @@ public class Transcript extends IQ { .append(sessionID) .append("\">"); - for (Iterator it=packets.iterator(); it.hasNext();) { + for (Iterator it = packets.iterator(); it.hasNext();) { Stanza packet = it.next(); buf.append(packet.toXML()); } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/TranscriptsProvider.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/TranscriptsProvider.java index a3b075c69..5a48946ad 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/TranscriptsProvider.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/packet/TranscriptsProvider.java @@ -83,14 +83,14 @@ public class TranscriptsProvider extends IQProvider { synchronized (UTC_FORMAT) { joinTime = UTC_FORMAT.parse(parser.nextText()); } - } catch (ParseException e) {} + } catch (ParseException e) { } } else if (parser.getName().equals("leftTime")) { try { synchronized (UTC_FORMAT) { leftTime = UTC_FORMAT.parse(parser.nextText()); } - } catch (ParseException e) {} + } catch (ParseException e) { } } else if (parser.getName().equals("agents")) { agents = parseAgents(parser); @@ -124,14 +124,14 @@ public class TranscriptsProvider extends IQProvider { synchronized (UTC_FORMAT) { joinTime = UTC_FORMAT.parse(parser.nextText()); } - } catch (ParseException e) {} + } catch (ParseException e) { } } else if (parser.getName().equals("leftTime")) { try { synchronized (UTC_FORMAT) { leftTime = UTC_FORMAT.parse(parser.nextText()); } - } catch (ParseException e) {} + } catch (ParseException e) { } } else if (parser.getName().equals("agent")) { agentJID = null; 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 13c34a800..cfbadbbad 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 @@ -42,7 +42,7 @@ public class WorkgroupInformation implements ExtensionElement { private String workgroupJID; - public WorkgroupInformation(String workgroupJID){ + public WorkgroupInformation(String workgroupJID) { this.workgroupJID = workgroupJID; } diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/ChatSetting.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/ChatSetting.java index 8b6236cf2..00a227c61 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/ChatSetting.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/ChatSetting.java @@ -22,7 +22,7 @@ public class ChatSetting { private String value; private int type; - public ChatSetting(String key, String value, int type){ + public ChatSetting(String key, String value, int type) { setKey(key); setValue(value); setType(type); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/OfflineSettings.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/OfflineSettings.java index 59554ab14..75b125b21 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/OfflineSettings.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/OfflineSettings.java @@ -80,7 +80,7 @@ public class OfflineSettings extends SimpleIQ { return (StringUtils.isNotEmpty(getRedirectURL())); } - public boolean isConfigured(){ + public boolean isConfigured() { return StringUtils.isNotEmpty(getEmailAddress()) && StringUtils.isNotEmpty(getSubject()) && StringUtils.isNotEmpty(getOfflineText()); diff --git a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/SearchSettings.java b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/SearchSettings.java index 74bc043f5..287dd2650 100644 --- a/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/SearchSettings.java +++ b/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/settings/SearchSettings.java @@ -48,11 +48,11 @@ public class SearchSettings extends SimpleIQ { this.kbLocation = kbLocation; } - public boolean hasKB(){ + public boolean hasKB() { return StringUtils.isNotEmpty(getKbLocation()); } - public boolean hasForums(){ + public boolean hasForums() { return StringUtils.isNotEmpty(getForumsLocation()); } 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 338715788..0b7f814be 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 @@ -192,7 +192,7 @@ public class Workgroup { StanzaCollector collector = connection.createStanzaCollectorAndSend(new AndFilter(fromFilter, typeFilter), directedPresence); - Presence response = (Presence)collector.nextResultOrThrow(); + Presence response = (Presence) collector.nextResultOrThrow(); return Presence.Type.available == response.getType(); } @@ -482,7 +482,7 @@ public class Workgroup { } private void fireQueueJoinedEvent() { - for (QueueListener listener : queueListeners){ + for (QueueListener listener : queueListeners) { // CHECKSTYLE:OFF listener.joinedQueue(); // CHECKSTYLE:ON @@ -511,7 +511,7 @@ public class Workgroup { private void handlePacket(Stanza packet) { if (packet instanceof Message) { - Message msg = (Message)packet; + Message msg = (Message) packet; // Check to see if the user left the queue. ExtensionElement pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup"); ExtensionElement queueStatus = msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup"); @@ -520,7 +520,7 @@ public class Workgroup { fireQueueDepartedEvent(); } else if (queueStatus != null) { - QueueUpdate queueUpdate = (QueueUpdate)queueStatus; + QueueUpdate queueUpdate = (QueueUpdate) queueStatus; if (queueUpdate.getPosition() != -1) { fireQueuePositionEvent(queueUpdate.getPosition()); } @@ -531,7 +531,7 @@ public class Workgroup { else { // Check if a room invitation was sent and if the sender is the workgroup - MUCUser mucUser = (MUCUser)msg.getExtension("x", "http://jabber.org/protocol/muc#user"); + MUCUser mucUser = (MUCUser) msg.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null; if (invite != null && workgroupJID.equals(invite.getFrom())) { String sessionID = null; @@ -540,13 +540,13 @@ public class Workgroup { pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE); if (pe != null) { - sessionID = ((SessionID)pe).getSessionID(); + sessionID = ((SessionID) pe).getSessionID(); } pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE); if (pe != null) { - metaData = ((MetaData)pe).getMetaData(); + metaData = ((MetaData) pe).getMetaData(); } WorkgroupInvitation inv = new WorkgroupInvitation(connection.getUser(), msg.getFrom(), 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 fb2eda00a..87234cef7 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 @@ -48,7 +48,7 @@ public class RemoteRosterEntry { * @param groups the list of group names the entry will belong to, or null if the * the roster entry won't belong to a group. */ - public RemoteRosterEntry(Jid user, String name, String [] groups) { + public RemoteRosterEntry(Jid user, String name, String[] groups) { this.user = user; this.name = name; if (groups != null) { diff --git a/smack-resolver-minidns/src/main/java/org/jivesoftware/smack/util/dns/minidns/MiniDnsDaneVerifier.java b/smack-resolver-minidns/src/main/java/org/jivesoftware/smack/util/dns/minidns/MiniDnsDaneVerifier.java index ad63c74a1..5f757f52e 100644 --- a/smack-resolver-minidns/src/main/java/org/jivesoftware/smack/util/dns/minidns/MiniDnsDaneVerifier.java +++ b/smack-resolver-minidns/src/main/java/org/jivesoftware/smack/util/dns/minidns/MiniDnsDaneVerifier.java @@ -51,7 +51,7 @@ public class MiniDnsDaneVerifier implements SmackDaneVerifier { throw new IllegalStateException("DaneProvider was initialized before. Use newInstance() instead."); } expectingTrustManager = new ExpectingTrustManager(tm); - context.init(km, new TrustManager[]{expectingTrustManager}, random); + context.init(km, new TrustManager[] {expectingTrustManager}, random); } @Override 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 723256838..34cdbaf5f 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 @@ -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. @@ -115,8 +115,7 @@ public class SASLDigestMD5Mechanism extends SASLMechanism { switch (state) { case INITIAL: for (String part : challengeParts) { - String[] keyValue = part.split("="); - assert (keyValue.length == 2); + String[] keyValue = part.split("=", 2); String key = keyValue[0]; // RFC 2831 § 7.1 about the formating of the digest-challenge: // "The full form is "#element" indicating at least and diff --git a/smack-tcp/src/main/java/org/jivesoftware/smack/sm/provider/ParseStreamManagement.java b/smack-tcp/src/main/java/org/jivesoftware/smack/sm/provider/ParseStreamManagement.java index 9b5fd3f75..a6ce522a9 100644 --- a/smack-tcp/src/main/java/org/jivesoftware/smack/sm/provider/ParseStreamManagement.java +++ b/smack-tcp/src/main/java/org/jivesoftware/smack/sm/provider/ParseStreamManagement.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. @@ -46,7 +46,7 @@ public class ParseStreamManagement { String name; XMPPError.Condition condition = null; outerloop: - while(true) { + while (true) { int event = parser.next(); switch (event) { case XmlPullParser.START_TAG: 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 d42ed16af..b4676e663 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 @@ -566,7 +566,7 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { int port = hostAddress.getPort(); if (proxyInfo == null) { inetAddresses = hostAddress.getInetAddresses().iterator(); - assert(inetAddresses.hasNext()); + assert (inetAddresses.hasNext()); innerloop: while (inetAddresses.hasNext()) { // Create a *new* Socket before every connection attempt, i.e. connect() call, since Sockets are not @@ -707,13 +707,13 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { if ("PKCS11".equals(keyStoreType)) { try { Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class); - String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library(); + String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library(); ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8)); - Provider p = (Provider)c.newInstance(config); + Provider p = (Provider) c.newInstance(config); Security.addProvider(p); ks = KeyStore.getInstance("PKCS11",p); pcb = new PasswordCallback("PKCS11 Password: ",false); - callbackHandler.handle(new Callback[]{pcb}); + callbackHandler.handle(new Callback[] {pcb}); ks.load(null,pcb.getPassword()); } catch (Exception e) { @@ -727,7 +727,7 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { //pcb = new PasswordCallback("Apple Keychain",false); //pcb.setPassword(null); } - else if (keyStoreType != null){ + else if (keyStoreType != null) { ks = KeyStore.getInstance(keyStoreType); if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) { try { @@ -1034,7 +1034,7 @@ public class XMPPTCPConnection extends AbstractXMPPConnection { if ("jabber:client".equals(parser.getNamespace(null))) { streamId = parser.getAttributeValue("", "id"); String reportedServerDomain = parser.getAttributeValue("", "from"); - assert(config.getXMPPServiceDomain().equals(reportedServerDomain)); + assert (config.getXMPPServiceDomain().equals(reportedServerDomain)); } break; case "error":