asterisk-java-cvs Mailing List for Asterisk-Java Library (Page 95)
Brought to you by:
srt
You can subscribe to this list here.
2005 |
Jan
(4) |
Feb
(75) |
Mar
(211) |
Apr
(70) |
May
(12) |
Jun
(7) |
Jul
(96) |
Aug
(90) |
Sep
(11) |
Oct
(42) |
Nov
(45) |
Dec
(4) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(20) |
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(32) |
Aug
|
Sep
(4) |
Oct
(2) |
Nov
(10) |
Dec
|
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(4) |
Jul
(3) |
Aug
(73) |
Sep
(13) |
Oct
(4) |
Nov
(1) |
Dec
(7) |
2009 |
Jan
(1) |
Feb
(2) |
Mar
(48) |
Apr
(21) |
May
(14) |
Jun
(11) |
Jul
(9) |
Aug
(2) |
Sep
(11) |
Oct
(14) |
Nov
(6) |
Dec
(4) |
2010 |
Jan
(3) |
Feb
(2) |
Mar
|
Apr
|
May
(3) |
Jun
(3) |
Jul
|
Aug
|
Sep
|
Oct
(9) |
Nov
|
Dec
(12) |
2011 |
Jan
(1) |
Feb
(5) |
Mar
(7) |
Apr
(1) |
May
(1) |
Jun
|
Jul
|
Aug
(10) |
Sep
|
Oct
(5) |
Nov
|
Dec
|
2012 |
Jan
(3) |
Feb
|
Mar
(3) |
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
(3) |
Oct
|
Nov
(2) |
Dec
(2) |
2013 |
Jan
|
Feb
(2) |
Mar
(1) |
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
(3) |
Sep
|
Oct
(2) |
Nov
|
Dec
(1) |
2014 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
(1) |
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
(5) |
2015 |
Jan
(1) |
Feb
|
Mar
|
Apr
(25) |
May
(10) |
Jun
(4) |
Jul
(7) |
Aug
(4) |
Sep
(1) |
Oct
(1) |
Nov
(3) |
Dec
(1) |
2016 |
Jan
|
Feb
(42) |
Mar
(6) |
Apr
(15) |
May
(3) |
Jun
(1) |
Jul
(11) |
Aug
|
Sep
|
Oct
(17) |
Nov
(2) |
Dec
|
2017 |
Jan
|
Feb
(4) |
Mar
(1) |
Apr
(3) |
May
(2) |
Jun
(3) |
Jul
(7) |
Aug
(11) |
Sep
(5) |
Oct
(7) |
Nov
(4) |
Dec
(4) |
2018 |
Jan
(11) |
Feb
(11) |
Mar
(3) |
Apr
|
May
(9) |
Jun
(6) |
Jul
(17) |
Aug
(9) |
Sep
(2) |
Oct
(4) |
Nov
(3) |
Dec
(3) |
2019 |
Jan
(13) |
Feb
(1) |
Mar
(1) |
Apr
|
May
(5) |
Jun
|
Jul
(1) |
Aug
(6) |
Sep
|
Oct
|
Nov
(3) |
Dec
|
2020 |
Jan
(2) |
Feb
(72) |
Mar
(8) |
Apr
(11) |
May
(12) |
Jun
(3) |
Jul
(12) |
Aug
(3) |
Sep
(5) |
Oct
(4) |
Nov
|
Dec
(9) |
2021 |
Jan
|
Feb
(31) |
Mar
(6) |
Apr
(3) |
May
|
Jun
(2) |
Jul
|
Aug
(2) |
Sep
|
Oct
(9) |
Nov
|
Dec
(32) |
2022 |
Jan
(5) |
Feb
(7) |
Mar
(2) |
Apr
(3) |
May
|
Jun
|
Jul
(3) |
Aug
|
Sep
(2) |
Oct
(111) |
Nov
(105) |
Dec
(26) |
2023 |
Jan
(25) |
Feb
(6) |
Mar
(10) |
Apr
(54) |
May
(41) |
Jun
(24) |
Jul
(6) |
Aug
(11) |
Sep
(9) |
Oct
(8) |
Nov
(55) |
Dec
(34) |
2024 |
Jan
(6) |
Feb
(4) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(2) |
Aug
(89) |
Sep
(48) |
Oct
(31) |
Nov
(9) |
Dec
(19) |
2025 |
Jan
(12) |
Feb
(18) |
Mar
(9) |
Apr
(7) |
May
|
Jun
(7) |
Jul
(7) |
Aug
(3) |
Sep
(22) |
Oct
(2) |
Nov
|
Dec
|
From: Stefan R. <sr...@us...> - 2005-03-05 00:14:41
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4089/src/java/net/sf/asterisk/manager Modified Files: DefaultManagerConnection.java Log Message: Added more unit tests for DefaultManagerConnection Index: DefaultManagerConnection.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/DefaultManagerConnection.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -d -p -r1.5 -r1.6 --- DefaultManagerConnection.java 4 Mar 2005 22:21:04 -0000 1.5 +++ DefaultManagerConnection.java 5 Mar 2005 00:14:32 -0000 1.6 @@ -59,8 +59,8 @@ public class DefaultManagerConnection im /* Config attributes */ private AsteriskServer asteriskServer; - private String username; - private String password; + protected String username; + protected String password; private long defaultTimeout = 2000; private long sleepTime = 50; private boolean keepAliveAfterAuthenticationFailure = false; @@ -81,7 +81,7 @@ public class DefaultManagerConnection im private String protocolIdentifier; private final Map responseHandlers; private final Collection eventHandlers; - private boolean keepAlive = false; + protected boolean keepAlive = false; public DefaultManagerConnection() { @@ -273,8 +273,14 @@ public class DefaultManagerConnection im try { MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(challenge.getBytes()); - md.update(password.getBytes()); + if (challenge != null) + { + md.update(challenge.getBytes()); + } + if (password != null) + { + md.update(password.getBytes()); + } loginAction.setKey(Util.toHexString(md.digest())); } catch (NoSuchAlgorithmException ex) @@ -305,7 +311,7 @@ public class DefaultManagerConnection im { this.reader = createReader(this, asteriskServer); } - + if (this.writer == null) { this.writer = createWriter(); @@ -583,16 +589,13 @@ public class DefaultManagerConnection im ManagerEventHandler eventHandler; eventHandler = (ManagerEventHandler) i.next(); - if (eventHandler != null) + try { - try - { - eventHandler.handleEvent(event); - } - catch (Exception e) - { - logger.warn("Exception calling eventHandler", e); - } + eventHandler.handleEvent(event); + } + catch (Exception e) + { + logger.warn("Exception calling eventHandler", e); } } } @@ -685,7 +688,7 @@ public class DefaultManagerConnection im } else { - logger.error("Unable to log in after reconnect. Giving up.", e1); + logger.error("Unable to log in after reconnect. Giving up."); this.keepAlive = false; } } |
From: Stefan R. <sr...@us...> - 2005-03-05 00:14:41
|
Update of /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4089/src/test/net/sf/asterisk/manager Modified Files: ManagerWriterMock.java DefaultManagerConnectionTest.java Log Message: Added more unit tests for DefaultManagerConnection Index: ManagerWriterMock.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager/ManagerWriterMock.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -p -r1.1 -r1.2 --- ManagerWriterMock.java 4 Mar 2005 22:21:04 -0000 1.1 +++ ManagerWriterMock.java 5 Mar 2005 00:14:32 -0000 1.2 @@ -20,10 +20,12 @@ import java.io.IOException; import net.sf.asterisk.manager.action.ChallengeAction; import net.sf.asterisk.manager.action.LoginAction; +import net.sf.asterisk.manager.action.LogoffAction; import net.sf.asterisk.manager.action.ManagerAction; import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.ChallengeResponse; +import net.sf.asterisk.manager.response.ManagerError; import net.sf.asterisk.manager.response.ManagerResponse; public class ManagerWriterMock implements ManagerWriter @@ -36,9 +38,12 @@ public class ManagerWriterMock implement private String expectedKey; private String expectedUsername; + private boolean sendResponse = true; + private boolean sendConnectEvent = true; public int challengeActionsSent = 0; public int loginActionsSent = 0; + public int logoffActionsSent = 0; public int otherActionsSent = 0; public ManagerWriterMock() @@ -59,27 +64,39 @@ public class ManagerWriterMock implement { this.expectedKey = key; } - + public void setExpectedUsername(String username) { this.expectedUsername = username; } + public void setSendResponse(boolean sendResponse) + { + this.sendResponse = sendResponse; + } + + public void setSendConnectEvent(boolean sendConnectEvent) + { + this.sendConnectEvent = sendConnectEvent; + } + public void setSocket(SocketConnectionFacade socket) { this.socket = socket; - ConnectEvent connectEvent; - connectEvent = new ConnectEvent(asteriskServer); - connectEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); - dispatcher.dispatchEvent(connectEvent); + if (sendConnectEvent) + { + ConnectEvent connectEvent; + connectEvent = new ConnectEvent(asteriskServer); + connectEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); + dispatcher.dispatchEvent(connectEvent); + } } public void sendAction(ManagerAction action) throws IOException { if (action instanceof ChallengeAction) { - ChallengeResponse challengeResponse; ChallengeAction challengeAction = (ChallengeAction) action; String authType = challengeAction.getAuthType(); @@ -88,51 +105,83 @@ public class ManagerWriterMock implement throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } - challengeResponse = new ChallengeResponse(); - challengeResponse.setActionId(action.getActionId()); - challengeResponse.setChallenge(CHALLENGE); - dispatcher.dispatchResponse(challengeResponse); - challengeActionsSent++; + + if (sendResponse) + { + ChallengeResponse challengeResponse; + + challengeResponse = new ChallengeResponse(); + challengeResponse.setActionId(action.getActionId()); + challengeResponse.setChallenge(CHALLENGE); + dispatcher.dispatchResponse(challengeResponse); + } } else if (action instanceof LoginAction) { - ManagerResponse loginResponse; + LoginAction loginAction = (LoginAction) action; String username = loginAction.getUsername(); String key = loginAction.getKey(); String authType = loginAction.getAuthType(); - if (!authType.equals("MD5")) + if (!"MD5".equals(authType)) { throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } - if (!username.equals(expectedUsername)) + if (!expectedUsername.equals(username)) { throw new RuntimeException("Expected username '" + expectedUsername + "' got '" + username + "'"); } - if (!key.equals(expectedKey)) + + loginActionsSent++; + + if (sendResponse) { - throw new RuntimeException("Expected key '" + expectedKey + "' got '" + key + "'"); + ManagerResponse loginResponse; + + if (key.equals(expectedKey)) + { + loginResponse = new ManagerResponse(); + loginResponse.setResponse("Success"); + } + else + { + loginResponse = new ManagerError(); + loginResponse.setResponse("Error"); + loginResponse.setMessage("Authentication failed"); + } + loginResponse.setActionId(action.getActionId()); + dispatcher.dispatchResponse(loginResponse); } + } + else if (action instanceof LogoffAction) + { + logoffActionsSent++; - loginResponse = new ManagerResponse(); - loginResponse.setActionId(action.getActionId()); - loginResponse.setResponse("Success"); - dispatcher.dispatchResponse(loginResponse); + if (sendResponse) + { + ManagerResponse response; - loginActionsSent++; + response = new ManagerResponse(); + response.setActionId(action.getActionId()); + response.setResponse("Success"); + dispatcher.dispatchResponse(response); + } } else { - ManagerResponse response; - - response = new ManagerResponse(); - response.setActionId(action.getActionId()); - response.setResponse("Success"); - dispatcher.dispatchResponse(response); - otherActionsSent++; + + if (sendResponse) + { + ManagerResponse response; + + response = new ManagerResponse(); + response.setActionId(action.getActionId()); + response.setResponse("Success"); + dispatcher.dispatchResponse(response); + } } } } Index: DefaultManagerConnectionTest.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager/DefaultManagerConnectionTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -p -r1.1 -r1.2 --- DefaultManagerConnectionTest.java 4 Mar 2005 22:21:04 -0000 1.1 +++ DefaultManagerConnectionTest.java 5 Mar 2005 00:14:32 -0000 1.2 @@ -16,9 +16,12 @@ */ package net.sf.asterisk.manager; +import java.io.IOException; + import junit.framework.TestCase; import net.sf.asterisk.manager.action.StatusAction; import net.sf.asterisk.manager.event.ConnectEvent; +import net.sf.asterisk.manager.event.DisconnectEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.ManagerResponse; @@ -38,22 +41,40 @@ public class DefaultManagerConnectionTes asteriskServer = new AsteriskServer("localhost", 5038); mockWriter = new ManagerWriterMock(); + mockWriter.setExpectedUsername("username"); + // md5 sum of 12345password + mockWriter.setExpectedKey("40b1b887502902a8ce61a16e44630f7c"); + mockReader = new ManagerReaderMock(); socketMC = MockControl.createControl(SocketConnectionFacade.class); mockSocket = (SocketConnectionFacade) socketMC.getMock(); dmc = new MockedDefaultManagerConnection(mockReader, mockWriter, mockSocket); + + // make tests faster that expect a TimeoutException + dmc.setDefaultTimeout(10); + mockWriter.setDispatcher(dmc); mockWriter.setAsteriskServer(asteriskServer); } - public void testConstructor() + public void testDefaultConstructor() { assertEquals("Invalid default hostname", "localhost", dmc.getAsteriskServer().getHostname()); assertEquals("Invalid default port", 5038, dmc.getAsteriskServer().getPort()); } + public void testFullConstructor() + { + dmc = new MockedDefaultManagerConnection("host", 1234, "u", "p"); + + assertEquals("Invalid hostname", "host", dmc.getAsteriskServer().getHostname()); + assertEquals("Invalid port", 1234, dmc.getAsteriskServer().getPort()); + assertEquals("Invalid username", "u", dmc.getUsername()); + assertEquals("Invalid password", "p", dmc.getPassword()); + } + public void testLogin() throws Exception { MockControl managerEventHandlerMC; @@ -70,14 +91,51 @@ public class DefaultManagerConnectionTes socketMC.replay(); + dmc.setUsername("username"); + dmc.setPassword("password"); + dmc.addEventHandler(managerEventHandler); + dmc.login(); + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); + assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + // assertEquals("run() not called 1 time", 1, mockReader.runCalls); + assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + + assertTrue("keepAlive not set", dmc.getKeepAlive()); + + socketMC.verify(); + managerEventHandlerMC.verify(); + } + + public void testLoginIncorrectKey() throws Exception + { + ConnectEvent connectEvent; + + mockSocket.close(); + socketMC.replay(); + mockWriter.setExpectedUsername("username"); // md5 sum of 12345password mockWriter.setExpectedKey("40b1b887502902a8ce61a16e44630f7c"); dmc.setUsername("username"); - dmc.setPassword("password"); - dmc.addEventHandler(managerEventHandler); - dmc.login(); + dmc.setPassword("wrong password"); + + try + { + dmc.login(); + fail("No AuthenticationFailedException thrown"); + } + catch (AuthenticationFailedException e) + { + } assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); @@ -88,11 +146,143 @@ public class DefaultManagerConnectionTes assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + // TODO why is run() not called? + // assertEquals("run() not called 1 time", 1, mockReader.runCalls); + assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + + socketMC.verify(); + } + + public void testLoginIOExceptionOnConnect() throws Exception + { + socketMC.replay(); + + dmc.setThrowIOExceptionOnFirstSocketCreate(true); + try + { + dmc.login(); + fail("No IOException thrown"); + } + catch (IOException e) + { + } + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("unexpected challenge action sent", 0, mockWriter.challengeActionsSent); + assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertEquals("unexpected call to setSocket()", 0, mockReader.setSocketCalls); + assertEquals("unexpected call to run()", 0, mockReader.runCalls); + assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + + socketMC.verify(); + } + + public void testLoginTimeoutOnConnect() throws Exception + { + mockSocket.close(); + socketMC.replay(); + + // provoke timeout + mockWriter.setSendConnectEvent(false); + + try + { + dmc.login(); + fail("No TimeoutException on login()"); + } + catch (TimeoutException e) + { + assertEquals("Timeout waiting for protocol identifier", e.getMessage()); + } + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("unexpected challenge action sent", 0, mockWriter.challengeActionsSent); + assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + assertEquals("run() not called 1 time", 1, mockReader.runCalls); + assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + + socketMC.verify(); + } + + public void testLoginTimeoutOnChallengeAction() throws Exception + { + socketMC.replay(); + + // provoke timeout + mockWriter.setSendResponse(false); + + try + { + dmc.login(); + fail("No TimeoutException on login()"); + } + catch (TimeoutException e) + { + assertEquals("Timeout waiting for response to Challenge", e.getMessage()); + } + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); + assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); assertEquals("run() not called 1 time", 1, mockReader.runCalls); assertEquals("unexpected call to die()", 0, mockReader.dieCalls); socketMC.verify(); - managerEventHandlerMC.verify(); + } + + public void testLogoffWhenConnected() throws Exception + { + mockSocket.close(); + socketMC.replay(); + + // fake connect + dmc.connect(); + + dmc.logoff(); + + assertEquals("logoff action not sent 1 time", 1, mockWriter.logoffActionsSent); + socketMC.verify(); + } + + public void testLogoffWhenNotConnected() throws Exception + { + socketMC.replay(); + + dmc.logoff(); + + assertEquals("unexpected logoff action sent", 0, mockWriter.logoffActionsSent); + socketMC.verify(); + } + + public void testSendActionWithNullAction() throws Exception + { + // fake connect + dmc.connect(); + try + { + dmc.sendAction(null); + fail("No IllgealArgumentException thrown"); + } + catch (IllegalArgumentException e) + { + } } public void testSendActionWhenNotConnected() throws Exception @@ -129,12 +319,166 @@ public class DefaultManagerConnectionTes assertEquals("other actions not sent 1 time", 1, mockWriter.otherActionsSent); } + public void testSendActionTimeout() throws Exception + { + StatusAction statusAction; + + statusAction = new StatusAction(); + statusAction.setActionId("123"); + + // fake connect + dmc.connect(); + // provoke timeout + mockWriter.setSendResponse(false); + try + { + dmc.sendAction(statusAction); + fail("No TimeoutException thrown"); + } + catch (TimeoutException e) + { + } + + assertEquals("other actions not sent 1 time", 1, mockWriter.otherActionsSent); + } + + public void testDispatchResponseUnexpectedResponse() + { + ManagerResponse response; + + response = new ManagerResponse(); + // internalActionId: 123_0 + response.setActionId("123_0-abc"); + response.setResponse("Success"); + + // expected result is ignoring the response and logging + dmc.dispatchResponse(response); + } + + public void testDispatchResponseMissingInternalActionId() + { + ManagerResponse response; + + response = new ManagerResponse(); + response.setActionId("abc"); + response.setResponse("Success"); + + // expected result is ignoring the response and logging + dmc.dispatchResponse(response); + } + + public void testDispatchResponseNullActionId() + { + ManagerResponse response; + + response = new ManagerResponse(); + response.setActionId(null); + response.setResponse("Success"); + + // expected result is ignoring the response and logging + dmc.dispatchResponse(response); + } + + public void testDispatchResponseNullResponse() + { + // expected result is ignoring and logging + dmc.dispatchResponse(null); + } + + public void testReconnect() throws Exception + { + DisconnectEvent disconnectEvent; + + socketMC.replay(); + disconnectEvent = new DisconnectEvent(asteriskServer); + + // fake successful login + dmc.setKeepAlive(true); + + dmc.setUsername("username"); + dmc.setPassword("password"); + + dmc.dispatchEvent(disconnectEvent); + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); + assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertTrue("keepAlive not enabled", dmc.getKeepAlive()); + + socketMC.verify(); + } + + public void testReconnectWithIOException() throws Exception + { + DisconnectEvent disconnectEvent; + + socketMC.replay(); + disconnectEvent = new DisconnectEvent(asteriskServer); + + // fake successful login + dmc.setKeepAlive(true); + + dmc.setThrowIOExceptionOnFirstSocketCreate(true); + + dmc.setUsername("username"); + dmc.setPassword("password"); + + dmc.dispatchEvent(disconnectEvent); + + assertEquals("createSocket not called 1 time", 2, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); + assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertTrue("keepAlive not enabled", dmc.getKeepAlive()); + + socketMC.verify(); + } + + public void testReconnectWithAuthenticationFailure() throws Exception + { + DisconnectEvent disconnectEvent; + + mockSocket.close(); + socketMC.replay(); + disconnectEvent = new DisconnectEvent(asteriskServer); + + // fake successful login + dmc.setKeepAlive(true); + + dmc.setUsername("username"); + + dmc.dispatchEvent(disconnectEvent); + + assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); + assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); + assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); + + assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); + assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); + assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + + assertFalse("keepAlive not disabled", dmc.getKeepAlive()); + + socketMC.verify(); + } + private class MockedDefaultManagerConnection extends DefaultManagerConnection { ManagerReader mockReader; ManagerWriter mockWriter; SocketConnectionFacade mockSocket; + private boolean throwIOExceptionOnFirstSocketCreate = false; + public int createReaderCalls = 0; public int createWriterCalls = 0; public int createSocketCalls = 0; @@ -148,6 +492,36 @@ public class DefaultManagerConnectionTes this.mockSocket = mockSocket; } + public MockedDefaultManagerConnection(String hostname, int port, String username, String password) + { + super(hostname, port, username, password); + } + + public void setThrowIOExceptionOnFirstSocketCreate(boolean throwIOExceptionOnSocketCreate) + { + this.throwIOExceptionOnFirstSocketCreate = throwIOExceptionOnSocketCreate; + } + + public String getUsername() + { + return username; + } + + public String getPassword() + { + return password; + } + + public void setKeepAlive(boolean keepAlive) + { + this.keepAlive = keepAlive; + } + + public boolean getKeepAlive() + { + return keepAlive; + } + protected ManagerReader createReader(Dispatcher d, AsteriskServer s) { createReaderCalls++; @@ -160,9 +534,14 @@ public class DefaultManagerConnectionTes return mockWriter; } - protected SocketConnectionFacade createSocket() + protected SocketConnectionFacade createSocket() throws IOException { createSocketCalls++; + + if (throwIOExceptionOnFirstSocketCreate && createSocketCalls == 1) + { + throw new IOException(); + } return mockSocket; } } |
From: Stefan R. <sr...@us...> - 2005-03-04 22:21:16
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3989/src/java/net/sf/asterisk/manager Modified Files: AsteriskServer.java DefaultManagerConnection.java Log Message: Added unit tests for DefaultManagerConnection Index: AsteriskServer.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/AsteriskServer.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -d -p -r1.3 -r1.4 --- AsteriskServer.java 23 Feb 2005 22:50:57 -0000 1.3 +++ AsteriskServer.java 4 Mar 2005 22:21:04 -0000 1.4 @@ -99,4 +99,40 @@ public class AsteriskServer implements S { this.port = port; } + + public boolean equals(Object o) + { + if (o == null || !(o instanceof AsteriskServer)) + { + return false; + } + + AsteriskServer s = (AsteriskServer) o; + if (this.getHostname() != null) + { + if (!this.getHostname().equals(s.getHostname())) + { + return false; + } + } + else + { + if (s.getHostname() != null) + { + return false; + } + } + + if (this.getPort() != s.getPort()) + { + return false; + } + + return true; + } + + public String toString() + { + return "AsteriskServer[hostname='" + hostname + "',port=" + port + "]"; + } } Index: DefaultManagerConnection.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/DefaultManagerConnection.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -d -p -r1.4 -r1.5 --- DefaultManagerConnection.java 2 Mar 2005 23:15:49 -0000 1.4 +++ DefaultManagerConnection.java 4 Mar 2005 22:21:04 -0000 1.5 @@ -71,12 +71,12 @@ public class DefaultManagerConnection im /** * The reader to use to receive events and responses from asterisk. */ - private final ManagerReader reader; + private ManagerReader reader; /** * The writer to use to send actions to asterisk. */ - private final ManagerWriter writer; + private ManagerWriter writer; private String protocolIdentifier; private final Map responseHandlers; @@ -87,8 +87,6 @@ public class DefaultManagerConnection im { this.asteriskServer = new AsteriskServer(); - this.reader = new ManagerReaderImpl(this, asteriskServer); - this.writer = new ManagerWriterImpl(); this.responseHandlers = new HashMap(); this.eventHandlers = new HashSet(); } @@ -103,6 +101,16 @@ public class DefaultManagerConnection im setPassword(password); } + protected ManagerReader createReader(Dispatcher dispatcher, AsteriskServer server) + { + return new ManagerReaderImpl(dispatcher, server); + } + + protected ManagerWriter createWriter() + { + return new ManagerWriterImpl(); + } + /** * Sets the hostname of the asterisk server to connect to.<br> * Default is <code>localhost</code>. @@ -289,10 +297,20 @@ public class DefaultManagerConnection im logger.info("Successfully logged in"); } - private synchronized void connect() throws IOException + protected synchronized void connect() throws IOException { logger.info("Connecting to " + asteriskServer.getHostname() + " port " + asteriskServer.getPort()); + if (this.reader == null) + { + this.reader = createReader(this, asteriskServer); + } + + if (this.writer == null) + { + this.writer = createWriter(); + } + this.socket = createSocket(); this.reader.setSocket(socket); @@ -512,6 +530,10 @@ public class DefaultManagerConnection im { this.responseHandlers.remove(internalActionId); } + else + { + logger.warn("No response handler registered for internalActionId '" + internalActionId + "'"); + } } } else @@ -574,27 +596,24 @@ public class DefaultManagerConnection im } } } - + if (event instanceof ConnectEvent) { setProtocolIdentifier(((ConnectEvent) event).getProtocolIdentifier()); } if (event instanceof DisconnectEvent) { - handleDisconnection(); + reconnect(); } } /** - * This method is called by the reader when the asterisk server receives the protocol - * identifier, i.e. a string like "Asterisk Call Manager/1.0". Having received a correct - * protocol identifier is the precodition for logging in. - * - * @param protocolIdentifier the protocol version received by the reader + * This method is called when a {@link ConnectEvent} is received from the reader. Having + * received a correct protocol identifier is the precodition for logging in. * - * @see ManagerReaderImpl + * @param protocolIdentifier the protocol version used by the asterisk server. */ - void setProtocolIdentifier(String protocolIdentifier) + private void setProtocolIdentifier(final String protocolIdentifier) { logger.info("Connected via " + protocolIdentifier); @@ -609,13 +628,14 @@ public class DefaultManagerConnection im } /** - * This method is called by the reader if the connection to the asterisk server is lost. While - * keepAlive is <code>true</code> we will try to reconnect. Reconnection attempts will be - * stopped when the {@link #logoff()} method is called or when the login after a successful + * Reconnects to the asterisk server when the connection is lost.<br> + * While keepAlive is <code>true</code> we will try to reconnect. Reconnection attempts will + * be stopped when the {@link #logoff()} method is called or when the login after a successful * reconnect results in an {@link AuthenticationFailedException} suggesting that the manager - * credentials have changed and keepAliveAfterAuthenticationFailure is not set. + * credentials have changed and keepAliveAfterAuthenticationFailure is not set.<br> + * This method is called when a {@link DisconnectEvent} is received from the reader. */ - void handleDisconnection() + private void reconnect() { int numTries; |
Update of /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3989/src/test/net/sf/asterisk/manager Modified Files: ManagerReaderImplTest.java Added Files: ManagerWriterMock.java ManagerReaderMock.java DefaultManagerConnectionTest.java Log Message: Added unit tests for DefaultManagerConnection --- NEW FILE: ManagerWriterMock.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import java.io.IOException; import net.sf.asterisk.manager.action.ChallengeAction; import net.sf.asterisk.manager.action.LoginAction; import net.sf.asterisk.manager.action.ManagerAction; import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.ChallengeResponse; import net.sf.asterisk.manager.response.ManagerResponse; public class ManagerWriterMock implements ManagerWriter { private static final String CHALLENGE = "12345"; private Dispatcher dispatcher; private AsteriskServer asteriskServer; private SocketConnectionFacade socket; private String expectedKey; private String expectedUsername; public int challengeActionsSent = 0; public int loginActionsSent = 0; public int otherActionsSent = 0; public ManagerWriterMock() { } public void setDispatcher(Dispatcher dispatcher) { this.dispatcher = dispatcher; } public void setAsteriskServer(AsteriskServer asteriskServer) { this.asteriskServer = asteriskServer; } public void setExpectedKey(String key) { this.expectedKey = key; } public void setExpectedUsername(String username) { this.expectedUsername = username; } public void setSocket(SocketConnectionFacade socket) { this.socket = socket; ConnectEvent connectEvent; connectEvent = new ConnectEvent(asteriskServer); connectEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); dispatcher.dispatchEvent(connectEvent); } public void sendAction(ManagerAction action) throws IOException { if (action instanceof ChallengeAction) { ChallengeResponse challengeResponse; ChallengeAction challengeAction = (ChallengeAction) action; String authType = challengeAction.getAuthType(); if (!authType.equals("MD5")) { throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } challengeResponse = new ChallengeResponse(); challengeResponse.setActionId(action.getActionId()); challengeResponse.setChallenge(CHALLENGE); dispatcher.dispatchResponse(challengeResponse); challengeActionsSent++; } else if (action instanceof LoginAction) { ManagerResponse loginResponse; LoginAction loginAction = (LoginAction) action; String username = loginAction.getUsername(); String key = loginAction.getKey(); String authType = loginAction.getAuthType(); if (!authType.equals("MD5")) { throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } if (!username.equals(expectedUsername)) { throw new RuntimeException("Expected username '" + expectedUsername + "' got '" + username + "'"); } if (!key.equals(expectedKey)) { throw new RuntimeException("Expected key '" + expectedKey + "' got '" + key + "'"); } loginResponse = new ManagerResponse(); loginResponse.setActionId(action.getActionId()); loginResponse.setResponse("Success"); dispatcher.dispatchResponse(loginResponse); loginActionsSent++; } else { ManagerResponse response; response = new ManagerResponse(); response.setActionId(action.getActionId()); response.setResponse("Success"); dispatcher.dispatchResponse(response); otherActionsSent++; } } } --- NEW FILE: ManagerReaderMock.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import net.sf.asterisk.manager.io.SocketConnectionFacade; public class ManagerReaderMock implements ManagerReader { public int setSocketCalls = 0; public int dieCalls = 0; public int runCalls = 0; public ManagerReaderMock() { } public void setSocket(SocketConnectionFacade socket) { setSocketCalls++; } public void die() { dieCalls++; } public void run() { runCalls++; } } --- NEW FILE: DefaultManagerConnectionTest.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import junit.framework.TestCase; import net.sf.asterisk.manager.action.StatusAction; import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.ManagerResponse; import org.easymock.MockControl; public class DefaultManagerConnectionTest extends TestCase { protected MockControl socketMC; protected SocketConnectionFacade mockSocket; protected ManagerWriterMock mockWriter; protected ManagerReaderMock mockReader; protected MockedDefaultManagerConnection dmc; protected AsteriskServer asteriskServer; protected void setUp() throws Exception { asteriskServer = new AsteriskServer("localhost", 5038); mockWriter = new ManagerWriterMock(); mockReader = new ManagerReaderMock(); socketMC = MockControl.createControl(SocketConnectionFacade.class); mockSocket = (SocketConnectionFacade) socketMC.getMock(); dmc = new MockedDefaultManagerConnection(mockReader, mockWriter, mockSocket); mockWriter.setDispatcher(dmc); mockWriter.setAsteriskServer(asteriskServer); } public void testConstructor() { assertEquals("Invalid default hostname", "localhost", dmc.getAsteriskServer().getHostname()); assertEquals("Invalid default port", 5038, dmc.getAsteriskServer().getPort()); } public void testLogin() throws Exception { MockControl managerEventHandlerMC; ManagerEventHandler managerEventHandler; ConnectEvent connectEvent; managerEventHandlerMC = MockControl.createControl(ManagerEventHandler.class); managerEventHandler = (ManagerEventHandler) managerEventHandlerMC.getMock(); connectEvent = new ConnectEvent(asteriskServer); connectEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); managerEventHandler.handleEvent(connectEvent); managerEventHandlerMC.replay(); socketMC.replay(); mockWriter.setExpectedUsername("username"); // md5 sum of 12345password mockWriter.setExpectedKey("40b1b887502902a8ce61a16e44630f7c"); dmc.setUsername("username"); dmc.setPassword("password"); dmc.addEventHandler(managerEventHandler); dmc.login(); assertEquals("createSocket not called 1 time", 1, dmc.createSocketCalls); assertEquals("createWriter not called 1 time", 1, dmc.createWriterCalls); assertEquals("createReader not called 1 time", 1, dmc.createReaderCalls); assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); assertEquals("run() not called 1 time", 1, mockReader.runCalls); assertEquals("unexpected call to die()", 0, mockReader.dieCalls); socketMC.verify(); managerEventHandlerMC.verify(); } public void testSendActionWhenNotConnected() throws Exception { StatusAction statusAction; statusAction = new StatusAction(); try { dmc.sendAction(statusAction); fail("No IllegalStateException thrown"); } catch (IllegalStateException e) { } } public void testSendAction() throws Exception { StatusAction statusAction; ManagerResponse response; statusAction = new StatusAction(); statusAction.setActionId("123"); // fake connect dmc.connect(); response = dmc.sendAction(statusAction); assertEquals("incorrect actionId in response", "123", response.getActionId()); assertEquals("incorrect response", "Success", response.getResponse()); assertEquals("other actions not sent 1 time", 1, mockWriter.otherActionsSent); } private class MockedDefaultManagerConnection extends DefaultManagerConnection { ManagerReader mockReader; ManagerWriter mockWriter; SocketConnectionFacade mockSocket; public int createReaderCalls = 0; public int createWriterCalls = 0; public int createSocketCalls = 0; public MockedDefaultManagerConnection(ManagerReader mockReader, ManagerWriter mockWriter, SocketConnectionFacade mockSocket) { super(); this.mockReader = mockReader; this.mockWriter = mockWriter; this.mockSocket = mockSocket; } protected ManagerReader createReader(Dispatcher d, AsteriskServer s) { createReaderCalls++; return mockReader; } protected ManagerWriter createWriter() { createWriterCalls++; return mockWriter; } protected SocketConnectionFacade createSocket() { createSocketCalls++; return mockSocket; } } } Index: ManagerReaderImplTest.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager/ManagerReaderImplTest.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -p -r1.1 -r1.2 --- ManagerReaderImplTest.java 2 Mar 2005 23:15:50 -0000 1.1 +++ ManagerReaderImplTest.java 4 Mar 2005 22:21:04 -0000 1.2 @@ -42,7 +42,7 @@ public class ManagerReaderImplTest exten private AsteriskServer asteriskServer; private ManagerReader managerReader; - public void setUp() + protected void setUp() { now = new Date(); DateUtil.overrideCurrentDate(now); @@ -54,6 +54,11 @@ public class ManagerReaderImplTest exten socketConnectionFacadeMC = MockControl.createControl(SocketConnectionFacade.class); socketConnectionFacade = (SocketConnectionFacade) socketConnectionFacadeMC.getMock(); } + + protected void tearDown() + { + DateUtil.overrideCurrentDate(null); + } public void testRunWithoutSocket() throws Exception { |
From: Stefan R. <sr...@us...> - 2005-03-03 22:04:43
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30000/src/java/net/sf/asterisk/manager/event Modified Files: QueueMemberStatusEvent.java Log Message: Changed type of paused property to Boolean Index: QueueMemberStatusEvent.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event/QueueMemberStatusEvent.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -d -p -r1.2 -r1.3 --- QueueMemberStatusEvent.java 3 Mar 2005 19:05:30 -0000 1.2 +++ QueueMemberStatusEvent.java 3 Mar 2005 22:04:16 -0000 1.3 @@ -29,7 +29,8 @@ public class QueueMemberStatusEvent exte */ private static final long serialVersionUID = -2293926744791895763L; private String status; - private String paused; + private Boolean paused; + /** * @param source */ @@ -37,32 +38,36 @@ public class QueueMemberStatusEvent exte { super(source); } + /** * Returns the status. */ public String getStatus() { - return status; + return status; } + /** * Sets the status. */ public void setStatus(String status) { - this.status = status; + this.status = status; } + /** * Returns whether or not the call is paused. */ - public String getPaused() + public Boolean getPaused() { - return paused; + return paused; } + /** * Sets whether or not the call is paused. */ - public void setPaused(String paused) + public void setPaused(Boolean paused) { - this.paused = paused; + this.paused = paused; } } |
From: Jon H. <squ...@us...> - 2005-03-03 19:05:52
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11261 Modified Files: QueueMemberStatusEvent.java Log Message: add "paused" property Index: QueueMemberStatusEvent.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event/QueueMemberStatusEvent.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -p -r1.1 -r1.2 --- QueueMemberStatusEvent.java 2 Mar 2005 18:35:38 -0000 1.1 +++ QueueMemberStatusEvent.java 3 Mar 2005 19:05:30 -0000 1.2 @@ -28,7 +28,8 @@ public class QueueMemberStatusEvent exte * Serializable version identifier */ private static final long serialVersionUID = -2293926744791895763L; - private String status; + private String status; + private String paused; /** * @param source */ @@ -50,4 +51,18 @@ public class QueueMemberStatusEvent exte { this.status = status; } + /** + * Returns whether or not the call is paused. + */ + public String getPaused() + { + return paused; + } + /** + * Sets whether or not the call is paused. + */ + public void setPaused(String paused) + { + this.paused = paused; + } } |
From: Stefan R. <sr...@us...> - 2005-03-02 23:28:29
|
Update of /cvsroot/asterisk-java/asterisk-java In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv549 Modified Files: project.xml Log Message: Added John Index: project.xml =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/project.xml,v retrieving revision 1.7 retrieving revision 1.8 diff -u -d -p -r1.7 -r1.8 --- project.xml 2 Mar 2005 23:15:50 -0000 1.7 +++ project.xml 2 Mar 2005 23:28:17 -0000 1.8 @@ -93,6 +93,13 @@ <email>partoutatis at users.sourceforge.net</email> <timezone>+1</timezone> </developer> + <developer> + <name>John Hood</name> + <id>squinky86</id> + <email>john at asteriasgi.com</email> + <organization>Asteria Soulutions Group, Inc.</organization> + <timezone>-6</timezone> + </developer> </developers> <dependencies> <dependency> |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:04
|
Update of /cvsroot/asterisk-java/asterisk-java In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560 Modified Files: project.xml Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) Index: project.xml =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/project.xml,v retrieving revision 1.6 retrieving revision 1.7 diff -u -d -p -r1.6 -r1.7 --- project.xml 27 Feb 2005 23:49:36 -0000 1.6 +++ project.xml 2 Mar 2005 23:15:50 -0000 1.7 @@ -110,6 +110,13 @@ <type>jar</type> <url>http://jakarta.apache.org/commons/lang/</url> </dependency> + <dependency> + <groupId>easymock</groupId> + <artifactId>easymock</artifactId> + <version>1.1</version> + <type>jar</type> + <url>http://www.easymock.org/</url> + </dependency> </dependencies> <build> <nagEmailAddress>sr...@re...</nagEmailAddress> |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:03
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/util In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560/src/java/net/sf/asterisk/manager/util Added Files: DateUtil.java Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) --- NEW FILE: DateUtil.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager.util; import java.util.Date; /** * Utility class to obtain the current date and allows to override with a fixed value for testing. * * @author srt * @version $Id: DateUtil.java,v 1.1 2005/03/02 23:15:51 srt Exp $ */ public class DateUtil { private static Date currentDate; private DateUtil() { } /** * If set to a non null value uses the date given as current date on calls to getDate(). Set to * null to restore the normal behavior. * * @param currentDate the date to return on calls to getDate() or <code>null</code> to return * the real current date. */ public static void overrideCurrentDate(Date currentDate) { DateUtil.currentDate = currentDate; } /** * Returns the real current date or the date set with overrideCurrentDate(). * * @return the real current date or the date set with overrideCurrentDate(). */ public static Date getDate() { if (currentDate != null) { return currentDate; } else { return new Date(); } } } |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:01
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560/src/java/net/sf/asterisk/manager Modified Files: ManagerReader.java DefaultManagerConnection.java Added Files: Dispatcher.java ManagerWriterImpl.java ManagerWriter.java ManagerReaderImpl.java Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) --- NEW FILE: Dispatcher.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import net.sf.asterisk.manager.event.ManagerEvent; import net.sf.asterisk.manager.response.ManagerResponse; public interface Dispatcher { /** * This method is called by the reader whenever a {@link ManagerResponse} is received. The * response is dispatched to the associated {@link ManagerResponseHandler}. * * @param response the resonse received by the reader * * @see ManagerReader */ void dispatchResponse(ManagerResponse response); /** * This method is called by the reader whenever a ManagerEvent is received. The event is * dispatched to all registered ManagerEventHandlers. * * @param event the event received by the reader * * @see ManagerReader */ void dispatchEvent(ManagerEvent event); } --- NEW FILE: ManagerWriterImpl.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import java.io.IOException; import net.sf.asterisk.manager.action.ManagerAction; import net.sf.asterisk.manager.io.SocketConnectionFacade; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Default implementation of ManagerWriter interface. * * @author srt * @version $Id: ManagerWriterImpl.java,v 1.1 2005/03/02 23:15:49 srt Exp $ */ class ManagerWriterImpl implements ManagerWriter { /** * Instance logger. */ private final Log logger = LogFactory.getLog(getClass()); /** * The action builder utility to convert ManagerAction to a String suitable to be sent to the * asterisk server. */ private final ActionBuilder actionBuilder; private SocketConnectionFacade socket; /** * Creates a new ManagerWriterImpl. */ ManagerWriterImpl() { this.actionBuilder = new ActionBuilder(); } public synchronized void setSocket(final SocketConnectionFacade socket) { this.socket = socket; } public synchronized void sendAction(final ManagerAction action) throws IOException { final String actionString; if (socket == null) { throw new IllegalStateException("Unable to send action: socket is null"); } actionString = actionBuilder.buildAction(action); socket.print(actionString); socket.flush(); logger.debug("Sent " + action.getAction() + " action with actionId '" + action.getActionId() + "':\n" + actionString); } } --- NEW FILE: ManagerWriter.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import java.io.IOException; import net.sf.asterisk.manager.action.ManagerAction; import net.sf.asterisk.manager.io.SocketConnectionFacade; /** * The ManagerWriter transforms actions using the ActionBuilder and sends them to the asterisk * server.<br> * This class is intended to be used only by the DefaultManagerConnection. * * @see net.sf.asterisk.manager.ActionBuilder * @see net.sf.asterisk.manager.DefaultManagerConnection * * @author srt * @version $Id: ManagerWriter.java,v 1.1 2005/03/02 23:15:49 srt Exp $ */ interface ManagerWriter { void setSocket(final SocketConnectionFacade socket); /** * Sends the given action to the asterisk server. * * @param action the action to send to the asterisk server. * @throws IOException if there is a problem sending the action. */ void sendAction(final ManagerAction action) throws IOException; } --- NEW FILE: ManagerReaderImpl.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.event.DisconnectEvent; import net.sf.asterisk.manager.event.ManagerEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.CommandResponse; import net.sf.asterisk.manager.response.ManagerResponse; import net.sf.asterisk.manager.util.DateUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Default implementation of the ManagerReader interface. * * @author srt * @version $Id: ManagerReaderImpl.java,v 1.1 2005/03/02 23:15:50 srt Exp $ */ class ManagerReaderImpl implements ManagerReader { /** * Instance logger. */ private final Log logger = LogFactory.getLog(getClass()); /** * The event builder utility to convert a map of attributes reveived from asterisk to instances * of registered event classes. */ private final EventBuilder eventBuilder; /** * The response builder utility to convert a map of attributes reveived from asterisk to * instances of well known response classes. */ private final ResponseBuilder responseBuilder; /** * The dispatcher to use for dispatching events and responses. */ private final Dispatcher dispatcher; /** * The asterisk server we are reading from. */ private final AsteriskServer asteriskServer; /** * The socket to use for reading from the asterisk server. */ private SocketConnectionFacade socket; /** * If set to <code>true</code>, terminates and closes the reader. */ private boolean die = false; /** * Creates a new ManagerReaderImpl. * @param dispatcher the dispatcher to use for dispatching events and responses. */ ManagerReaderImpl(final Dispatcher dispatcher, AsteriskServer asteriskServer) { this.dispatcher = dispatcher; this.asteriskServer = asteriskServer; this.eventBuilder = new EventBuilder(); this.responseBuilder = new ResponseBuilder(); } /** * Sets the socket to use for reading from the asterisk server. * @param socket the socket to use for reading from the asterisk server. */ public void setSocket(final SocketConnectionFacade socket) { this.socket = socket; } /** * Reads line by line from the asterisk server, sets the protocol identifier as soon as it is * received and dispatches the received events and responses via the associated dispatcher. * * @see DefaultManagerConnection#dispatchEvent(ManagerEvent) * @see DefaultManagerConnection#dispatchResponse(ManagerResponse) * @see DefaultManagerConnection#setProtocolIdentifier(String) */ public void run() { final Map buffer = new HashMap(); final List commandResult = new ArrayList(); String line; boolean processingCommandResult = false; if (socket == null) { throw new IllegalStateException("Unable to run: socket is null."); } this.die = false; try { while ((line = socket.readLine()) != null && !this.die) { // dirty hack for handling the CommandAction. Needs fix when manager protocol is // enhanced. if (processingCommandResult) { if ("--END COMMAND--".equals(line)) { CommandResponse commandResponse = new CommandResponse(); if (!commandResult.isEmpty() && ((String) commandResult.get(0)).startsWith("ActionID")) { String tmp = (String) commandResult.get(0); int delimiterIndex = tmp.indexOf(":"); if (delimiterIndex > 0 && tmp.length() > delimiterIndex + 2) { commandResult.remove(0); commandResponse.setActionId(tmp.substring(delimiterIndex + 2)); } } commandResponse.setResponse("Follows"); commandResponse.setDateReceived(DateUtil.getDate()); commandResponse.setResult(commandResult); dispatcher.dispatchResponse(commandResponse); processingCommandResult = false; } else { commandResult.add(line); } continue; } // Reponse: Follows indicates that the output starting on the next line until // --END COMMAND-- must be treated as raw output of a command executed by a // CommandAction. if ("Response: Follows".equalsIgnoreCase(line)) { processingCommandResult = true; commandResult.clear(); continue; } // maybe we will find a better way to identify the protocol identifier but for now // this works quite well. if (line.startsWith("Asterisk Call Manager/")) { ConnectEvent connectEvent = new ConnectEvent(asteriskServer); connectEvent.setProtocolIdentifier(line); connectEvent.setDateReceived(DateUtil.getDate()); dispatcher.dispatchEvent(connectEvent); continue; } // an empty line indicates a normal response's or event's end so we build // the corresponding value object and dispatch it through the ManagerConnection. if (line.length() == 0) { if (buffer.containsKey("response")) { ManagerResponse response = buildResponse(buffer); if (response != null) { dispatcher.dispatchResponse(response); } } else if (buffer.containsKey("event")) { ManagerEvent event = buildEvent(asteriskServer, buffer); if (event != null) { dispatcher.dispatchEvent(event); } } buffer.clear(); } else { int delimiterIndex; delimiterIndex = line.indexOf(":"); if (delimiterIndex > 0 && line.length() > delimiterIndex + 2) { String name; String value; name = line.substring(0, delimiterIndex).toLowerCase(); value = line.substring(delimiterIndex + 2); buffer.put(name, value); } } } logger.info("Reached end of stream, terminating reader."); } catch (IOException e) { logger.info("IOException while reading from asterisk server, terminating reader thread: " + e.getMessage()); } finally { // cleans resources and reconnects if needed DisconnectEvent disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(DateUtil.getDate()); dispatcher.dispatchEvent(disconnectEvent); } } public void die() { this.die = true; } private ManagerResponse buildResponse(Map buffer) { ManagerResponse response; response = responseBuilder.buildResponse(buffer); if (response != null) { response.setDateReceived(DateUtil.getDate()); } return response; } private ManagerEvent buildEvent(Object source, Map buffer) { ManagerEvent event; event = eventBuilder.buildEvent(source, buffer); if (event != null) { event.setDateReceived(DateUtil.getDate()); } return event; } } Index: ManagerReader.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/ManagerReader.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -d -p -r1.5 -r1.6 --- ManagerReader.java 2 Mar 2005 00:37:03 -0000 1.5 +++ ManagerReader.java 2 Mar 2005 23:15:38 -0000 1.6 @@ -16,231 +16,31 @@ */ package net.sf.asterisk.manager; -import java.io.BufferedReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.sf.asterisk.manager.event.ManagerEvent; -import net.sf.asterisk.manager.response.CommandResponse; -import net.sf.asterisk.manager.response.ManagerResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import net.sf.asterisk.manager.io.SocketConnectionFacade; /** - * The ManagerReader is a Thread that reads events and responses from an asterisk server, parses - * them to the corresponding ManagerEvent and ManagerResponse objects and dispatches them via the - * associated DefaultManagerConnection. <br> + * The ManagerReader reads events and responses from the asterisk server, parses them using + * EventBuilder and ResponseBuilder and dispatches them to the associated ManagerConnection.<br> * This class is intended to be used only by the DefaultManagerConnection. * - * @see net.sf.asterisk.manager.event.ManagerEvent - * @see net.sf.asterisk.manager.response.ManagerResponse + * @see net.sf.asterisk.manager.EventBuilder + * @see net.sf.asterisk.manager.ResponseBuilder * @see net.sf.asterisk.manager.DefaultManagerConnection * * @author srt * @version $Id$ */ -class ManagerReader extends Thread -{ - private Log log = LogFactory.getLog(getClass()); - - private static int threadCount = 0; - - /** - * The event builder utility to convert a map of attributes reveived from asterisk to instances - * of registered event classes. - */ - private EventBuilder eventBuilder; - - /** - * The response builder utility to convert a map of attributes reveived from asterisk to - * instances of well known response classes. - */ - private ResponseBuilder responseBuilder; - - /** - * If set to <code>true</code>, terminates and closes the reader. - */ - private boolean die = false; - private BufferedReader reader; - private DefaultManagerConnection connection; - - ManagerReader(DefaultManagerConnection connection, BufferedReader reader) - { - int i = threadCount++; - setName("ManagerReader-" + i); - - this.connection = connection; - this.reader = reader; - this.eventBuilder = new EventBuilder(); - this.responseBuilder = new ResponseBuilder(); - } +interface ManagerReader extends Runnable +{ /** - * Reads line by line from the asterisk server, sets the protocol identifier as soon as it is - * received and dispatches the received events and responses via the associated connection. + * Sets the socket to use for reading from the asterisk server. * - * @see DefaultManagerConnection#dispatchEvent(ManagerEvent) - * @see DefaultManagerConnection#dispatchResponse(ManagerResponse) - * @see DefaultManagerConnection#setProtocolIdentifier(String) + * @param socket the socket to use for reading from the asterisk server. */ - public void run() - { - String line; - List commandResult = new ArrayList(); - boolean processingCommandResult = false; - Map buffer = new HashMap(); - - try - { - while ((line = reader.readLine()) != null && !die) - { - // dirty hack for handling the CommandAction. Needs fix when manager protocol is - // enhanced. - if (processingCommandResult) - { - if ("--END COMMAND--".equals(line)) - { - CommandResponse commandResponse = new CommandResponse(); - - if (!commandResult.isEmpty() && ((String) commandResult.get(0)).startsWith("ActionID")) - { - String tmp = (String) commandResult.get(0); - int delimiterIndex = tmp.indexOf(":"); - if (delimiterIndex > 0 && tmp.length() > delimiterIndex + 2) - { - commandResult.remove(0); - commandResponse.setActionId(tmp.substring(delimiterIndex + 2)); - } - } - commandResponse.setResponse("Follows"); - commandResponse.setDateReceived(new Date()); - commandResponse.setResult(commandResult); - connection.dispatchResponse(commandResponse); - processingCommandResult = false; - } - else - { - commandResult.add(line); - } - continue; - } - - // Reponse: Follows indicates that the output starting on the next line until - // --END COMMAND-- must be treated as raw output of a command executed by a - // CommandAction. - if ("Response: Follows".equalsIgnoreCase(line)) - { - processingCommandResult = true; - commandResult.clear(); - continue; - } - - // maybe we will find a better way to identify the protocol identifier but for now - // this works quite well. - if (line.startsWith("Asterisk Call Manager/") && connection.getProtocolIdentifier() == null) - { - connection.setProtocolIdentifier(line); - continue; - } - - // an empty line indicates a normal response's or event's end so we build - // the corresponding value object and dispatch it through the ManagerConnection. - if (line.length() == 0) - { - if (buffer.containsKey("response")) - { - ManagerResponse response = buildResponse(buffer); - if (response != null) - { - connection.dispatchResponse(response); - } - } - else if (buffer.containsKey("event")) - { - ManagerEvent event = buildEvent(connection.getAsteriskServer(), buffer); - if (event != null) - { - connection.dispatchEvent(event); - } - } - - buffer.clear(); - } - else - { - int delimiterIndex; - - delimiterIndex = line.indexOf(":"); - if (delimiterIndex > 0 && line.length() > delimiterIndex + 2) - { - String name; - String value; - - name = line.substring(0, delimiterIndex).toLowerCase(); - value = line.substring(delimiterIndex + 2); - - buffer.put(name, value); - } - } - } - } - catch (IOException e) - { - log.warn("IOException while reading from asterisk server, terminating thread.", e); - } - finally - { - log.info("Disconnected, closing reader."); - try - { - reader.close(); - } - catch (IOException ex) - { - log.warn("Unable to close reader", ex); - } - - // cleans resources and reconnects if needed - connection.handleDisconnection(); - } - } - - public void die() - { - this.die = true; - } - - private ManagerResponse buildResponse(Map buffer) - { - ManagerResponse response; - - response = responseBuilder.buildResponse(buffer); - - if (response != null) - { - response.setDateReceived(new Date()); - } - - return response; - } - - private ManagerEvent buildEvent(Object source, Map buffer) - { - ManagerEvent event; - - event = eventBuilder.buildEvent(source, buffer); + void setSocket(final SocketConnectionFacade socket); - if (event != null) - { - event.setDateReceived(new Date()); - } + void die(); - return event; - } } Index: DefaultManagerConnection.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/DefaultManagerConnection.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -d -p -r1.3 -r1.4 --- DefaultManagerConnection.java 2 Mar 2005 00:37:38 -0000 1.3 +++ DefaultManagerConnection.java 2 Mar 2005 23:15:49 -0000 1.4 @@ -16,13 +16,8 @@ */ package net.sf.asterisk.manager; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; import java.io.Serializable; -import java.net.Socket; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; @@ -38,6 +33,8 @@ import net.sf.asterisk.manager.action.Ma import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.event.DisconnectEvent; import net.sf.asterisk.manager.event.ManagerEvent; +import net.sf.asterisk.manager.io.SocketConnectionFacade; +import net.sf.asterisk.manager.io.SocketConnectionFacadeImpl; import net.sf.asterisk.manager.response.ChallengeResponse; import net.sf.asterisk.manager.response.ManagerError; import net.sf.asterisk.manager.response.ManagerResponse; @@ -51,7 +48,7 @@ import org.apache.commons.logging.LogFac * @author srt * @version $Id$ */ -public class DefaultManagerConnection implements ManagerConnection +public class DefaultManagerConnection implements ManagerConnection, Dispatcher { /** * Instance logger. @@ -68,23 +65,40 @@ public class DefaultManagerConnection im private long sleepTime = 50; private boolean keepAliveAfterAuthenticationFailure = false; - private Socket socket; - private ManagerReader reader; - private PrintWriter writer; - private ActionBuilder actionBuilder = new ActionBuilder(); + private SocketConnectionFacade socket; + private Thread readerThread; + + /** + * The reader to use to receive events and responses from asterisk. + */ + private final ManagerReader reader; + + /** + * The writer to use to send actions to asterisk. + */ + private final ManagerWriter writer; + private String protocolIdentifier; - private Map responseHandlers = new HashMap(); - private Collection eventHandlers = new HashSet(); + private final Map responseHandlers; + private final Collection eventHandlers; private boolean keepAlive = false; public DefaultManagerConnection() { this.asteriskServer = new AsteriskServer(); + + this.reader = new ManagerReaderImpl(this, asteriskServer); + this.writer = new ManagerWriterImpl(); + this.responseHandlers = new HashMap(); + this.eventHandlers = new HashSet(); } public DefaultManagerConnection(String hostname, int port, String username, String password) { - this.asteriskServer = new AsteriskServer(hostname, port); + this(); + + setHostname(hostname); + setPort(port); setUsername(username); setPassword(password); } @@ -273,24 +287,24 @@ public class DefaultManagerConnection im this.keepAlive = true; logger.info("Successfully logged in"); - - // notify event listeners - dispatchEvent(new ConnectEvent(this.asteriskServer)); } private synchronized void connect() throws IOException { - BufferedReader bufferedReader; - logger.info("Connecting to " + asteriskServer.getHostname() + " port " + asteriskServer.getPort()); - this.socket = new Socket(asteriskServer.getHostname(), asteriskServer.getPort()); + this.socket = createSocket(); - bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + this.reader.setSocket(socket); + this.readerThread = new Thread(reader); + this.readerThread.start(); - this.reader = new ManagerReader(this, bufferedReader); - this.reader.start(); - this.writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); + this.writer.setSocket(socket); + } + + protected SocketConnectionFacade createSocket() throws IOException + { + return new SocketConnectionFacadeImpl(asteriskServer.getHostname(), asteriskServer.getPort()); } /** @@ -300,7 +314,7 @@ public class DefaultManagerConnection im * @return <code>true</code> if there is a socket connection to the asterisk server, * <code>false</code> otherwise. */ - protected synchronized boolean isConnected() + private synchronized boolean isConnected() { // return socket != null && socket.isConnected(); // JDK 1.4 return socket != null; @@ -317,7 +331,7 @@ public class DefaultManagerConnection im this.keepAlive = false; logoffAction = new LogoffAction(); - + if (isConnected()) { sendAction(logoffAction); @@ -327,23 +341,16 @@ public class DefaultManagerConnection im private synchronized void disconnect() { - if (this.writer != null) - { - logger.info("Closing writer"); - this.writer.close(); - this.writer = null; - } - if (this.socket != null) { - logger.info("Closing socket"); + logger.info("Closing socket."); try { this.socket.close(); } catch (IOException ex) { - logger.warn("Unable to close socket", ex); + logger.warn("Unable to close socket: " + ex.getMessage()); } this.socket = null; } @@ -389,12 +396,15 @@ public class DefaultManagerConnection im public void sendAction(ManagerAction action, ManagerResponseHandler callbackHandler) throws IOException { String internalActionId; - String actionString; if (action == null) { - logger.error("Unable to send null action"); - throw new IllegalArgumentException("Unable to send null action"); + throw new IllegalArgumentException("Unable to send action: action is null."); + } + + if (!isConnected()) + { + throw new IllegalStateException("Unable to send " + action.getAction() + " action: not connected."); } internalActionId = createInternalActionId(); @@ -416,21 +426,7 @@ public class DefaultManagerConnection im } } - actionString = actionBuilder.buildAction(action); - - synchronized (this) - { - if (!isConnected()) - { - throw new IllegalStateException("Unable to send " + action.getAction() + " action: not connected."); - } - - this.writer.print(actionString); - this.writer.flush(); - } - - logger.debug("Sent " + action.getAction() + " action with internalActionId '" + internalActionId + "':\n" - + actionString); + writer.sendAction(action); } /** @@ -439,7 +435,7 @@ public class DefaultManagerConnection im */ private String createInternalActionId() { - StringBuffer sb; + final StringBuffer sb; sb = new StringBuffer(); sb.append(this.hashCode()); @@ -449,7 +445,7 @@ public class DefaultManagerConnection im return sb.toString(); } - public void addEventHandler(ManagerEventHandler eventHandler) + public void addEventHandler(final ManagerEventHandler eventHandler) { synchronized (this.eventHandlers) { @@ -457,7 +453,7 @@ public class DefaultManagerConnection im } } - public void removeEventHandler(ManagerEventHandler eventHandler) + public void removeEventHandler(final ManagerEventHandler eventHandler) { synchronized (this.eventHandlers) { @@ -473,7 +469,7 @@ public class DefaultManagerConnection im return this.protocolIdentifier; } - /* Callbacks for ManagerReader */ + /* Callbacks for ManagerReaderImpl */ /** * This method is called by the reader whenever a {@link ManagerResponse} is received. The @@ -481,11 +477,11 @@ public class DefaultManagerConnection im * * @param response the resonse received by the reader * - * @see ManagerReader + * @see ManagerReaderImpl */ - void dispatchResponse(ManagerResponse response) + public void dispatchResponse(ManagerResponse response) { - String actionId; + final String actionId; String internalActionId; ManagerResponseHandler responseHandler; @@ -545,9 +541,9 @@ public class DefaultManagerConnection im * * @see #addEventHandler(ManagerEventHandler) * @see #removeEventHandler(ManagerEventHandler) - * @see ManagerReader + * @see ManagerReaderImpl */ - void dispatchEvent(ManagerEvent event) + public void dispatchEvent(ManagerEvent event) { if (event == null) { @@ -578,6 +574,15 @@ public class DefaultManagerConnection im } } } + + if (event instanceof ConnectEvent) + { + setProtocolIdentifier(((ConnectEvent) event).getProtocolIdentifier()); + } + if (event instanceof DisconnectEvent) + { + handleDisconnection(); + } } /** @@ -587,7 +592,7 @@ public class DefaultManagerConnection im * * @param protocolIdentifier the protocol version received by the reader * - * @see ManagerReader + * @see ManagerReaderImpl */ void setProtocolIdentifier(String protocolIdentifier) { @@ -617,9 +622,6 @@ public class DefaultManagerConnection im // clean up at first disconnect(); - // notify event listeners - dispatchEvent(new DisconnectEvent(this.asteriskServer)); - // try to reconnect numTries = 0; while (this.keepAlive) @@ -671,7 +673,10 @@ public class DefaultManagerConnection im { // shouldn't happen logger.error("TimeoutException while trying to log in after reconnect."); - socket.close(); + synchronized (this) + { + socket.close(); + } } } catch (IOException e) |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:00
|
Update of /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560/src/test/net/sf/asterisk/manager Added Files: ManagerWriterImplTest.java ManagerReaderImplTest.java Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) --- NEW FILE: ManagerWriterImplTest.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import org.easymock.MockControl; import net.sf.asterisk.manager.action.StatusAction; import net.sf.asterisk.manager.io.SocketConnectionFacade; import junit.framework.TestCase; public class ManagerWriterImplTest extends TestCase { private ManagerWriter managerWriter; public void setUp() { managerWriter = new ManagerWriterImpl(); } public void testSendActionWithoutSocket() throws Exception { try { managerWriter.sendAction(new StatusAction()); fail("Must throw IllegalStateException"); } catch (IllegalStateException e) { assertTrue("Exception must be of type IllegalStateException", e instanceof IllegalStateException); } } public void testSendAction() throws Exception { MockControl socketMC; SocketConnectionFacade socketConnectionFacade; socketMC = MockControl.createControl(SocketConnectionFacade.class); socketConnectionFacade = (SocketConnectionFacade) socketMC.getMock(); socketConnectionFacade.print("action: Status\r\n\r\n"); socketConnectionFacade.flush(); socketMC.replay(); managerWriter.setSocket(socketConnectionFacade); managerWriter.sendAction(new StatusAction()); socketMC.verify(); } } --- NEW FILE: ManagerReaderImplTest.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import junit.framework.TestCase; import net.sf.asterisk.manager.event.ConnectEvent; import net.sf.asterisk.manager.event.DisconnectEvent; import net.sf.asterisk.manager.event.StatusCompleteEvent; import net.sf.asterisk.manager.io.SocketConnectionFacade; import net.sf.asterisk.manager.response.CommandResponse; import net.sf.asterisk.manager.response.ManagerResponse; import net.sf.asterisk.manager.util.DateUtil; import org.easymock.MockControl; public class ManagerReaderImplTest extends TestCase { private Date now; private MockControl dispatcherMC; private Dispatcher dispatcher; private MockControl socketConnectionFacadeMC; private SocketConnectionFacade socketConnectionFacade; private AsteriskServer asteriskServer; private ManagerReader managerReader; public void setUp() { now = new Date(); DateUtil.overrideCurrentDate(now); asteriskServer = new AsteriskServer(); dispatcherMC = MockControl.createControl(Dispatcher.class); dispatcher = (Dispatcher) dispatcherMC.getMock(); managerReader = new ManagerReaderImpl(dispatcher, asteriskServer); socketConnectionFacadeMC = MockControl.createControl(SocketConnectionFacade.class); socketConnectionFacade = (SocketConnectionFacade) socketConnectionFacadeMC.getMock(); } public void testRunWithoutSocket() throws Exception { try { managerReader.run(); fail("Must throw IllegalStateException"); } catch (IllegalStateException e) { assertTrue("Exception must be of type IllegalStateException", e instanceof IllegalStateException); } } public void testRunReceivingProtocolIdentifier() throws Exception { ConnectEvent connectEvent; DisconnectEvent disconnectEvent; socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Asterisk Call Manager/1.0"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(null); connectEvent = new ConnectEvent(asteriskServer); connectEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); connectEvent.setDateReceived(now); dispatcher.dispatchEvent(connectEvent); disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(now); dispatcher.dispatchEvent(disconnectEvent); socketConnectionFacadeMC.replay(); dispatcherMC.replay(); managerReader.setSocket(socketConnectionFacade); managerReader.run(); socketConnectionFacadeMC.verify(); dispatcherMC.verify(); } public void testRunReceivingEvent() throws Exception { DisconnectEvent disconnectEvent; StatusCompleteEvent statusCompleteEvent; socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Event: StatusComplete"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(""); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(null); statusCompleteEvent = new StatusCompleteEvent(asteriskServer); statusCompleteEvent.setDateReceived(now); dispatcher.dispatchEvent(statusCompleteEvent); disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(now); dispatcher.dispatchEvent(disconnectEvent); socketConnectionFacadeMC.replay(); dispatcherMC.replay(); managerReader.setSocket(socketConnectionFacade); managerReader.run(); socketConnectionFacadeMC.verify(); dispatcherMC.verify(); } public void testRunReceivingResponse() throws Exception { DisconnectEvent disconnectEvent; ManagerResponse response; socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Response: Success"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Message: Authentication accepted"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(""); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(null); response = new ManagerResponse(); response.setResponse("Success"); response.setMessage("Authentication accepted"); response.setDateReceived(now); dispatcher.dispatchResponse(response); disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(now); dispatcher.dispatchEvent(disconnectEvent); socketConnectionFacadeMC.replay(); dispatcherMC.replay(); managerReader.setSocket(socketConnectionFacade); managerReader.run(); socketConnectionFacadeMC.verify(); dispatcherMC.verify(); } public void testRunReceivingCommandResponse() throws Exception { DisconnectEvent disconnectEvent; CommandResponse response; List result = new ArrayList(); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Response: Follows"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("ActionID: 12345"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Line1"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("Line2"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue("--END COMMAND--"); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(""); socketConnectionFacade.readLine(); socketConnectionFacadeMC.setReturnValue(null); response = new CommandResponse(); response.setResponse("Follows"); response.setActionId("12345"); result.add("Line1"); result.add("Line2"); response.setResult(result); response.setDateReceived(now); dispatcher.dispatchResponse(response); disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(now); dispatcher.dispatchEvent(disconnectEvent); socketConnectionFacadeMC.replay(); dispatcherMC.replay(); managerReader.setSocket(socketConnectionFacade); managerReader.run(); socketConnectionFacadeMC.verify(); dispatcherMC.verify(); } public void testRunCatchingIOException() throws Exception { DisconnectEvent disconnectEvent; socketConnectionFacade.readLine(); socketConnectionFacadeMC.setThrowable(new IOException("Something happened to the network...")); disconnectEvent = new DisconnectEvent(asteriskServer); disconnectEvent.setDateReceived(now); dispatcher.dispatchEvent(disconnectEvent); socketConnectionFacadeMC.replay(); dispatcherMC.replay(); managerReader.setSocket(socketConnectionFacade); managerReader.run(); socketConnectionFacadeMC.verify(); dispatcherMC.verify(); } } |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:00
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/io In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560/src/java/net/sf/asterisk/manager/io Added Files: SocketConnectionFacade.java SocketConnectionFacadeImpl.java Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) --- NEW FILE: SocketConnectionFacade.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager.io; import java.io.IOException; public interface SocketConnectionFacade { String readLine() throws IOException; void print(String s) throws IOException; void flush() throws IOException; void close() throws IOException; } --- NEW FILE: SocketConnectionFacadeImpl.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; public class SocketConnectionFacadeImpl implements SocketConnectionFacade { private final Socket socket; private final BufferedReader reader; private final PrintWriter writer; public SocketConnectionFacadeImpl(String host, int port) throws IOException { this.socket = new Socket(host, port); this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); this.writer = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream())); } public String readLine() throws IOException { return reader.readLine(); } public void print(String s) throws IOException { writer.print(s); } public void flush() throws IOException { writer.flush(); } public void close() throws IOException { this.socket.close(); } } |
From: Stefan R. <sr...@us...> - 2005-03-02 23:16:00
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29560/src/java/net/sf/asterisk/manager/event Modified Files: ConnectEvent.java Log Message: Added unit tests for ManagerReader and ManagerWriter (and did some refactoring to make this work) Index: ConnectEvent.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event/ConnectEvent.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -d -p -r1.2 -r1.3 --- ConnectEvent.java 23 Feb 2005 22:50:58 -0000 1.2 +++ ConnectEvent.java 2 Mar 2005 23:15:50 -0000 1.3 @@ -31,10 +31,35 @@ public class ConnectEvent extends Manage private static final long serialVersionUID = 3257845467831284784L; /** + * The version of the manager protocol. + */ + private String protocolIdentifier; + + /** * @param source */ public ConnectEvent(Object source) { super(source); } + + /** + * Returns the version of the protocol. + * + * @return the version of the protocol. + */ + public String getProtocolIdentifier() + { + return protocolIdentifier; + } + + /** + * Sets the version of the protocol. + * + * @param protocolIdentifier the version of the protocol. + */ + public void setProtocolIdentifier(String protocolIdentifier) + { + this.protocolIdentifier = protocolIdentifier; + } } |
From: Stefan R. <sr...@us...> - 2005-03-02 23:15:24
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/io In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29493/src/java/net/sf/asterisk/manager/io Log Message: Directory /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/io added to the repository |
From: Stefan R. <sr...@us...> - 2005-03-02 23:15:24
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/util In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29493/src/java/net/sf/asterisk/manager/util Log Message: Directory /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/util added to the repository |
From: Jon H. <squ...@us...> - 2005-03-02 18:35:52
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24543/manager Modified Files: EventBuilder.java Log Message: add QueueMemberStatusEvent Index: EventBuilder.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/EventBuilder.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -d -p -r1.6 -r1.7 --- EventBuilder.java 2 Mar 2005 01:57:29 -0000 1.6 +++ EventBuilder.java 2 Mar 2005 18:35:38 -0000 1.7 @@ -53,6 +53,7 @@ import net.sf.asterisk.manager.event.Par import net.sf.asterisk.manager.event.PeerStatusEvent; import net.sf.asterisk.manager.event.QueueEntryEvent; import net.sf.asterisk.manager.event.QueueMemberEvent; +import net.sf.asterisk.manager.event.QueueMemberStatusEvent; import net.sf.asterisk.manager.event.QueueParamsEvent; import net.sf.asterisk.manager.event.RegistryEvent; import net.sf.asterisk.manager.event.ReloadEvent; @@ -117,6 +118,7 @@ public class EventBuilder registerEventClass(PeerStatusEvent.class); registerEventClass(QueueEntryEvent.class); registerEventClass(QueueMemberEvent.class); + registerEventClass(QueueMemberStatusEvent.class); registerEventClass(QueueParamsEvent.class); registerEventClass(RegistryEvent.class); registerEventClass(ReloadEvent.class); |
From: Jon H. <squ...@us...> - 2005-03-02 18:35:49
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24543/manager/event Added Files: QueueMemberStatusEvent.java Log Message: add QueueMemberStatusEvent --- NEW FILE: QueueMemberStatusEvent.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager.event; /** * A QueueMemberStatusEvent shows the status of a QueueMemberEvent * * @author Asteria Solutions Group, Inc. <http://www.asteriasgi.com/> * @version $Id: QueueMemberStatusEvent.java,v 1.1 2005/03/02 18:35:38 squinky86 Exp $ */ public class QueueMemberStatusEvent extends QueueMemberEvent { /** * Serializable version identifier */ private static final long serialVersionUID = -2293926744791895763L; private String status; /** * @param source */ public QueueMemberStatusEvent(Object source) { super(source); } /** * Returns the status. */ public String getStatus() { return status; } /** * Sets the status. */ public void setStatus(String status) { this.status = status; } } |
From: Stefan R. <sr...@us...> - 2005-03-02 11:33:26
|
Update of /cvsroot/asterisk-java/asterisk-java In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4336 Modified Files: .cvsignore Log Message: Added .project and .classpath Index: .cvsignore =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/.cvsignore,v retrieving revision 1.2 retrieving revision 1.3 diff -u -d -p -r1.2 -r1.3 --- .cvsignore 23 Feb 2005 12:42:32 -0000 1.2 +++ .cvsignore 2 Mar 2005 11:33:06 -0000 1.3 @@ -5,3 +5,5 @@ bin .externalToolBuilders velocity.log target +.classpath +.project |
From: Stefan R. <sr...@us...> - 2005-03-02 11:27:40
|
Update of /cvsroot/asterisk-java/asterisk-java In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv2433 Removed Files: .classpath .project Log Message: - removed eclipse specific files (can be easily generated by "maven eclipse" --- .classpath DELETED --- --- .project DELETED --- |
From: Stefan R. <sr...@us...> - 2005-03-02 01:57:43
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/event In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23220/src/java/net/sf/asterisk/manager/event Added Files: DialEvent.java Log Message: Added DialEvent (Patch #1154463) --- NEW FILE: DialEvent.java --- /* * Copyright 2004-2005 Stefan Reuter * * 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 net.sf.asterisk.manager.event; /** * A dial event is triggered whenever a phone attempts to dial someone.<br> * This event is implemented in <code>apps/app_dial.c</code> * * @author Asteria Solutions Group, Inc. <http://www.asteriasgi.com/> * @version $Id: DialEvent.java,v 1.1 2005/03/02 01:57:29 srt Exp $ */ public class DialEvent extends ManagerEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 3258130241292417336L; /** * The name of the source channel. */ private String src; /** * The name of the destination channel. */ private String destination; /** * The new Caller*ID. */ private String callerId; /** * The new Caller*ID Name. */ private String callerIdName; /** * The unique id of the source channel. */ private String srcUniqueId; /** * The unique id of the destination channel. */ private String destUniqueId; /** * @param source */ public DialEvent(Object source) { super(source); } /** * Returns the name of the source channel. * * @return the name of the source channel. */ public String getSrc() { return src; } /** * Sets the name of the source channel. * * @param source the name of the source channel. */ public void setSrc(String src) { this.src = src; } /** * Returns the name of the destination channel. * * @return the name of the destination channel. */ public String getDestination() { return destination; } /** * Sets the name of the destination channel. * * @param destination the name of the destination channel. */ public void setDestination(String destination) { this.destination = destination; } /** * Returns the Caller*ID. * * @return the Caller*ID. */ public String getCallerId() { return callerId; } /** * Sets the caller*ID. * * @param callerId the caller*ID. */ public void setCallerId(String callerid) { this.callerId = callerid; } /** * Returns the Caller*ID Name. * * @return the Caller*ID Name. */ public String getCallerIdName() { return callerIdName; } /** * Sets the callerId name. */ public void setCallerIdName(String calleridname) { this.callerIdName = calleridname; } /** * Returns the unique ID of the source channel. * * @return the unique ID of the source channel. */ public String getSrcUniqueId() { return srcUniqueId; } /** * Sets the unique ID of the source channel. * * @param srcUniqueId the unique ID of the source channel. */ public void setSrcUniqueId(String srcuniqueid) { this.srcUniqueId = srcuniqueid; } /** * Returns the unique ID of the deistination channel. * * @return the unique ID of the deistination channel. */ public String getDestUniqueId() { return destUniqueId; } /** * Sets the unique ID of the distination channel. * * @param destUniqueId the unique ID of the distination channel. */ public void setDestUniqueId(String destuniqueid) { this.destUniqueId = destuniqueid; } } |
From: Stefan R. <sr...@us...> - 2005-03-02 01:57:43
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23220/src/java/net/sf/asterisk/manager Modified Files: EventBuilder.java Log Message: Added DialEvent (Patch #1154463) Index: EventBuilder.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/EventBuilder.java,v retrieving revision 1.5 retrieving revision 1.6 diff -u -d -p -r1.5 -r1.6 --- EventBuilder.java 2 Mar 2005 00:38:18 -0000 1.5 +++ EventBuilder.java 2 Mar 2005 01:57:29 -0000 1.6 @@ -31,6 +31,7 @@ import net.sf.asterisk.manager.event.Age import net.sf.asterisk.manager.event.AlarmClearEvent; import net.sf.asterisk.manager.event.AlarmEvent; import net.sf.asterisk.manager.event.CdrEvent; +import net.sf.asterisk.manager.event.DialEvent; import net.sf.asterisk.manager.event.ExtensionStatusEvent; import net.sf.asterisk.manager.event.HangupEvent; import net.sf.asterisk.manager.event.HoldedCallEvent; @@ -95,6 +96,7 @@ public class EventBuilder registerEventClass(AlarmEvent.class); registerEventClass(AlarmClearEvent.class); registerEventClass(CdrEvent.class); + registerEventClass(DialEvent.class); registerEventClass(ExtensionStatusEvent.class); registerEventClass(HangupEvent.class); registerEventClass(HoldedCallEvent.class); |
From: Stefan R. <sr...@us...> - 2005-03-02 00:38:42
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30471/src/java/net/sf/asterisk/manager Modified Files: EventBuilder.java Log Message: Changed logging of event registration to debug Index: EventBuilder.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/EventBuilder.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -d -p -r1.4 -r1.5 --- EventBuilder.java 1 Mar 2005 19:24:35 -0000 1.4 +++ EventBuilder.java 2 Mar 2005 00:38:18 -0000 1.5 @@ -187,7 +187,7 @@ public class EventBuilder registeredEventClasses.put(eventType.toLowerCase(), clazz); - logger.info("Registered event type '" + eventType + "' (" + clazz + ")"); + logger.debug("Registered event type '" + eventType + "' (" + clazz + ")"); } public ManagerEvent buildEvent(Object source, Map attributes) |
From: Stefan R. <sr...@us...> - 2005-03-02 00:38:01
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30168/src/java/net/sf/asterisk/manager Modified Files: DefaultManagerConnection.java Log Message: Synchronized access to socket and writer Index: DefaultManagerConnection.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/DefaultManagerConnection.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -d -p -r1.2 -r1.3 --- DefaultManagerConnection.java 23 Feb 2005 22:50:57 -0000 1.2 +++ DefaultManagerConnection.java 2 Mar 2005 00:37:38 -0000 1.3 @@ -53,6 +53,9 @@ import org.apache.commons.logging.LogFac */ public class DefaultManagerConnection implements ManagerConnection { + /** + * Instance logger. + */ private final Log logger = LogFactory.getLog(getClass()); private long actionIdCount = 0; @@ -70,7 +73,6 @@ public class DefaultManagerConnection im private PrintWriter writer; private ActionBuilder actionBuilder = new ActionBuilder(); private String protocolIdentifier; - private String challenge; private Map responseHandlers = new HashMap(); private Collection eventHandlers = new HashSet(); private boolean keepAlive = false; @@ -175,7 +177,7 @@ public class DefaultManagerConnection im * login is delayed until the protocol identifier has been received by the reader. * * @throws AuthenticationFailedException if the username and/or password are incorrect - * @throws TimeoutException if there no response is received within the specified timeout period + * @throws TimeoutException if no response is received within the specified timeout period * * @see ChallengeAction * @see LoginAction @@ -185,15 +187,34 @@ public class DefaultManagerConnection im login(defaultTimeout); } + /** + * Does the real login, following the steps outlined below.<br> + * <ol> + * <li>Connects to the asterisk server by calling {@link #connect()} if not already connected + * <li>Waits until the protocol identifier is received. This is checked every + * {@link #sleepTime} ms but not longer than timeout ms in total. + * <li>Sends a {@link ChallengeAction} requesting a challenge for authType MD5. + * <li>When the {@link ChallengeResponse} is received a {@link LoginAction} is sent using the + * calculated key (MD5 hash of the password appended to the received challenge). + * </ol> + * + * @param timeout the maximum time to wait for the protocol identifier (in ms) + * @throws AuthenticationFailedException if username or password are incorrect and the login + * action returns an error or if the MD5 hash cannot be computed. The connection is closed in + * this case. + * @throws TimeoutException if a timeout occurs either while waiting for the protocol identifier + * or when sending the challenge or login action. The connection is closed in this case. + */ private void login(long timeout) throws IOException, AuthenticationFailedException, TimeoutException { long timeSpent; ChallengeAction challengeAction; ChallengeResponse challengeResponse; + String challenge; LoginAction loginAction; ManagerResponse loginResponse; - if (socket == null) + if (!isConnected()) { connect(); } @@ -236,7 +257,6 @@ public class DefaultManagerConnection im } catch (NoSuchAlgorithmException ex) { - logger.error("Unable to create login key using MD5 Message Digest", ex); disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } @@ -244,7 +264,6 @@ public class DefaultManagerConnection im loginResponse = sendAction(loginAction); if (loginResponse instanceof ManagerError) { - logger.info("Authentication failed: " + loginResponse.getMessage()); disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } @@ -259,7 +278,7 @@ public class DefaultManagerConnection im dispatchEvent(new ConnectEvent(this.asteriskServer)); } - private void connect() throws IOException + private synchronized void connect() throws IOException { BufferedReader bufferedReader; @@ -274,7 +293,23 @@ public class DefaultManagerConnection im this.writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); } - public void logoff() throws IOException, TimeoutException + /** + * Returns <code>true</code> if there is a socket connection to the asterisk server, + * <code>false</code> otherwise. + * + * @return <code>true</code> if there is a socket connection to the asterisk server, + * <code>false</code> otherwise. + */ + protected synchronized boolean isConnected() + { + // return socket != null && socket.isConnected(); // JDK 1.4 + return socket != null; + } + + /** + * Sends a {@link LogoffAction} and disconnects from the server. + */ + public synchronized void logoff() throws IOException, TimeoutException { LogoffAction logoffAction; @@ -282,12 +317,15 @@ public class DefaultManagerConnection im this.keepAlive = false; logoffAction = new LogoffAction(); - sendAction(logoffAction); - - disconnect(); + + if (isConnected()) + { + sendAction(logoffAction); + disconnect(); + } } - private void disconnect() + private synchronized void disconnect() { if (this.writer != null) { @@ -351,6 +389,7 @@ public class DefaultManagerConnection im public void sendAction(ManagerAction action, ManagerResponseHandler callbackHandler) throws IOException { String internalActionId; + String actionString; if (action == null) { @@ -377,16 +416,21 @@ public class DefaultManagerConnection im } } - synchronized (this.writer) + actionString = actionBuilder.buildAction(action); + + synchronized (this) { - String actionString; + if (!isConnected()) + { + throw new IllegalStateException("Unable to send " + action.getAction() + " action: not connected."); + } - actionString = actionBuilder.buildAction(action); this.writer.print(actionString); this.writer.flush(); - - logger.debug("Sent action with internalActionId '" + internalActionId + "':\n" + actionString); } + + logger.debug("Sent " + action.getAction() + " action with internalActionId '" + internalActionId + "':\n" + + actionString); } /** @@ -547,7 +591,7 @@ public class DefaultManagerConnection im */ void setProtocolIdentifier(String protocolIdentifier) { - logger.debug("Received protocol identifier '" + protocolIdentifier + "'"); + logger.info("Connected via " + protocolIdentifier); if (!"Asterisk Call Manager/1.0".equals(protocolIdentifier)) { |
From: Stefan R. <sr...@us...> - 2005-03-02 00:37:30
|
Update of /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29838/src/java/net/sf/asterisk/manager Modified Files: ManagerReader.java Log Message: Moved handleDisconnection to finally block Index: ManagerReader.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/java/net/sf/asterisk/manager/ManagerReader.java,v retrieving revision 1.4 retrieving revision 1.5 diff -u -d -p -r1.4 -r1.5 --- ManagerReader.java 1 Mar 2005 19:25:35 -0000 1.4 +++ ManagerReader.java 2 Mar 2005 00:37:03 -0000 1.5 @@ -57,8 +57,8 @@ class ManagerReader extends Thread private EventBuilder eventBuilder; /** - * The response builder utility to convert a map of attributes reveived from asterisk to instances - * of well known response classes. + * The response builder utility to convert a map of attributes reveived from asterisk to + * instances of well known response classes. */ private ResponseBuilder responseBuilder; @@ -130,7 +130,7 @@ class ManagerReader extends Thread } continue; } - + // Reponse: Follows indicates that the output starting on the next line until // --END COMMAND-- must be treated as raw output of a command executed by a // CommandAction. @@ -189,8 +189,6 @@ class ManagerReader extends Thread } } } - - connection.handleDisconnection(); } catch (IOException e) { @@ -198,7 +196,7 @@ class ManagerReader extends Thread } finally { - log.info("Disconnected, closing reader"); + log.info("Disconnected, closing reader."); try { reader.close(); @@ -207,6 +205,9 @@ class ManagerReader extends Thread { log.warn("Unable to close reader", ex); } + + // cleans resources and reconnects if needed + connection.handleDisconnection(); } } |
From: Stefan R. <sr...@us...> - 2005-03-02 00:35:50
|
Update of /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29317/src/test/net/sf/asterisk/manager Modified Files: TestDefaultManagerConnection.java Log Message: Added testLoginAuthenticationFailure Index: TestDefaultManagerConnection.java =================================================================== RCS file: /cvsroot/asterisk-java/asterisk-java/src/test/net/sf/asterisk/manager/TestDefaultManagerConnection.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -d -p -r1.1 -r1.2 --- TestDefaultManagerConnection.java 23 Feb 2005 12:45:23 -0000 1.1 +++ TestDefaultManagerConnection.java 2 Mar 2005 00:35:36 -0000 1.2 @@ -19,6 +19,7 @@ public class TestDefaultManagerConnectio { DefaultManagerConnection dmc; +// dmc = new DefaultManagerConnection("deprecated", 5038, "manager", "obelisk"); dmc = new DefaultManagerConnection(); dmc.setUsername("manager"); dmc.setPassword("obelisk"); @@ -46,4 +47,22 @@ public class TestDefaultManagerConnectio Thread.sleep(3000); dmc.logoff(); } + + public void testLoginAuthenticationFailure() throws Exception + { + DefaultManagerConnection dmc; + + dmc = getDefaultManagerConnection(); + dmc.setPassword(""); + + try + { + dmc.login(); + fail("No AuthenticationFailedException received."); + } + catch (AuthenticationFailedException e) + { + } + dmc.logoff(); + } } |