1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2025-12-08 22:21:08 +01:00

applied patches for extracted api for socks5 bytestreams and in-band bytestream

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/branches/improve_bytestreams@11818 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Henning Staib 2010-08-15 10:49:11 +00:00 committed by henning
parent 0540662db2
commit 8cb01900c9
72 changed files with 11761 additions and 1893 deletions

View file

@ -0,0 +1,77 @@
/**
* All rights reserved. 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.ibb;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ibb.packet.Close;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.powermock.reflect.Whitebox;
/**
* Test for the CloseListener class.
*
* @author Henning Staib
*/
public class CloseListenerTest {
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
/**
* If a close request to an unknown session is received it should be replied
* with an <item-not-found/> error.
*
* @throws Exception should not happen
*/
@Test
public void shouldReplyErrorIfSessionIsUnknown() throws Exception {
// mock connection
Connection connection = mock(Connection.class);
// initialize InBandBytestreamManager to get the CloseListener
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// get the CloseListener from InBandByteStreamManager
CloseListener closeListener = Whitebox.getInternalState(byteStreamManager,
CloseListener.class);
Close close = new Close("unknownSessionId");
close.setFrom(initiatorJID);
close.setTo(targetJID);
closeListener.processPacket(close);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// capture reply to the In-Band Bytestream close request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
argument.getValue().getError().getCondition());
}
}

View file

@ -0,0 +1,79 @@
/**
* All rights reserved. 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.ibb;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ibb.packet.Data;
import org.jivesoftware.smackx.ibb.packet.DataPacketExtension;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.powermock.reflect.Whitebox;
/**
* Test for the CloseListener class.
*
* @author Henning Staib
*/
public class DataListenerTest {
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
/**
* If a data packet of an unknown session is received it should be replied
* with an &lt;item-not-found/&gt; error.
*
* @throws Exception should not happen
*/
@Test
public void shouldReplyErrorIfSessionIsUnknown() throws Exception {
// mock connection
Connection connection = mock(Connection.class);
// initialize InBandBytestreamManager to get the DataListener
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// get the DataListener from InBandByteStreamManager
DataListener dataListener = Whitebox.getInternalState(byteStreamManager,
DataListener.class);
DataPacketExtension dpe = new DataPacketExtension("unknownSessionID", 0, "Data");
Data data = new Data(dpe);
data.setFrom(initiatorJID);
data.setTo(targetJID);
dataListener.processPacket(data);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// capture reply to the In-Band Bytestream close request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
argument.getValue().getError().getCondition());
}
}

View file

@ -0,0 +1,57 @@
package org.jivesoftware.smackx.ibb;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
/**
* Utility methods to create packets.
*
* @author Henning Staib
*/
public class IBBPacketUtils {
/**
* Returns an error IQ.
*
* @param from the senders JID
* @param to the recipients JID
* @param xmppError the XMPP error
* @return an error IQ
*/
public static IQ createErrorIQ(String from, String to, XMPPError xmppError) {
IQ errorIQ = new IQ() {
public String getChildElementXML() {
return null;
}
};
errorIQ.setType(IQ.Type.ERROR);
errorIQ.setFrom(from);
errorIQ.setTo(to);
errorIQ.setError(xmppError);
return errorIQ;
}
/**
* Returns a result IQ.
*
* @param from the senders JID
* @param to the recipients JID
* @return a result IQ
*/
public static IQ createResultIQ(String from, String to) {
IQ result = new IQ() {
public String getChildElementXML() {
return null;
}
};
result.setType(IQ.Type.RESULT);
result.setFrom(from);
result.setTo(to);
return result;
}
}

View file

@ -0,0 +1,21 @@
package org.jivesoftware.smackx.ibb;
import org.jivesoftware.smackx.ibb.packet.CloseTest;
import org.jivesoftware.smackx.ibb.packet.DataPacketExtensionTest;
import org.jivesoftware.smackx.ibb.packet.DataTest;
import org.jivesoftware.smackx.ibb.packet.OpenTest;
import org.jivesoftware.smackx.ibb.provider.OpenIQProviderTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses( { CloseTest.class, DataPacketExtensionTest.class, DataTest.class,
OpenTest.class, OpenIQProviderTest.class, CloseListenerTest.class,
DataListenerTest.class, InBandBytestreamManagerTest.class,
InBandBytestreamRequestTest.class,
InBandBytestreamSessionMessageTest.class,
InBandBytestreamSessionTest.class, InitiationListenerTest.class })
public class IBBTestsSuite {
// the class remains completely empty,
// being used only as a holder for the above annotations
}

View file

