use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.
the class ConnectionUtils method createMockedConnection.
/**
* Creates a mocked XMPP connection that stores every stanza(/packet) that is send over this
* connection in the given protocol instance and returns the predefined answer packets
* form the protocol instance.
* <p>
* This mocked connection can used to collect packets that require a reply using a
* StanzaCollector.
*
* <pre>
* <code>
* StanzaCollector collector = connection.createStanzaCollector(new PacketFilter());
* connection.sendStanza(packet);
* Stanza(/Packet) reply = collector.nextResult();
* </code>
* </pre>
*
* @param protocol protocol helper containing answer packets
* @param initiatorJID the user associated to the XMPP connection
* @param xmppServer the XMPP server associated to the XMPP connection
* @return a mocked XMPP connection
* @throws SmackException
* @throws XMPPErrorException
* @throws InterruptedException
*/
public static XMPPConnection createMockedConnection(final Protocol protocol, EntityFullJid initiatorJID, DomainBareJid xmppServer) throws SmackException, XMPPErrorException, InterruptedException {
// mock XMPP connection
XMPPConnection connection = mock(XMPPConnection.class);
when(connection.getUser()).thenReturn(initiatorJID);
when(connection.getXMPPServiceDomain()).thenReturn(xmppServer);
// mock packet collector
final StanzaCollector collector = mock(StanzaCollector.class);
when(connection.createStanzaCollector(isA(StanzaFilter.class))).thenReturn(collector);
Answer<StanzaCollector> collectorAndSend = new Answer<StanzaCollector>() {
@Override
public StanzaCollector answer(InvocationOnMock invocation) throws Throwable {
Stanza packet = (Stanza) invocation.getArguments()[0];
protocol.getRequests().add(packet);
return collector;
}
};
when(connection.createStanzaCollectorAndSend(isA(IQ.class))).thenAnswer(collectorAndSend);
// mock send method
Answer<Object> addIncoming = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
protocol.getRequests().add((Stanza) invocation.getArguments()[0]);
return null;
}
};
doAnswer(addIncoming).when(connection).sendStanza(isA(Stanza.class));
// mock receive methods
Answer<Stanza> answer = new Answer<Stanza>() {
@Override
public Stanza answer(InvocationOnMock invocation) throws Throwable {
return protocol.getResponses().poll();
}
};
when(collector.nextResult(anyInt())).thenAnswer(answer);
when(collector.nextResult()).thenAnswer(answer);
Answer<Stanza> answerOrThrow = new Answer<Stanza>() {
@Override
public Stanza answer(InvocationOnMock invocation) throws Throwable {
Stanza packet = protocol.getResponses().poll();
if (packet == null)
return packet;
XMPPErrorException.ifHasErrorThenThrow(packet);
return packet;
}
};
when(collector.nextResultOrThrow()).thenAnswer(answerOrThrow);
when(collector.nextResultOrThrow(anyLong())).thenAnswer(answerOrThrow);
// initialize service discovery manager for this connection
ServiceDiscoveryManager.getInstanceFor(connection);
return connection;
}
use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.
the class Transcript method getIQChildElementBuilder.
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) {
buf.append(" sessionID=\"").append(sessionID).append("\">");
for (Iterator<Stanza> it = packets.iterator(); it.hasNext(); ) {
Stanza packet = it.next();
buf.append(packet.toXML());
}
return buf;
}
use of org.jivesoftware.smack.packet.Stanza in project xabber-android by redsolution.
the class ForwardedProvider method parse.
@Override
public Forwarded parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
DelayInformationProvider delayInformationProvider = new DelayInformationProvider();
DelayInformation delayInformation = null;
Stanza packet = null;
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("delay"))
delayInformation = delayInformationProvider.parse(parser);
else if (parser.getName().equals("message"))
packet = PacketParserUtils.parseMessage(parser);
else
throw new SmackException("Unsupported forwarded packet type: " + parser.getName());
} else if (eventType == XmlPullParser.END_TAG && parser.getName().equals(Forwarded.ELEMENT_NAME))
done = true;
}
if (packet == null)
throw new SmackException("forwarded extension must contain a packet");
return new Forwarded(delayInformation, packet);
}
use of org.jivesoftware.smack.packet.Stanza 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.packet.Stanza 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));
}
Aggregations