use of org.jivesoftware.smack.StanzaListener in project Smack by igniterealtime.
the class JingleManager method initJingleSessionRequestListeners.
/**
* Register the listenerJingles, waiting for a Jingle stanza that tries to
* establish a new session.
*/
private void initJingleSessionRequestListeners() {
StanzaFilter initRequestFilter = new StanzaFilter() {
// Return true if we accept this packet
@Override
public boolean accept(Stanza pin) {
if (pin instanceof IQ) {
IQ iq = (IQ) pin;
if (iq.getType().equals(IQ.Type.set)) {
if (iq instanceof Jingle) {
Jingle jin = (Jingle) pin;
if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
return true;
}
}
}
}
return false;
}
};
jingleSessionRequestListeners = new ArrayList<>();
// Start a packet listener for session initiation requests
connection.addAsyncStanzaListener(new StanzaListener() {
@Override
public void processStanza(Stanza packet) {
triggerSessionRequested((Jingle) packet);
}
}, initRequestFilter);
}
use of org.jivesoftware.smack.StanzaListener in project xabber-android by redsolution.
the class HttpFileUploadManager method uploadFile.
public void uploadFile(final AccountJid account, final UserJid user, final String filePath) {
final Jid uploadServerUrl = uploadServers.get(account);
if (uploadServerUrl == null) {
return;
}
AccountItem accountItem = AccountManager.getInstance().getAccount(account);
if (accountItem == null) {
return;
}
final File file = new File(filePath);
final com.xabber.xmpp.httpfileupload.Request httpFileUpload = new com.xabber.xmpp.httpfileupload.Request();
httpFileUpload.setFilename(file.getName());
httpFileUpload.setSize(String.valueOf(file.length()));
httpFileUpload.setTo(uploadServerUrl);
try {
accountItem.getConnection().sendIqWithResponseCallback(httpFileUpload, new StanzaListener() {
@Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
if (!(packet instanceof Slot)) {
return;
}
uploadFileToSlot(account, (Slot) packet);
}
private void uploadFileToSlot(final AccountJid account, final Slot slot) {
SSLSocketFactory sslSocketFactory = null;
MemorizingTrustManager mtm = CertificateManager.getInstance().getNewFileUploadManager(account);
final SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
return;
}
OkHttpClient client = new OkHttpClient().newBuilder().sslSocketFactory(sslSocketFactory).hostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())).writeTimeout(5, TimeUnit.MINUTES).connectTimeout(5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES).build();
Request request = new Request.Builder().url(slot.getPutUrl()).put(RequestBody.create(CONTENT_TYPE, file)).build();
final String fileMessageId;
fileMessageId = MessageManager.getInstance().createFileMessage(account, user, file);
LogManager.i(HttpFileUploadManager.this, "starting upload file to " + slot.getPutUrl() + " size " + file.length());
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogManager.i(HttpFileUploadManager.this, "onFailure " + e.getMessage());
MessageManager.getInstance().updateMessageWithError(fileMessageId, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
LogManager.i(HttpFileUploadManager.this, "onResponse " + response.isSuccessful() + " " + response.body().string());
if (response.isSuccessful()) {
MessageManager.getInstance().updateFileMessage(account, user, fileMessageId, slot.getGetUrl());
} else {
MessageManager.getInstance().updateMessageWithError(fileMessageId, response.message());
}
}
});
}
}, new ExceptionCallback() {
@Override
public void processException(Exception exception) {
LogManager.i(this, "On HTTP file upload slot error");
LogManager.exception(this, exception);
Application.getInstance().onError(R.string.http_file_upload_slot_error);
}
});
} catch (SmackException.NotConnectedException | InterruptedException e) {
LogManager.exception(this, e);
}
}
use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.
the class ReversiPlugin method initialize.
public void initialize() {
// Offers and invitations hold all pending game offers we've sent to
// other users or incoming
// invitations. The map key is always the opponent's JID. The map value
// is a transcript alert
// UI component.
gameOffers = new ConcurrentHashMap<String, JPanel>();
gameInvitations = new ConcurrentHashMap<String, JPanel>();
// Add Reversi item to chat toolbar.
addToolbarButton();
// Add Smack providers. The plugin uses custom XMPP extensions to
// communicate game offers
// and current game state. Adding the Smack providers lets us use the
// custom protocol.
ProviderManager.addIQProvider(GameOffer.ELEMENT_NAME, GameOffer.NAMESPACE, new GameOffer.Provider());
ProviderManager.addExtensionProvider(GameMove.ELEMENT_NAME, GameMove.NAMESPACE, new GameMove.Provider());
ProviderManager.addExtensionProvider(GameForfeit.ELEMENT_NAME, GameForfeit.NAMESPACE, new GameForfeit.Provider());
// Add IQ listener to listen for incoming game invitations.
gameOfferListener = new StanzaListener() {
public void processPacket(Stanza stanza) {
GameOffer invitation = (GameOffer) stanza;
if (invitation.getType() == IQ.Type.get) {
showInvitationAlert(invitation);
} else if (invitation.getType() == IQ.Type.error) {
handleErrorIQ(invitation);
}
}
};
SparkManager.getConnection().addAsyncStanzaListener(gameOfferListener, new StanzaTypeFilter(GameOffer.class));
}
use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.
the class ReversiPlugin method addToolbarButton.
/**
* Adds the Reversi toolbar button.
*/
private void addToolbarButton() {
ChatManager manager = SparkManager.getChatManager();
chatRoomListener = new ChatRoomListenerAdapter() {
ImageIcon icon = ReversiRes.getImageIcon(ReversiRes.REVERSI_ICON);
public void chatRoomOpened(final ChatRoom room) {
if (!(room instanceof ChatRoomImpl)) {
// Don't do anything if this is not a 1on1-Chat
return;
}
ChatRoomButton button = new ChatRoomButton(icon);
button.setToolTipText("Reversi");
room.getToolBar().addChatRoomButton(button);
// Add a button listener that sends out a game invite on a user
// click.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Show "requesting a game panel"
final JPanel request = new JPanel();
request.setLayout(new BorderLayout());
JPanel requestPanel = new JPanel() {
private static final long serialVersionUID = 4490592207923738251L;
protected void paintComponent(Graphics g) {
g.drawImage(icon.getImage(), 0, 0, null);
}
};
requestPanel.setPreferredSize(new Dimension(24, 24));
request.add(requestPanel, BorderLayout.WEST);
String opponentJID = ((ChatRoomImpl) room).getJID();
// TODO:
String opponentName = "[" + opponentJID + "]";
// convert
// to
// more
// readable
// name.
final JPanel content = new JPanel(new BorderLayout());
final JLabel label = new JLabel("Requesting a Reversi game with " + opponentName + ", please wait...");
content.add(label, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
final JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameOffer reply = new GameOffer();
reply.setTo(((ChatRoomImpl) room).getJID());
reply.setType(IQ.Type.error);
try {
SparkManager.getConnection().sendStanza(reply);
} catch (SmackException.NotConnectedException e1) {
Log.warning("Unable to send invitation cancellation to " + reply.getTo(), e1);
}
cancelButton.setText("Canceled");
cancelButton.setEnabled(false);
}
});
buttonPanel.add(cancelButton, BorderLayout.SOUTH);
content.add(buttonPanel, BorderLayout.SOUTH);
request.add(content, BorderLayout.CENTER);
room.getTranscriptWindow().addComponent(request);
final GameOffer offer = new GameOffer();
offer.setTo(opponentJID);
// Add a listener for a reply to our offer.
SparkManager.getConnection().addAsyncStanzaListener(new StanzaListener() {
public void processPacket(Stanza stanza) {
GameOffer offerReply = ((GameOffer) stanza);
if (offerReply.getType() == IQ.Type.result) {
// Remove the offer panel
room.getTranscriptWindow().remove(request);
content.remove(1);
label.setText("Starting game...");
// Show game board (using original offer!).
showReversiBoard(offer.getGameID(), room, offer.isStartingPlayer(), offerReply.getFrom());
} else if (offerReply.getType() == IQ.Type.error) {
cancelButton.setVisible(false);
JPanel userDeclinedPanel = new JPanel(new BorderLayout());
JLabel userDeclined = new JLabel("User declined...");
userDeclinedPanel.add(userDeclined, BorderLayout.SOUTH);
request.add(userDeclinedPanel, BorderLayout.SOUTH);
}
// TODO: Handle error case
}
}, new StanzaIdFilter(offer.getStanzaId()));
try {
SparkManager.getConnection().sendStanza(offer);
} catch (SmackException.NotConnectedException e1) {
Log.warning("Unable to send invitation to " + offer.getTo(), e1);
}
}
});
}
public void chatRoomClosed(ChatRoom room) {
super.chatRoomClosed(room);
// TODO: if game is in progress, close it down. What we need is
// an API that lets us see
// TODO: if there's a transcript alert currently there.
}
};
manager.addChatRoomListener(chatRoomListener);
}
use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.
the class TicTacToePlugin method addButtonToToolBar.
/**
* Add the TTT-Button to every opening Chatroom
* and create Listeners for it
*/
private void addButtonToToolBar() {
_chatRoomListener = new ChatRoomListenerAdapter() {
@Override
public void chatRoomOpened(final ChatRoom room) {
if (!(room instanceof ChatRoomImpl)) {
// Don't do anything if this is not a 1on1-Chat
return;
}
final ChatRoomButton sendGameButton = new ChatRoomButton(buttonimg);
room.getToolBar().addChatRoomButton(sendGameButton);
final String opponentJID = ((ChatRoomImpl) room).getJID();
sendGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_currentInvitations.contains(XmppStringUtils.parseBareJid(opponentJID))) {
return;
}
final GameOfferPacket offer = new GameOfferPacket();
offer.setTo(opponentJID);
offer.setType(IQ.Type.get);
_currentInvitations.add(XmppStringUtils.parseBareJid(opponentJID));
room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.sent"), false, false, Color.BLUE);
try {
SparkManager.getConnection().sendStanza(offer);
} catch (SmackException.NotConnectedException e1) {
Log.warning("Unable to send offer to " + opponentJID, e1);
}
SparkManager.getConnection().addAsyncStanzaListener(new StanzaListener() {
@Override
public void processPacket(Stanza stanza) {
GameOfferPacket answer = (GameOfferPacket) stanza;
answer.setStartingPlayer(offer.isStartingPlayer());
answer.setGameID(offer.getGameID());
if (answer.getType() == IQ.Type.result) {
// ACCEPT
_currentInvitations.remove(XmppStringUtils.parseBareJid(opponentJID));
room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.accept"), false, false, Color.BLUE);
createTTTWindow(answer, opponentJID);
} else {
// DECLINE
room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.decline"), false, false, Color.RED);
_currentInvitations.remove(XmppStringUtils.parseBareJid(opponentJID));
}
}
}, new PacketIDFilter(offer.getPacketID()));
}
});
}
@Override
public void chatRoomClosed(ChatRoom room) {
if (room instanceof ChatRoomImpl) {
ChatRoomImpl cri = (ChatRoomImpl) room;
_currentInvitations.remove(cri.getParticipantJID());
}
}
};
SparkManager.getChatManager().addChatRoomListener(_chatRoomListener);
}
Aggregations