1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-09 17:19:39 +02:00

Merge branch '4.2'

This commit is contained in:
Florian Schmaus 2017-05-25 10:39:59 +02:00
commit 7a5f9e6a03
187 changed files with 2284 additions and 588 deletions

View file

@ -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());
}
}

View file

@ -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";
}
/**

View file

@ -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);
}
}

View file

@ -118,9 +118,9 @@ public final class BookmarkManager {
BookmarkedConference bookmark
= new BookmarkedConference(name, jid, isAutoJoin, nickname, password);
List<BookmarkedConference> 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<BookmarkedConference> 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<BookmarkedURL> 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<BookmarkedURL> 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");
}

View file

@ -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);
}

View file

@ -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);
}

View file

@ -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);
}

View file

@ -64,7 +64,7 @@ class DataListener extends AbstractIqRequestHandler {
ibbSession.processIQPacket(data);
}
}
catch (NotConnectedException|InterruptedException e) {
catch (NotConnectedException | InterruptedException e) {
return null;
}
return null;

View file

@ -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;

View file

@ -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);
}

View file

@ -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());

View file

@ -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);

View file

@ -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();

View file

@ -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 <item-not-found/> 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;
}

View file

@ -74,7 +74,7 @@ public class DiscoverInfoProvider extends IQProvider<DiscoverInfo> {
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;

View file

@ -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");

View file

@ -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;
}

View file

@ -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);
}
}

View file

@ -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 <subject/> and a <body/> or a <subject/> and a <thread/> 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));

View file

@ -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;
}

View file

@ -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 <code>null</code> if the room itself changed the subject.
*/
public abstract void subjectUpdated(String subject, EntityFullJid from);

View file

@ -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;

View file

@ -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);
}

View file

@ -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 <service-unavailable/>.
// 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<Boolean> pingAsync(Jid jid) {
return pingAsync(jid, connection().getReplyTimeout());
}
public SmackFuture<Boolean> pingAsync(final Jid jid, long pongTimeout) {
final InternalSmackFuture<Boolean> future = new InternalSmackFuture<Boolean>() {
@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;
}

View file

@ -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);
}
}

View file

@ -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

View file

@ -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;

View file

@ -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()));
}
}

View file

@ -61,7 +61,7 @@ public class EventElement implements EmbeddedPacketExtension
@Override
public List<ExtensionElement> getExtensions()
{
return Arrays.asList(new ExtensionElement[]{getEvent()});
return Arrays.asList(new ExtensionElement[] {getEvent()});
}
public NodeExtension getEvent()

View file

@ -134,7 +134,7 @@ public class ItemsExtension extends NodeExtension implements EmbeddedPacketExten
@SuppressWarnings("unchecked")
public List<ExtensionElement> getExtensions()
{
return (List<ExtensionElement>)getItems();
return (List<ExtensionElement>) getItems();
}
/**

View file

@ -303,7 +303,7 @@ public class LeafNode extends Node
public <T extends Item> void publish(T item) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
Collection<T> items = new ArrayList<T>(1);
items.add((item == null ? (T)new Item() : item));
items.add((item == null ? (T) new Item() : item));
publish(items);
}

View file

@ -573,7 +573,7 @@ abstract public class Node
private static List<String> 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<String> 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<ExtensionElement> secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions();
List<ExtensionElement> secondLevelList = ((EmbeddedPacketExtension) embedEvent).getExtensions();
// XEP-0060 allows no elements on second level for notifications. See schema or
// for example § 4.3:

View file

@ -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)
{

View file

@ -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;
}
}
}

View file

@ -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<XMPPConnection, Map<BareJid, PubSubManager>> 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.
* <p>
* Not every PubSub service supports automatic node creation. You can discover if this service supports it by using
* {@link #supportsAutomaticNodeCreation()}.
* </p>
*
* @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 <I extends Item> 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 <a href="https://xmpp.org/extensions/xep-0060.html#publisher-publish-autocreate">XEP-0060 § 7.1.4 Automatic Node Creation</a>
*/
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

View file

@ -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

View file

@ -35,7 +35,7 @@ import org.jivesoftware.smackx.pubsub.AffiliationsExtension;
@Override
protected AffiliationsExtension createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content)
{
return new AffiliationsExtension((List<Affiliation>)content);
return new AffiliationsExtension((List<Affiliation>) content);
}
}

View file