@ -0,0 +1,185 @@
/**
* All rights reserved. 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.ibb;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ibb.InBandBytestreamManager.StanzaType;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.jivesoftware.util.ConnectionUtils;
import org.jivesoftware.util.Protocol;
import org.jivesoftware.util.Verification;
import org.junit.Before;
import org.junit.Test;
/**
* Test for InBandBytestreamManager.
*
* @author Henning Staib
*/
public class InBandBytestreamManagerTest {
// settings
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String sessionID = "session_id";
// protocol verifier
Protocol protocol;
// mocked XMPP connection
Connection connection;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// build protocol verifier
protocol = new Protocol();
// create mocked XMPP connection
connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID,
xmppServer);
}
/**
* Test that
* {@link InBandBytestreamManager#getByteStreamManager(Connection)} returns
* one bytestream manager for every connection
*/
@Test
public void shouldHaveOneManagerForEveryConnection() {
// mock two connections
Connection connection1 = mock(Connection.class);
Connection connection2 = mock(Connection.class);
// get bytestream manager for the first connection twice
InBandBytestreamManager conn1ByteStreamManager1 = InBandBytestreamManager.getByteStreamManager(connection1);
InBandBytestreamManager conn1ByteStreamManager2 = InBandBytestreamManager.getByteStreamManager(connection1);
// get bytestream manager for second connection
InBandBytestreamManager conn2ByteStreamManager1 = InBandBytestreamManager.getByteStreamManager(connection2);
// assertions
assertEquals(conn1ByteStreamManager1, conn1ByteStreamManager2);
assertNotSame(conn1ByteStreamManager1, conn2ByteStreamManager1);
}
/**
* Invoking {@link InBandBytestreamManager#establishSession(String)} should
* throw an exception if the given target does not support in-band
* bytestream.
*/
@Test
public void shouldFailIfTargetDoesNotSupportIBB() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
try {
XMPPError xmppError = new XMPPError(
XMPPError.Condition.feature_not_implemented);
IQ errorIQ = IBBPacketUtils.createErrorIQ(targetJID, initiatorJID, xmppError);
protocol.addResponse(errorIQ);
// start In-Band Bytestream
byteStreamManager.establishSession(targetJID);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertEquals(XMPPError.Condition.feature_not_implemented.toString(),
e.getXMPPError().getCondition());
}
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowTooBigDefaultBlockSize() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
byteStreamManager.setDefaultBlockSize(1000000);
}
@Test
public void shouldCorrectlySetDefaultBlockSize() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
byteStreamManager.setDefaultBlockSize(1024);
assertEquals(1024, byteStreamManager.getDefaultBlockSize());
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowTooBigMaximumBlockSize() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
byteStreamManager.setMaximumBlockSize(1000000);
}
@Test
public void shouldCorrectlySetMaximumBlockSize() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
byteStreamManager.setMaximumBlockSize(1024);
assertEquals(1024, byteStreamManager.getMaximumBlockSize());
}
@Test
public void shouldUseConfiguredStanzaType() {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
byteStreamManager.setStanza(StanzaType.MESSAGE);
protocol.addResponse(null, new Verification<Open, IQ>() {
public void verify(Open request, IQ response) {
assertEquals(StanzaType.MESSAGE, request.getStanza());
}
});
try {
// start In-Band Bytestream
byteStreamManager.establishSession(targetJID);
}
catch (XMPPException e) {
protocol.verifyAll();
}
}
@Test
public void shouldReturnSession() throws Exception {
InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
IQ success = IBBPacketUtils.createResultIQ(targetJID, initiatorJID);
protocol.addResponse(success, Verification.correspondingSenderReceiver,
Verification.requestTypeSET);
// start In-Band Bytestream
InBandBytestreamSession session = byteStreamManager.establishSession(targetJID);
assertNotNull(session);
assertNotNull(session.getInputStream());
assertNotNull(session.getOutputStream());
protocol.verifyAll();
}
}

View file

