xmppSession.addMessageListener(new MessageListener() {
@Override
public void handle(MessageEvent e) {
if (e.isIncoming() && isEnabled()) {
Message message = e.getMessage();
Event event = message.getExtension(Event.class);
if (event != null) {
for (Item item : event.getItems()) {
if (item.getPayload() instanceof AvatarMetadata) {
AvatarMetadata avatarMetadata = (AvatarMetadata) item.getPayload();
// Empty avatar
if (avatarMetadata.getInfoList().isEmpty()) {
notifyListeners(message.getFrom().asBareJid(), null);
} else {
try {
// Check if we have a cached avatar.
byte[] cachedImage = loadFromCache(item.getId());
if (cachedImage != null) {
notifyListeners(message.getFrom().asBareJid(), cachedImage);
} else {
// We don't have a cached copy, let's retrieve it.
// Determine the best info
AvatarMetadata.Info chosenInfo = null;
// Check if there's an avatar, which is stored in PubSub node (and therefore must be in PNG format).
for (AvatarMetadata.Info info : avatarMetadata.getInfoList()) {
if (info.getUrl() == null) {
chosenInfo = info;
}
}
// If only URLs are available, choose the first URL.
if (chosenInfo == null) {
for (AvatarMetadata.Info info : avatarMetadata.getInfoList()) {
if (info.getUrl() != null) {
chosenInfo = info;
break;
}
}
}
if (chosenInfo != null && chosenInfo.getUrl() != null) {
URLConnection urlConnection = chosenInfo.getUrl().openConnection();
String type = urlConnection.getContentType();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Download the image file.
try (InputStream in = urlConnection.getInputStream()) {
byte data[] = new byte[4096];
int n;
while ((n = in.read(data, 0, 4096)) != -1) {
baos.write(data, 0, n);
}
}
byte[] data = baos.toByteArray();
storeToCache(item.getId(), data);
notifyListeners(message.getFrom().asBareJid(), data);
} else {
PubSubService pubSubService = xmppSession.getExtensionManager(PubSubManager.class).createPubSubService(message.getFrom());
List<Item> items = pubSubService.getNode(AvatarData.NAMESPACE).getItems(item.getId());
if (!items.isEmpty()) {
Item i = items.get(0);
if (i.getPayload() instanceof AvatarData) {
AvatarData avatarData = (AvatarData) i.getPayload();
storeToCache(item.getId(), avatarData.getData());
notifyListeners(message.getFrom().asBareJid(), avatarData.getData());
}
}
}
}
} catch (XmppException | IOException e1) {