tests for receiving authorization requests

cusax-fix
Damian Minkov 20 years ago
parent da89d23f85
commit 48e1ad68c0

@ -49,7 +49,7 @@ public class IcqTesterAgent
/**
* We use this field to determine whether registration has gone ok.
*/
private IcbmService icbmService = null;
private IcbmService icbmService = null;
/**
* The AimConnection that the IcqEchoTest user has established with the icq
@ -384,6 +384,9 @@ public synchronized void handleStateChange(StateEvent event)
icbmService.getOscarConnection().getSnacProcessor().
getCmdFactoryMgr().getDefaultFactoryList().
registerAll(authCmdFactory);
icbmService.getOscarConnection().getSnacProcessor().
addGlobalResponseListener(authCmdFactory);
}
else if (event.getNewState() == State.FAILED
|| event.getNewState() == State.DISCONNECTED)
@ -695,6 +698,7 @@ private class LayoutEventCollector
{
public Vector addedGroups = new Vector();
public Vector addedBuddies = new Vector();
public Vector removedBuddies = new Vector();
/**
* The method would wait until at least one new buddy is collected by
@ -738,6 +742,26 @@ public void waitForANewGroup(int milliseconds)
}
}
public void waitForRemovedBuddy(int milliseconds)
{
synchronized (this.removedBuddies)
{
if (!removedBuddies.isEmpty())
{
return;
}
try
{
this.removedBuddies.wait(milliseconds);
}
catch (InterruptedException ex)
{
logger.warn("A strange thing happened while waiting", ex);
}
}
}
/**
* Registers a reference to the group that has just been created and
* call a notifyAll() on this.
@ -1004,6 +1028,7 @@ public void groupNameChanged(Group group, String oldName,
}
}
////////////////////////// ugly unused testing code //////////////////////////
private RetroListener rl = new RetroListener();
public static void main(String[] args) throws Throwable
@ -1025,8 +1050,6 @@ public static void main(String[] args) throws Throwable
java.util.logging.Logger.getLogger("net.kano").setLevel(java.util.logging.Level.FINEST);
MutableBuddyList list = icqtests.conn.getSsiService().getBuddyList();
MutableGroup dupeGroup = null;
@ -1081,9 +1104,6 @@ public static void main(String[] args) throws Throwable
if (buddyToMove == movedBuddy)
System.out.println("hahaha");
}
private class TestSnacCmd extends SnacCommand
@ -1108,6 +1128,79 @@ public void writeData(OutputStream out) throws IOException
}
}
public void deleteBuddy(String screenname)
{
logger.debug("Will delete buddy : " + screenname);
MutableBuddyList joustSimBuddyList
= (MutableBuddyList)conn.getSsiService().getBuddyList();
LayoutEventCollector evtCollector = new LayoutEventCollector();
joustSimBuddyList.addLayoutListener(evtCollector);
List grList = joustSimBuddyList.getGroups();
boolean isDeleted = false;
Iterator iter = grList.iterator();
while (iter.hasNext())
{
MutableGroup item = (MutableGroup) iter.next();
List bs = item.getBuddiesCopy();
Iterator iter1 = bs.iterator();
while (iter1.hasNext())
{
Buddy b = (Buddy) iter1.next();
if(b.getScreenname().getFormatted().equals(screenname))
{
item.deleteBuddy(b);
isDeleted = true;
}
}
if(isDeleted)
break;
}
evtCollector.waitForRemovedBuddy(10000);
joustSimBuddyList.removeLayoutListener(evtCollector);
}
public void addBuddy(String screenname)
{
logger.debug("Will add buddy : " + screenname);
MutableBuddyList joustSimBuddyList
= (MutableBuddyList)conn.getSsiService().getBuddyList();
LayoutEventCollector evtCollector = new LayoutEventCollector();
joustSimBuddyList.addLayoutListener(evtCollector);
List grList = joustSimBuddyList.getGroups();
Iterator iter = grList.iterator();
while (iter.hasNext())
{
MutableGroup item = (MutableGroup) iter.next();
logger.debug("group : " + item);
List bs = item.getBuddiesCopy();
Iterator iter1 = bs.iterator();
while (iter1.hasNext())
{
Object b = (Object) iter1.next();
logger.debug("buddy : " + b);
}
}
if(grList.size() < 1)
{
logger.debug("No groups! Will stop now");
return;
}
((MutableGroup)grList.get(0)).addBuddy(screenname);
evtCollector.waitForANewBuddy(10000);
joustSimBuddyList.removeLayoutListener(evtCollector);
}
/**
* Sends <tt>body</tt> to <tt>buddy</tt> as an offline instant message
* @param buddy the screenname of the budy that we'd like to send our msg to.
@ -1200,6 +1293,7 @@ public void writeData(OutputStream out)
public class AuthCmdFactory
extends ServerSsiCmdFactory
implements SnacResponseListener
{
List SUPPORTED_TYPES = null;
@ -1207,6 +1301,9 @@ public class AuthCmdFactory
public String requestReasonStr = null;
public boolean ACCEPT = false;
public boolean isErrorAddingReceived = false;
public boolean isRequestAccepted = false;
public AuthCmdFactory()
{
List types = super.getSupportedTypes();
@ -1249,22 +1346,82 @@ public SnacCommand genSnacCommand(SnacPacket packet)
ACCEPT));
return cmd;
}
else if (command == 26) // auth reply
else if (command == 27) // auth reply
{
AuthReplyCmd cmd = new AuthReplyCmd(packet);
System.out.println("cmd " + cmd);
System.out.println("is accepted " + cmd.accepted);
System.out.println("reason " + cmd.reason);
isRequestAccepted = cmd.accepted;
responseReasonStr = cmd.reason;
return cmd;
}
return super.genSnacCommand(packet);
}
public void handleResponse(SnacResponseEvent e)
{
if (e.getSnacCommand() instanceof SsiDataModResponse)
{
SsiDataModResponse dataModResponse =
(SsiDataModResponse) e.getSnacCommand();
int[] results = dataModResponse.getResults();
List items = ( (ItemsCmd) e.getRequest().getCommand()).
getItems();
items = new LinkedList(items);
for (int i = 0; i < results.length; i++)
{
int result = results[i];
if (result ==
SsiDataModResponse.RESULT_ICQ_AUTH_REQUIRED)
{
isErrorAddingReceived = true;
// authorisation required for user
SsiItem buddyItem = (SsiItem) items.get(i);
String uinToAskForAuth = buddyItem.getName();
logger.trace("finding buddy : " + uinToAskForAuth);
Vector buddiesToBeAdded = new Vector();
BuddyAwaitingAuth newBuddy = new BuddyAwaitingAuth(
buddyItem);
buddiesToBeAdded.add(newBuddy);
CreateItemsCmd addCMD = new CreateItemsCmd(buddiesToBeAdded);
logger.trace("Adding buddy as awaiting authorization");
MutableBuddyList joustSimBuddyList
= (MutableBuddyList)conn.getSsiService().getBuddyList();
LayoutEventCollector evtCollector = new LayoutEventCollector();
joustSimBuddyList.addLayoutListener(evtCollector);
conn.getSsiService().sendSnac(addCMD);
evtCollector.waitForANewBuddy(15000);
joustSimBuddyList.removeLayoutListener(evtCollector);
logger.trace("Finished - Adding buddy as awaiting authorization");
//SNAC(13,18) send authorization request
conn.getSsiService().sendSnac(
new RequestAuthCmd(
uinToAskForAuth,
requestReasonStr));
}
}
}
}
}
public class RequestAuthCmd
private class RequestAuthCmd
extends SsiCommand
{
String uin;
@ -1389,4 +1546,57 @@ public void writeUShort(OutputStream out, int number)
}
}
private static class BuddyAwaitingAuth
extends SsiItem
{
private SsiItem originalItem = null;
public BuddyAwaitingAuth(SsiItem originalItem)
{
super(
originalItem.getName(),
originalItem.getParentId(),
originalItem.getId(),
originalItem.getItemType(),
getSpecTlvData());
this.originalItem = originalItem;
}
public void write(OutputStream out) throws IOException
{
byte[] namebytes = BinaryTools.getAsciiBytes(originalItem.getName());
BinaryTools.writeUShort(out, namebytes.length);
out.write(namebytes);
BinaryTools.writeUShort(out, originalItem.getParentId());
BinaryTools.writeUShort(out, originalItem.getId());
BinaryTools.writeUShort(out, originalItem.getItemType());
ByteBlock data = getData();
// here we are nice and let data be null
int len = data == null ? 0 : data.getLength();
BinaryTools.writeUShort(out, len);
if (data != null)
{
data.write(out);
}
}
private static ByteBlock getSpecTlvData()
{
try
{
ByteArrayOutputStream o = new ByteArrayOutputStream();
new Tlv(0x0066).write(o);
ByteBlock block = ByteBlock.wrap(o.toByteArray());
return block;
}
catch (IOException ex)
{
logger.error("Error creating buddy awaiting auth tlv", ex);
return null;
}
}
}
}

@ -28,6 +28,7 @@
* postTestUnsubscribe().
* <p>
* @author Emil Ivov
* @author Damian Minkov
*/
public class TestOperationSetPresence
extends TestCase
@ -39,6 +40,9 @@ public class TestOperationSetPresence
private OperationSetPresence operationSetPresence = null;
private String statusMessageRoot = new String("Our status is now: ");
// be sure its only one
private static AuthEventCollector authEventCollector = new AuthEventCollector();
public TestOperationSetPresence(String name)
{
super(name);
@ -96,6 +100,10 @@ public static Test suite()
suite.addTest(new TestOperationSetPresence("postTestSubscribe"));
suite.addTest(new TestOperationSetPresence("postTestUnsubscribe"));
// execute this test after postTestSubscribe
// to be sure that AuthorizationHandler is installed
suite.addTest(new TestOperationSetPresence("postTestReceiveAuthorizatinonRequest"));
return suite;
}
@ -414,8 +422,6 @@ public void postTestSubscribe()
SubscriptionEventCollector subEvtCollector
= new SubscriptionEventCollector();
AuthEventCollector authEventCollector = new AuthEventCollector();
logger.trace("set Auth Handler");
operationSetPresence.setAuthorizationHandler(authEventCollector);
@ -1018,7 +1024,7 @@ public void contactPresenceStatusChanged(
}
}
private class AuthEventCollector
private static class AuthEventCollector
implements AuthorizationHandler
{
boolean isAuthorizationRequestSent = false;
@ -1028,11 +1034,38 @@ private class AuthEventCollector
AuthorizationResponse response = null;
String authorizationResponseString = null;
// receiving auth request
AuthorizationResponse responseToRequest = null;
boolean isAuthorizationRequestReceived = false;
public AuthorizationResponse processAuthorisationRequest(
AuthorizationRequest req, Contact sourceContact)
{
logger.trace("processAuthorisationRequest " + req + " " + sourceContact);
return null;
logger.debug("Processing in " + this);
synchronized(this)
{
logger.trace("processAuthorisationRequest " + req + " " +
sourceContact);
isAuthorizationRequestReceived = true;
authorizationRequestReason = req.getReason();
notifyAll();
// will wait as a normal user
Object lock = new Object();
synchronized (lock)
{
try
{
lock.wait(2000);
}
catch (Exception ex)
{}
}
return responseToRequest;
}
}
public AuthorizationRequest createAuthorizationRequest(Contact contact)
@ -1079,6 +1112,21 @@ public void waitForAuthResponse(long waitFor)
}
}
public void waitForAuthRequest(long waitFor)
{
synchronized(this){
if(isAuthorizationRequestReceived) return;
try{
wait(waitFor);
}
catch (InterruptedException ex){
logger.debug(
"Interrupted while waiting for a subscription evt", ex);
}
}
}
}
private class UnsubscribeWait implements SubscriptionListener
@ -1115,4 +1163,128 @@ public void subscriptionResolved(SubscriptionEvent evt)
{}
}
/**
* Tests for receiving authorization requests
*/
public void postTestReceiveAuthorizatinonRequest()
{
logger.debug("Testing receive of authorization request!");
// set first response isAccepted and responseString
String firstRequestResponse = "First Request will be denied!!!";
authEventCollector.responseToRequest = new AuthorizationResponse(AuthorizationResponse.REJECT, firstRequestResponse);
logger.debug("authEventCollector " + authEventCollector);
authEventCollector.isAuthorizationRequestReceived = false;
authEventCollector.authorizationRequestReason = null;
fixture.testerAgent.getAuthCmdFactory().requestReasonStr = "Deny my first request!";
fixture.testerAgent.getAuthCmdFactory().isErrorAddingReceived = false;
fixture.testerAgent.getAuthCmdFactory().responseReasonStr = null;
fixture.testerAgent.getAuthCmdFactory().isRequestAccepted = false;
// be sure buddy is not already in the list
fixture.testerAgent.deleteBuddy(fixture.ourAccountID);
fixture.testerAgent.addBuddy(fixture.ourAccountID);
// wait agent to receive error and to request us for our authorization
authEventCollector.waitForAuthRequest(25000);
// check have we received authorization request?
assertTrue("Error adding buddy not recieved or the buddy(" +
fixture.ourAccountID +
") doesn't require authorization",
fixture.testerAgent.getAuthCmdFactory().isErrorAddingReceived);
assertTrue("We haven't received any authorization request ",
authEventCollector.isAuthorizationRequestReceived);
assertNotNull("We haven't received any reason for authorization",
authEventCollector.authorizationRequestReason);
assertEquals("Error sent request reason is not as the received one",
fixture.testerAgent.getAuthCmdFactory().requestReasonStr,
authEventCollector.authorizationRequestReason
);
// wait agent to receive our response
Object lock = new Object();
synchronized(lock){
try{
lock.wait(5000);
}
catch (Exception ex){}
}
// check is correct - the received response from the agent
assertNotNull("Agent haven't received any reason from authorization reply",
authEventCollector.authorizationRequestReason);
assertEquals("Received auth response from agent is not as the sent one",
fixture.testerAgent.getAuthCmdFactory().responseReasonStr,
firstRequestResponse);
boolean isAcceptedAuthReuest =
authEventCollector.responseToRequest.getResponseCode().equals(AuthorizationResponse.ACCEPT);
assertEquals("Agent received Response is not as the sent one",
fixture.testerAgent.getAuthCmdFactory().isRequestAccepted,
isAcceptedAuthReuest);
// delete us from his list
// be sure buddy is not already in the list
fixture.testerAgent.deleteBuddy(fixture.ourAccountID);
// set second response isAccepted and responseString
String secondRequestResponse = "Second Request will be accepted!!!";
authEventCollector.responseToRequest =
new AuthorizationResponse(AuthorizationResponse.ACCEPT, secondRequestResponse);
authEventCollector.isAuthorizationRequestReceived = false;
authEventCollector.authorizationRequestReason = null;
fixture.testerAgent.getAuthCmdFactory().requestReasonStr = "Accept my second request!";
fixture.testerAgent.getAuthCmdFactory().isErrorAddingReceived = false;
fixture.testerAgent.getAuthCmdFactory().responseReasonStr = null;
fixture.testerAgent.getAuthCmdFactory().isRequestAccepted = false;
// add us to his list again
fixture.testerAgent.addBuddy(fixture.ourAccountID);
// wait agent to receive error and to request us for our authorization
authEventCollector.waitForAuthRequest(25000);
// check have we received authorization request?
assertTrue("Error adding buddy not recieved or the buddy(" +
fixture.ourAccountID +
") doesn't require authorization",
fixture.testerAgent.getAuthCmdFactory().isErrorAddingReceived);
assertTrue("We haven't received any authorization request ",
authEventCollector.isAuthorizationRequestReceived);
assertNotNull("We haven't received any reason for authorization",
authEventCollector.authorizationRequestReason);
assertEquals("Error sent request reason is not as the received one",
fixture.testerAgent.getAuthCmdFactory().requestReasonStr,
authEventCollector.authorizationRequestReason
);
// wait agent to receive our response
synchronized(lock){
try{
lock.wait(5000);
}
catch (Exception ex){}
}
// check is correct the received response from the agent
assertNotNull("Agent haven't received any reason from authorization reply",
authEventCollector.authorizationRequestReason);
assertEquals("Received auth response from agent is not as the sent one",
fixture.testerAgent.getAuthCmdFactory().responseReasonStr,
secondRequestResponse);
isAcceptedAuthReuest =
authEventCollector.responseToRequest.getResponseCode().equals(AuthorizationResponse.ACCEPT);
assertEquals("Agent received Response is not as the sent one",
fixture.testerAgent.getAuthCmdFactory().isRequestAccepted,
isAcceptedAuthReuest);
}
}

Loading…
Cancel
Save