@ -0,0 +1,98 @@
package org.jivesoftware.smackx.ibb;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
/**
* Test for InBandBytestreamRequest.
*
* @author Henning Staib
*/
public class InBandBytestreamRequestTest {
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String sessionID = "session_id";
Connection connection;
InBandBytestreamManager byteStreamManager;
Open initBytestream;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// mock connection
connection = mock(Connection.class);
// initialize InBandBytestreamManager to get the InitiationListener
byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// create a In-Band Bytestream open packet
initBytestream = new Open(sessionID, 4096);
initBytestream.setFrom(initiatorJID);
initBytestream.setTo(targetJID);
}
/**
* Test reject() method.
*/
@Test
public void shouldReplyWithErrorIfRequestIsRejected() {
InBandBytestreamRequest ibbRequest = new InBandBytestreamRequest(
byteStreamManager, initBytestream);
// reject request
ibbRequest.reject();
// capture reply to the In-Band Bytestream open request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.no_acceptable.toString(),
argument.getValue().getError().getCondition());
}
/**
* Test accept() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldReturnSessionIfRequestIsAccepted() throws Exception {
InBandBytestreamRequest ibbRequest = new InBandBytestreamRequest(
byteStreamManager, initBytestream);
// accept request
InBandBytestreamSession session = ibbRequest.accept();
// capture reply to the In-Band Bytestream open request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct acknowledgment packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.RESULT, argument.getValue().getType());
assertNotNull(session);
assertNotNull(session.getInputStream());
assertNotNull(session.getOutputStream());
}
}

View file

@ -0,0 +1,354 @@
package org.jivesoftware.smackx.ibb;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ibb.InBandBytestreamManager.StanzaType;
import org.jivesoftware.smackx.ibb.packet.DataPacketExtension;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.jivesoftware.util.ConnectionUtils;
import org.jivesoftware.util.Protocol;
import org.jivesoftware.util.Verification;
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
/**
* Test for InBandBytestreamSession.
* <p>
* Tests sending data encapsulated in message stanzas.
*
* @author Henning Staib
*/
public class InBandBytestreamSessionMessageTest {
// settings
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String sessionID = "session_id";
int blockSize = 10;
// protocol verifier
Protocol protocol;
// mocked XMPP connection
Connection connection;
InBandBytestreamManager byteStreamManager;
Open initBytestream;
Verification<Message, IQ> incrementingSequence;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// build protocol verifier
protocol = new Protocol();
// create mocked XMPP connection
connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID, xmppServer);
// initialize InBandBytestreamManager to get the InitiationListener
byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// create a In-Band Bytestream open packet with message stanza
initBytestream = new Open(sessionID, blockSize, StanzaType.MESSAGE);
initBytestream.setFrom(initiatorJID);
initBytestream.setTo(targetJID);
incrementingSequence = new Verification<Message, IQ>() {
long lastSeq = 0;
public void verify(Message request, IQ response) {
DataPacketExtension dpe = (DataPacketExtension) request.getExtension(
DataPacketExtension.ELEMENT_NAME, InBandBytestreamManager.NAMESPACE);
assertEquals(lastSeq++, dpe.getSeq());
}
};
}
/**
* Test the output stream write(byte[]) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets1() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// verify the data packets
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
byte[] controlData = new byte[blockSize * 3];
OutputStream outputStream = session.getOutputStream();
outputStream.write(controlData);
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream write(byte) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets2() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// verify the data packets
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
byte[] controlData = new byte[blockSize * 3];
OutputStream outputStream = session.getOutputStream();
for (byte b : controlData) {
outputStream.write(b);
}
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream write(byte[], int, int) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets3() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// verify the data packets
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
byte[] controlData = new byte[(blockSize * 3) - 2];
OutputStream outputStream = session.getOutputStream();
int off = 0;
for (int i = 1; i <= 7; i++) {
outputStream.write(controlData, off, i);
off += i;
}
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream flush() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThirtyDataPackets() throws Exception {
byte[] controlData = new byte[blockSize * 3];
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// verify the data packets
for (int i = 0; i < controlData.length; i++) {
protocol.addResponse(null, incrementingSequence);
}
OutputStream outputStream = session.getOutputStream();
for (byte b : controlData) {
outputStream.write(b);
outputStream.flush();
}
protocol.verifyAll();
}
/**
* Test successive calls to the output stream flush() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendNothingOnSuccessiveCallsToFlush() throws Exception {
byte[] controlData = new byte[blockSize * 3];
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// verify the data packets
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
protocol.addResponse(null, incrementingSequence);
OutputStream outputStream = session.getOutputStream();
outputStream.write(controlData);
outputStream.flush();
outputStream.flush();
outputStream.flush();
protocol.verifyAll();
}
/**
* If a data packet is received out of order the session should be closed. See XEP-0047 Section
* 2.2.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception {
// confirm close request
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ, Verification.requestTypeSET,
Verification.correspondingSenderReceiver);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build invalid packet with out of order sequence
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data);
Message dataMessage = new Message();
dataMessage.addExtension(dpe);
// add data packets
listener.processPacket(dataMessage);
// read until exception is thrown
try {
inputStream.read();
fail("exception should be thrown");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("Packets out of sequence"));
}
protocol.verifyAll();
}
/**
* Test the input stream read(byte[], int, int) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldReadAllReceivedData1() throws Exception {
// create random data
Random rand = new Random();
byte[] controlData = new byte[3 * blockSize];
rand.nextBytes(controlData);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// verify data packet and notify listener
for (int i = 0; i < controlData.length / blockSize; i++) {
String base64Data = StringUtils.encodeBase64(controlData, i * blockSize, blockSize,
false);
DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data);
Message dataMessage = new Message();
dataMessage.addExtension(dpe);
listener.processPacket(dataMessage);
}
byte[] bytes = new byte[3 * blockSize];
int read = 0;
read = inputStream.read(bytes, 0, blockSize);
assertEquals(blockSize, read);
read = inputStream.read(bytes, 10, blockSize);
assertEquals(blockSize, read);
read = inputStream.read(bytes, 20, blockSize);
assertEquals(blockSize, read);
// verify data
for (int i = 0; i < bytes.length; i++) {
assertEquals(controlData[i], bytes[i]);
}
protocol.verifyAll();
}
/**
* Test the input stream read() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldReadAllReceivedData2() throws Exception {
// create random data
Random rand = new Random();
byte[] controlData = new byte[3 * blockSize];
rand.nextBytes(controlData);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// verify data packet and notify listener
for (int i = 0; i < controlData.length / blockSize; i++) {
String base64Data = StringUtils.encodeBase64(controlData, i * blockSize, blockSize,
false);
DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data);
Message dataMessage = new Message();
dataMessage.addExtension(dpe);
listener.processPacket(dataMessage);
}
// read data
byte[] bytes = new byte[3 * blockSize];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) inputStream.read();
}
// verify data
for (int i = 0; i < bytes.length; i++) {
assertEquals(controlData[i], bytes[i]);
}
protocol.verifyAll();
}
}

View file

@ -0,0 +1,698 @@
package org.jivesoftware.smackx.ibb;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ibb.packet.Data;
import org.jivesoftware.smackx.ibb.packet.DataPacketExtension;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.jivesoftware.util.ConnectionUtils;
import org.jivesoftware.util.Protocol;
import org.jivesoftware.util.Verification;
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
/**
* Test for InBandBytestreamSession.
* <p>
* Tests the basic behavior of an In-Band Bytestream session along with sending data encapsulated in
* IQ stanzas.
*
* @author Henning Staib
*/
public class InBandBytestreamSessionTest {
// settings
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String sessionID = "session_id";
int blockSize = 10;
// protocol verifier
Protocol protocol;
// mocked XMPP connection
Connection connection;
InBandBytestreamManager byteStreamManager;
Open initBytestream;
Verification<Data, IQ> incrementingSequence;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// build protocol verifier
protocol = new Protocol();
// create mocked XMPP connection
connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID, xmppServer);
// initialize InBandBytestreamManager to get the InitiationListener
byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// create a In-Band Bytestream open packet
initBytestream = new Open(sessionID, blockSize);
initBytestream.setFrom(initiatorJID);
initBytestream.setTo(targetJID);
incrementingSequence = new Verification<Data, IQ>() {
long lastSeq = 0;
public void verify(Data request, IQ response) {
assertEquals(lastSeq++, request.getDataPacketExtension().getSeq());
}
};
}
/**
* Test the output stream write(byte[]) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets1() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
byte[] controlData = new byte[blockSize * 3];
OutputStream outputStream = session.getOutputStream();
outputStream.write(controlData);
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream write(byte) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets2() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
byte[] controlData = new byte[blockSize * 3];
OutputStream outputStream = session.getOutputStream();
for (byte b : controlData) {
outputStream.write(b);
}
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream write(byte[], int, int) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThreeDataPackets3() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
byte[] controlData = new byte[(blockSize * 3) - 2];
OutputStream outputStream = session.getOutputStream();
int off = 0;
for (int i = 1; i <= 7; i++) {
outputStream.write(controlData, off, i);
off += i;
}
outputStream.flush();
protocol.verifyAll();
}
/**
* Test the output stream flush() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendThirtyDataPackets() throws Exception {
byte[] controlData = new byte[blockSize * 3];
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
for (int i = 0; i < controlData.length; i++) {
protocol.addResponse(resultIQ, incrementingSequence);
}
OutputStream outputStream = session.getOutputStream();
for (byte b : controlData) {
outputStream.write(b);
outputStream.flush();
}
protocol.verifyAll();
}
/**
* Test successive calls to the output stream flush() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendNothingOnSuccessiveCallsToFlush() throws Exception {
byte[] controlData = new byte[blockSize * 3];
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
protocol.addResponse(resultIQ, incrementingSequence);
OutputStream outputStream = session.getOutputStream();
outputStream.write(controlData);
outputStream.flush();
outputStream.flush();
outputStream.flush();
protocol.verifyAll();
}
/**
* Test that the data is correctly chunked.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendDataCorrectly() throws Exception {
// create random data
Random rand = new Random();
final byte[] controlData = new byte[256 * blockSize];
rand.nextBytes(controlData);
// compares the data of each packet with the control data
Verification<Data, IQ> dataVerification = new Verification<Data, IQ>() {
public void verify(Data request, IQ response) {
byte[] decodedData = request.getDataPacketExtension().getDecodedData();
int seq = (int) request.getDataPacketExtension().getSeq();
for (int i = 0; i < decodedData.length; i++) {
assertEquals(controlData[(seq * blockSize) + i], decodedData[i]);
}
}
};
// set acknowledgments for the data packets
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
for (int i = 0; i < controlData.length / blockSize; i++) {
protocol.addResponse(resultIQ, incrementingSequence, dataVerification);
}
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
OutputStream outputStream = session.getOutputStream();
outputStream.write(controlData);
outputStream.flush();
protocol.verifyAll();
}
/**
* If the input stream is closed the output stream should not be closed as well.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotCloseBothStreamsIfOutputStreamIsClosed() throws Exception {
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
OutputStream outputStream = session.getOutputStream();
outputStream.close();
// verify data packet confirmation is of type RESULT
protocol.addResponse(null, Verification.requestTypeRESULT);
// insert data to read
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data = new Data(dpe);
listener.processPacket(data);
// verify no packet send
protocol.verifyAll();
try {
outputStream.flush();
fail("should throw an exception");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("closed"));
}
assertTrue(inputStream.read() != 0);
}
/**
* Valid data packets should be confirmed.
*
* @throws Exception should not happen
*/
@Test
public void shouldConfirmReceivedDataPacket() throws Exception {
// verify data packet confirmation is of type RESULT
protocol.addResponse(null, Verification.requestTypeRESULT);
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data = new Data(dpe);
listener.processPacket(data);
protocol.verifyAll();
}
/**
* If the data packet has a sequence that is already used an 'unexpected-request' error should
* be returned. See XEP-0047 Section 2.2.
*
* @throws Exception should not happen
*/
@Test
public void shouldReplyWithErrorIfAlreadyUsedSequenceIsReceived() throws Exception {
// verify reply to first valid data packet is of type RESULT
protocol.addResponse(null, Verification.requestTypeRESULT);
// verify reply to invalid data packet is an error
protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() {
public void verify(IQ request, IQ response) {
assertEquals(XMPPError.Condition.unexpected_request.toString(),
request.getError().getCondition());
}
});
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build data packets
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data1 = new Data(dpe);
Data data2 = new Data(dpe);
// notify listener
listener.processPacket(data1);
listener.processPacket(data2);
protocol.verifyAll();
}
/**
* If the data packet contains invalid Base64 encoding an 'bad-request' error should be
* returned. See XEP-0047 Section 2.2.
*
* @throws Exception should not happen
*/
@Test
public void shouldReplyWithErrorIfDataIsInvalid() throws Exception {
// verify reply to invalid data packet is an error
protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() {
public void verify(IQ request, IQ response) {
assertEquals(XMPPError.Condition.bad_request.toString(),
request.getError().getCondition());
}
});
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build data packets
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, "AA=BB");
Data data = new Data(dpe);
// notify listener
listener.processPacket(data);
protocol.verifyAll();
}
/**
* If a data packet is received out of order the session should be closed. See XEP-0047 Section
* 2.2.
*
* @throws Exception should not happen
*/
@Test
public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception {
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
// confirm data packet with invalid sequence
protocol.addResponse(resultIQ);
// confirm close request
protocol.addResponse(resultIQ, Verification.requestTypeSET,
Verification.correspondingSenderReceiver);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build invalid packet with out of order sequence
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data);
Data data = new Data(dpe);
// add data packets
listener.processPacket(data);
// read until exception is thrown
try {
inputStream.read();
fail("exception should be thrown");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("Packets out of sequence"));
}
protocol.verifyAll();
}
/**
* Test the input stream read(byte[], int, int) method.
*
* @throws Exception should not happen
*/
@Test
public void shouldReadAllReceivedData1() throws Exception {
// create random data
Random rand = new Random();
byte[] controlData = new byte[3 * blockSize];
rand.nextBytes(controlData);
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// set data packet acknowledgment and notify listener
for (int i = 0; i < controlData.length / blockSize; i++) {
protocol.addResponse(resultIQ);
String base64Data = StringUtils.encodeBase64(controlData, i * blockSize, blockSize,
false);
DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data);
Data data = new Data(dpe);
listener.processPacket(data);
}
byte[] bytes = new byte[3 * blockSize];
int read = 0;
read = inputStream.read(bytes, 0, blockSize);
assertEquals(blockSize, read);
read = inputStream.read(bytes, 10, blockSize);
assertEquals(blockSize, read);
read = inputStream.read(bytes, 20, blockSize);
assertEquals(blockSize, read);
// verify data
for (int i = 0; i < bytes.length; i++) {
assertEquals(controlData[i], bytes[i]);
}
protocol.verifyAll();
}
/**
* Test the input stream read() method.
*
* @throws Exception should not happen
*/
@Test
public void shouldReadAllReceivedData2() throws Exception {
// create random data
Random rand = new Random();
byte[] controlData = new byte[3 * blockSize];
rand.nextBytes(controlData);
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// set data packet acknowledgment and notify listener
for (int i = 0; i < controlData.length / blockSize; i++) {
protocol.addResponse(resultIQ);
String base64Data = StringUtils.encodeBase64(controlData, i * blockSize, blockSize,
false);
DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data);
Data data = new Data(dpe);
listener.processPacket(data);
}
// read data
byte[] bytes = new byte[3 * blockSize];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) inputStream.read();
}
// verify data
for (int i = 0; i < bytes.length; i++) {
assertEquals(controlData[i], bytes[i]);
}
protocol.verifyAll();
}
/**
* If the output stream is closed the input stream should not be closed as well.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotCloseBothStreamsIfInputStreamIsClosed() throws Exception {
// acknowledgment for data packet
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build data packet
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data = new Data(dpe);
// add data packets
listener.processPacket(data);
inputStream.close();
protocol.verifyAll();
try {
while (inputStream.read() != -1) {
}
inputStream.read();
fail("should throw an exception");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("closed"));
}
session.getOutputStream().flush();
}
/**
* If the session is closed the input stream and output stream should be closed as well.
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseBothStreamsIfSessionIsClosed() throws Exception {
// acknowledgment for data packet
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ);
// acknowledgment for close request
protocol.addResponse(resultIQ, Verification.correspondingSenderReceiver,
Verification.requestTypeSET);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build data packet
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data = new Data(dpe);
// add data packets
listener.processPacket(data);
session.close();
protocol.verifyAll();
try {
while (inputStream.read() != -1) {
}
inputStream.read();
fail("should throw an exception");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("closed"));
}
try {
session.getOutputStream().flush();
fail("should throw an exception");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("closed"));
}
}
/**
* If the input stream is closed concurrently there should be no deadlock.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotDeadlockIfInputStreamIsClosed() throws Exception {
// acknowledgment for data packet
IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
protocol.addResponse(resultIQ);
// get IBB sessions data packet listener
InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
initiatorJID);
final InputStream inputStream = session.getInputStream();
PacketListener listener = Whitebox.getInternalState(inputStream, PacketListener.class);
// build data packet
String base64Data = StringUtils.encodeBase64("Data");
DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
Data data = new Data(dpe);
// add data packets
listener.processPacket(data);
Thread closer = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(200);
inputStream.close();
}
catch (Exception e) {
fail(e.getMessage());
}
}
});
closer.start();
try {
byte[] bytes = new byte[20];
while (inputStream.read(bytes) != -1) {
}
inputStream.read();
fail("should throw an exception");
}
catch (IOException e) {
assertTrue(e.getMessage().contains("closed"));
}
protocol.verifyAll();
}
}

View file

@ -0,0 +1,327 @@
/**
* All rights reserved. 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.ibb;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.bytestreams.BytestreamRequest;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.powermock.reflect.Whitebox;
/**
* Test for the InitiationListener class.
*
* @author Henning Staib
*/
public class InitiationListenerTest {
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String sessionID = "session_id";
Connection connection;
InBandBytestreamManager byteStreamManager;
InitiationListener initiationListener;
Open initBytestream;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// mock connection
connection = mock(Connection.class);
// initialize InBandBytestreamManager to get the InitiationListener
byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);
// get the InitiationListener from InBandByteStreamManager
initiationListener = Whitebox.getInternalState(byteStreamManager, InitiationListener.class);
// create a In-Band Bytestream open packet
initBytestream = new Open(sessionID, 4096);
initBytestream.setFrom(initiatorJID);
initBytestream.setTo(targetJID);
}
/**
* If no listeners are registered for incoming In-Band Bytestream requests, all request should
* be rejected with an error.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithError() throws Exception {
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// capture reply to the In-Band Bytestream open request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.no_acceptable.toString(),
argument.getValue().getError().getCondition());
}
/**
* Open request with a block size that exceeds the maximum block size should be replied with an
* resource-constraint error.
*
* @throws Exception should not happen
*/
@Test
public void shouldRejectRequestWithTooBigBlockSize() throws Exception {
byteStreamManager.setMaximumBlockSize(1024);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// capture reply to the In-Band Bytestream open request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.resource_constraint.toString(),
argument.getValue().getError().getCondition());
}
/**
* If a listener for all requests is registered it should be notified on incoming requests.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeListenerForAllRequests() throws Exception {
// add listener
InBandBytestreamListener listener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert that listener is called for the correct request
assertEquals(initiatorJID, byteStreamRequest.getValue().getFrom());
}
/**
* If a listener for a specific user in registered it should be notified on incoming requests
* for that user.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeListenerForUser() throws Exception {
// add listener
InBandBytestreamListener listener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener, initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, byteStreamRequest.getValue().getFrom());
}
/**
* If listener for a specific user is registered it should not be notified on incoming requests
* from other users.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotInvokeListenerForUser() throws Exception {
// add listener for request of user "other_initiator"
InBandBytestreamListener listener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener, "other_" + initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// capture reply to the In-Band Bytestream open request
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.no_acceptable.toString(),
argument.getValue().getError().getCondition());
}
/**
* If a user specific listener and an all requests listener is registered only the user specific
* listener should be notified.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotInvokeAllRequestsListenerIfUserListenerExists() throws Exception {
// add listener for all request
InBandBytestreamListener allRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "initiator"
InBandBytestreamListener userRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
}
/**
* If a user specific listener and an all requests listener is registered only the all requests
* listener should be notified on an incoming request for another user.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeAllRequestsListenerIfUserListenerExists() throws Exception {
// add listener for all request
InBandBytestreamListener allRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "other_initiator"
InBandBytestreamListener userRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, "other_"
+ initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
}
/**
* If a request with a specific session ID should be ignored no listeners should be notified.
*
* @throws Exception should not happen
*/
@Test
public void shouldIgnoreInBandBytestreamRequestOnce() throws Exception {
// add listener for all request
InBandBytestreamListener allRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "initiator"
InBandBytestreamListener userRequestsListener = mock(InBandBytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, initiatorJID);
// ignore session ID
byteStreamManager.ignoreBytestreamRequestOnce(sessionID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// run the listener with the initiation packet again
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is called on the second request with the
// same session ID
verify(userRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
}
}

View file

@ -0,0 +1,80 @@
/**
* All rights reserved. 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.ibb.packet;
import static junit.framework.Assert.*;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.util.Properties;
import org.jivesoftware.smack.packet.IQ;
import org.junit.Test;
import com.jamesmurty.utils.XMLBuilder;
/**
* Test for the Close class.
*
* @author Henning Staib
*/
public class CloseTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArguments1() {
new Close(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArguments2() {
new Close("");
}
@Test
public void shouldBeOfIQTypeSET() {
Close close = new Close("sessionID");
assertEquals(IQ.Type.SET, close.getType());
}
@Test
public void shouldSetAllFieldsCorrectly() {
Close close = new Close("sessionID");
assertEquals("sessionID", close.getSessionID());
}
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
String control = XMLBuilder.create("iq")
.a("from", "romeo@montague.lit/orchard")
.a("to", "juliet@capulet.lit/balcony")
.a("id", "us71g45j")
.a("type", "set")
.e("close")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("sid", "i781hf64")
.asString(outputProperties);
Close close = new Close("i781hf64");
close.setFrom("romeo@montague.lit/orchard");
close.setTo("juliet@capulet.lit/balcony");
close.setPacketID("us71g45j");
assertXMLEqual(control, close.toXML());
}
}

View file

@ -0,0 +1,94 @@
/**
* All rights reserved. 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.ibb.packet;
import static junit.framework.Assert.*;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.util.Properties;
import org.junit.Test;
import com.jamesmurty.utils.XMLBuilder;
/**
* Test for the DataPacketExtension class.
*
* @author Henning Staib
*/
public class DataPacketExtensionTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument1() {
new DataPacketExtension(null, 0, "data");
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument2() {
new DataPacketExtension("", 0, "data");
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument3() {
new DataPacketExtension("sessionID", -1, "data");
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument4() {
new DataPacketExtension("sessionID", 70000, "data");
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument5() {
new DataPacketExtension("sessionID", 0, null);
}
@Test
public void shouldSetAllFieldsCorrectly() {
DataPacketExtension data = new DataPacketExtension("sessionID", 0, "data");
assertEquals("sessionID", data.getSessionID());
assertEquals(0, data.getSeq());
assertEquals("data", data.getData());
}
@Test
public void shouldReturnNullIfDataIsInvalid() {
// pad character is not at end of data
DataPacketExtension data = new DataPacketExtension("sessionID", 0, "BBBB=CCC");
assertNull(data.getDecodedData());
// invalid Base64 character
data = new DataPacketExtension("sessionID", 0, new String(new byte[] { 123 }));
assertNull(data.getDecodedData());
}
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
String control = XMLBuilder.create("data")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("seq", "0")
.a("sid", "i781hf64")
.t("DATA")
.asString(outputProperties);
DataPacketExtension data = new DataPacketExtension("i781hf64", 0, "DATA");
assertXMLEqual(control, data.toXML());
}
}

View file

@ -0,0 +1,84 @@
/**
* All rights reserved. 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.ibb.packet;
import static junit.framework.Assert.*;
import static org.custommonkey.xmlunit.XMLAssert.*;
import static org.mockito.Mockito.*;
import java.util.Properties;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.Base64;
import org.junit.Test;
import com.jamesmurty.utils.XMLBuilder;
/**
* Test for the Data class.
*
* @author Henning Staib
*/
public class DataTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArgument() {
new Data(null);
}
@Test
public void shouldBeOfIQTypeSET() {
DataPacketExtension dpe = mock(DataPacketExtension.class);
Data data = new Data(dpe);
assertEquals(IQ.Type.SET, data.getType());
}
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
String encodedData = Base64.encodeBytes("Test".getBytes());
String control = XMLBuilder.create("iq")
.a("from", "romeo@montague.lit/orchard")
.a("to", "juliet@capulet.lit/balcony")
.a("id", "kr91n475")
.a("type", "set")
.e("data")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("seq", "0")
.a("sid", "i781hf64")
.t(encodedData)
.asString(outputProperties);
DataPacketExtension dpe = mock(DataPacketExtension.class);
String dataTag = XMLBuilder.create("data")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("seq", "0")
.a("sid", "i781hf64")
.t(encodedData)
.asString(outputProperties);
when(dpe.toXML()).thenReturn(dataTag);
Data data = new Data(dpe);
data.setFrom("romeo@montague.lit/orchard");
data.setTo("juliet@capulet.lit/balcony");
data.setPacketID("kr91n475");
assertXMLEqual(control, data.toXML());
}
}

View file

@ -0,0 +1,103 @@
/**
* All rights reserved. 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.ibb.packet;
import static junit.framework.Assert.*;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.util.Properties;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.ibb.InBandBytestreamManager.StanzaType;
import org.junit.Test;
import com.jamesmurty.utils.XMLBuilder;
/**
* Test for the Open class.
*
* @author Henning Staib
*/
public class OpenTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArguments1() {
new Open(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArguments2() {
new Open("", 1);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotInstantiateWithInvalidArguments3() {
new Open("sessionID", -1);
}
@Test
public void shouldSetIQStanzaAsDefault() {
Open open = new Open("sessionID", 4096);
assertEquals(StanzaType.IQ, open.getStanza());
}
@Test
public void shouldUseMessageStanzaIfGiven() {
Open open = new Open("sessionID", 4096, StanzaType.MESSAGE);
assertEquals(StanzaType.MESSAGE, open.getStanza());
}
@Test
public void shouldBeOfIQTypeSET() {
Open open = new Open("sessionID", 4096);
assertEquals(IQ.Type.SET, open.getType());
}
@Test
public void shouldSetAllFieldsCorrectly() {
Open open = new Open("sessionID", 4096, StanzaType.MESSAGE);
assertEquals("sessionID", open.getSessionID());
assertEquals(4096, open.getBlockSize());
assertEquals(StanzaType.MESSAGE, open.getStanza());
}
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
String control = XMLBuilder.create("iq")
.a("from", "romeo@montague.lit/orchard")
.a("to", "juliet@capulet.lit/balcony")
.a("id", "jn3h8g65")
.a("type", "set")
.e("open")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("block-size", "4096")
.a("sid", "i781hf64")
.a("stanza", "iq")
.asString(outputProperties);
Open open = new Open("i781hf64", 4096, StanzaType.IQ);
open.setFrom("romeo@montague.lit/orchard");
open.setTo("juliet@capulet.lit/balcony");
open.setPacketID("jn3h8g65");
assertXMLEqual(control, open.toXML());
}
}

View file

@ -0,0 +1,86 @@
/**
* All rights reserved. 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.ibb.provider;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import org.jivesoftware.smackx.ibb.InBandBytestreamManager.StanzaType;
import org.jivesoftware.smackx.ibb.packet.Open;
import org.junit.Test;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.jamesmurty.utils.XMLBuilder;
/**
* Test for the OpenIQProvider class.
*
* @author Henning Staib
*/
public class OpenIQProviderTest {
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void shouldCorrectlyParseIQStanzaAttribute() throws Exception {
String control = XMLBuilder.create("open")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("block-size", "4096")
.a("sid", "i781hf64")
.a("stanza", "iq")
.asString(outputProperties);
OpenIQProvider oip = new OpenIQProvider();
Open open = (Open) oip.parseIQ(getParser(control));
assertEquals(StanzaType.IQ, open.getStanza());
}
@Test
public void shouldCorrectlyParseMessageStanzaAttribute() throws Exception {
String control = XMLBuilder.create("open")
.a("xmlns", "http://jabber.org/protocol/ibb")
.a("block-size", "4096")
.a("sid", "i781hf64")
.a("stanza", "message")
.asString(outputProperties);
OpenIQProvider oip = new OpenIQProvider();
Open open = (Open) oip.parseIQ(getParser(control));
assertEquals(StanzaType.MESSAGE, open.getStanza());
}
private XmlPullParser getParser(String control) throws XmlPullParserException,
IOException {
XmlPullParser parser = new MXParser();
parser.setInput(new StringReader(control));
while (true) {
if (parser.next() == XmlPullParser.START_TAG
&& parser.getName().equals("open")) {
break;
}
}
return parser;
}
}