@ -39,6 +39,6 @@ public class ConfigEventProvider extends EmbeddedExtensionProvider<Configuration
if (content.size() == 0)
return new ConfigurationEvent(attMap.get("node"));
else
return new ConfigurationEvent(attMap.get("node"), new ConfigureForm((DataForm)content.iterator().next()));
return new ConfigurationEvent(attMap.get("node"), new ConfigureForm((DataForm) content.iterator().next()));
}
}

View file

@ -36,6 +36,6 @@ public class EventProvider extends EmbeddedExtensionProvider<EventElement>
@Override
protected EventElement createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attMap, List<? extends ExtensionElement> 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));
}
}

View file

@ -37,6 +37,6 @@ public class FormNodeProvider extends EmbeddedExtensionProvider<FormNode>
@Override
protected FormNode createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> 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()));
}
}

View file

@ -36,7 +36,7 @@ public class SubscriptionsProvider extends EmbeddedExtensionProvider<Subscriptio
@Override
protected SubscriptionsExtension createReturnExtension(String currentElement, String currentNamespace, Map<String, String> attributeMap, List<? extends ExtensionElement> content)
{
return new SubscriptionsExtension(attributeMap.get("node"), (List<Subscription>)content);
return new SubscriptionsExtension(attributeMap.get("node"), (List<Subscription>) content);
}
}

View file

@ -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 <code>Row</code>.
* @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 <code>Column</code>.
* @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<String> getValues(String variable) {
for(Field field : getFields()) {
for (Field field : getFields()) {
if (variable.equalsIgnoreCase(field.getVariable())) {
return field.getValues();
}

View file

@ -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");
}

View file

@ -87,7 +87,7 @@ public class StreamInitiationProvider extends IQProvider<StreamInitiation> {
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);
}

View file

@ -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);
}

View file

@ -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());
}

View file

@ -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++;
}

View file

@ -176,7 +176,7 @@ public final class Socks5TestProxy {
*/
@SuppressWarnings("WaitNotInLoop")
public Socket getSocket(String digest) {
synchronized(this) {
synchronized (this) {
if (!startupComplete) {
try {
wait(5000);

View file

@ -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;

View file

@ -75,32 +75,32 @@ public class GeoLocationTest extends InitExtensions {
// @formatter:off
final String geoLocationMessageString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<accuracy>23</accuracy>"
+"<alt>1000</alt>"
+"<area>Delhi</area>"
+"<bearing>10</bearing>"
+"<building>Small Building</building>"
+"<country>India</country>"
+"<countrycode>IN</countrycode>"
+"<description>My Description</description>"
+"<error>90</error>"
+"<floor>top</floor>"
+"<lat>25.098345</lat>"
+"<locality>awesome</locality>"
+"<lon>77.992034</lon>"
+"<postalcode>110085</postalcode>"
+"<region>North</region>"
+"<room>small</room>"
+"<speed>250.0</speed>"
+"<street>Wall Street</street>"
+"<text>Unit Testing GeoLocation</text>"
+"<timestamp>2004-02-19</timestamp>"
+"<tzo>+5:30</tzo>"
+"<uri>http://xmpp.org</uri>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<accuracy>23</accuracy>"
+ "<alt>1000</alt>"
+ "<area>Delhi</area>"
+ "<bearing>10</bearing>"
+ "<building>Small Building</building>"
+ "<country>India</country>"
+ "<countrycode>IN</countrycode>"
+ "<description>My Description</description>"
+ "<error>90</error>"
+ "<floor>top</floor>"
+ "<lat>25.098345</lat>"
+ "<locality>awesome</locality>"
+ "<lon>77.992034</lon>"
+ "<postalcode>110085</postalcode>"
+ "<region>North</region>"
+ "<room>small</room>"
+ "<speed>250.0</speed>"
+ "<street>Wall Street</street>"
+ "<text>Unit Testing GeoLocation</text>"
+ "<timestamp>2004-02-19</timestamp>"
+ "<tzo>+5:30</tzo>"
+ "<uri>http://xmpp.org</uri>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationMessageString);

View file

@ -35,32 +35,32 @@ public class GeoLocationProviderTest extends InitExtensions {
public void testGeoLocationProviderWithNoDatumSet() throws Exception {
// @formatter:off
final String geoLocationString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<accuracy>23</accuracy>"
+"<alt>1000</alt>"
+"<area>Delhi</area>"
+"<bearing>10</bearing>"
+"<building>Small Building</building>"
+"<country>India</country>"
+"<countrycode>IN</countrycode>"
+"<description>My Description</description>"
+"<error>90</error>"
+"<floor>top</floor>"
+"<lat>25.098345</lat>"
+"<locality>awesome</locality>"
+"<lon>77.992034</lon>"
+"<postalcode>110085</postalcode>"
+"<region>North</region>"
+"<room>small</room>"
+"<speed>250.0</speed>"
+"<street>Wall Street</street>"
+"<text>Unit Testing GeoLocation</text>"
+"<timestamp>2004-02-19</timestamp>"
+"<tzo>+5:30</tzo>"
+"<uri>http://xmpp.org</uri>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<accuracy>23</accuracy>"
+ "<alt>1000</alt>"
+ "<area>Delhi</area>"
+ "<bearing>10</bearing>"
+ "<building>Small Building</building>"
+ "<country>India</country>"
+ "<countrycode>IN</countrycode>"
+ "<description>My Description</description>"
+ "<error>90</error>"
+ "<floor>top</floor>"
+ "<lat>25.098345</lat>"
+ "<locality>awesome</locality>"
+ "<lon>77.992034</lon>"
+ "<postalcode>110085</postalcode>"
+ "<region>North</region>"
+ "<room>small</room>"
+ "<speed>250.0</speed>"
+ "<street>Wall Street</street>"
+ "<text>Unit Testing GeoLocation</text>"
+ "<timestamp>2004-02-19</timestamp>"
+ "<tzo>+5:30</tzo>"
+ "<uri>http://xmpp.org</uri>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString);
@ -101,33 +101,33 @@ public class GeoLocationProviderTest extends InitExtensions {
// @formatter:off
final String geoLocationString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<accuracy>23</accuracy>"
+"<alt>1000</alt>"
+"<area>Delhi</area>"
+"<bearing>10</bearing>"
+"<building>Small Building</building>"
+"<country>India</country>"
+"<countrycode>IN</countrycode>"
+"<datum>Test Datum</datum>"
+"<description>My Description</description>"
+"<error>90</error>"
+"<floor>top</floor>"
+"<lat>25.098345</lat>"
+"<locality>awesome</locality>"
+"<lon>77.992034</lon>"
+"<postalcode>110085</postalcode>"
+"<region>North</region>"
+"<room>small</room>"
+"<speed>250.0</speed>"
+"<street>Wall Street</street>"
+"<text>Unit Testing GeoLocation</text>"
+"<timestamp>2004-02-19</timestamp>"
+"<tzo>+5:30</tzo>"
+"<uri>http://xmpp.org</uri>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<accuracy>23</accuracy>"
+ "<alt>1000</alt>"
+ "<area>Delhi</area>"
+ "<bearing>10</bearing>"
+ "<building>Small Building</building>"
+ "<country>India</country>"
+ "<countrycode>IN</countrycode>"
+ "<datum>Test Datum</datum>"
+ "<description>My Description</description>"
+ "<error>90</error>"
+ "<floor>top</floor>"
+ "<lat>25.098345</lat>"
+ "<locality>awesome</locality>"
+ "<lon>77.992034</lon>"
+ "<postalcode>110085</postalcode>"
+ "<region>North</region>"
+ "<room>small</room>"
+ "<speed>250.0</speed>"
+ "<street>Wall Street</street>"
+ "<text>Unit Testing GeoLocation</text>"
+ "<timestamp>2004-02-19</timestamp>"
+ "<tzo>+5:30</tzo>"
+ "<uri>http://xmpp.org</uri>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString);
@ -168,11 +168,11 @@ public class GeoLocationProviderTest extends InitExtensions {
// @formatter:off
final String geoLocationString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<error>90</error>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<error>90</error>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString);
@ -188,11 +188,11 @@ public class GeoLocationProviderTest extends InitExtensions {
// @formatter:off
final String geoLocationString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<accuracy>90</accuracy>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<accuracy>90</accuracy>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString);
@ -208,12 +208,12 @@ public class GeoLocationProviderTest extends InitExtensions {
// @formatter:off
final String geoLocationString = "<message from='portia@merchantofvenice.lit'"
+" to='bassanio@merchantofvenice.lit'>"
+"<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+"<accuracy>90</accuracy>"
+"<error>100</error>"
+"</geoloc>"
+"</message>";
+ " to='bassanio@merchantofvenice.lit'>"
+ "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
+ "<accuracy>90</accuracy>"
+ "<error>100</error>"
+ "</geoloc>"
+ "</message>";
// @formatter:on
Message messageWithGeoLocation = (Message) PacketParserUtils.parseStanza(geoLocationString);

View file

@ -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();

View file

@ -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());
}
}

View file

@ -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);

View file

@ -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("<html>Number of Persons by<br/> Nationality and Status</html>", 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("<html>Number of Persons by<br/> Nationality and Status</html>", section.getLabel());

View file

@ -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);